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): redesign date and time pickers (#43090)
yyh90f7fbd468c4
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 55740edb20c..3d9137c4231 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -838,24 +838,6 @@"count": 10}},- "web/app/components/base/date-and-time-picker/hooks.ts": {- "eslint-react/no-unnecessary-use-prefix": {- "count": 2- }- },- "web/app/components/base/date-and-time-picker/time-picker/index.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },- "web/app/components/base/date-and-time-picker/utils/dayjs.ts": {- "no-barrel-files/no-barrel-files": {- "count": 1- }- },"web/app/components/base/error-boundary/index.tsx": {"react/only-export-components": {"count": 1@@ -1098,7 +1080,7 @@},"web/app/components/base/markdown-blocks/index.ts": {"no-barrel-files/no-barrel-files": {- "count": 10+ "count": 9}},"web/app/components/base/markdown-blocks/link.tsx": {diff --git a/packages/dify-ui/README.md b/packages/dify-ui/README.mdindex 318fd307797..b4e5fc1179d 100644--- a/packages/dify-ui/README.md+++ b/packages/dify-ui/README.md@@ -45,10 +45,12 @@ Import `styles.css` once from the consumer's root stylesheet or entrypoint.| Media | `./avatar` || Navigation | `./breadcrumb`, `./file-tree`, `./pagination`, `./tabs` || Overlay and menu | `./alert-dialog`, `./context-menu`, `./dialog`, `./drawer`, `./dropdown-menu`, `./infotip`, `./popover`, `./preview-card`, `./tooltip` |-| Search and pick | `./autocomplete`, `./combobox`, `./select` |+| Search and pick | `./autocomplete`, `./combobox`, `./select`, `./date-picker`, `./time-picker`, `./date-time-picker` |Utilities:+- `./direction-provider` exports Base UI `DirectionProvider` and `useDirection`. Set HTML `dir` as well for CSS layout; pickers propagate their resolved direction to their trigger and portaled content.+- `./cn` re-exports `cn` from the `cn` package through Dify UI's public subpath.- `./styles.css` provides design tokens, theme variables, and shared utilities.@@ -60,12 +62,13 @@ Upstream behavior remains owned by the [Base UI documentation].### Component guides-| Guide | Dify-owned contract |-| ------------- | ------------------------------------------------------------------------------------------- |-| [Button] | Action semantics, submit and link choices, loading versus disabled, and content spacing. |-| [Icon Button] | Accessible names, decorative glyphs, appearance ownership, and primitive composition. |-| [Infotip] | Explanation triggers, concise dialog names, and hint surface ownership. |-| [Input Group] | Compound input anatomy, shared-surface ownership, DOM order, focus, and interactive addons. |+| Guide | Dify-owned contract |+| ----------------------- | ------------------------------------------------------------------------------------------- |+| [Date and time pickers] | Value semantics, composition, draft commits, localization and native forms. |+| [Button] | Action semantics, submit and link choices, loading versus disabled, and content spacing. |+| [Icon Button] | Accessible names, decorative glyphs, appearance ownership, and primitive composition. |+| [Infotip] | Explanation triggers, concise dialog names, and hint surface ownership. |+| [Input Group] | Compound input anatomy, shared-surface ownership, DOM order, focus, and interactive addons. |### Cross-component guides@@ -88,6 +91,7 @@ For a known contract, go directly to its guide above.[Base UI documentation]: https://base-ui.com/llms.txt[Base UI]: https://base-ui.com/react[Button]: ./src/button/README.md+[Date and time pickers]: ./src/date-time/README.md[Forms]: ./docs/forms.md[Icon Button]: ./src/icon-button/README.md[Infotip]: ./src/infotip/README.mddiff --git a/packages/dify-ui/docs/forms.md b/packages/dify-ui/docs/forms.mdindex 862b207ed74..1a7ea99249f 100644--- a/packages/dify-ui/docs/forms.md+++ b/packages/dify-ui/docs/forms.md@@ -44,6 +44,9 @@ Choose the label primitive by the control:- Text-like inputs, `Textarea`, input-based `Combobox` and `Autocomplete`, a single `Checkbox`,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].- `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. They@@ -85,3 +88,4 @@ public field and control props instead of replacing the semantic structure.[Base UI forms handbook]: https://base-ui.com/react/handbook/forms[`Button`]: ../src/button/README.md[`InputGroup`]: ../src/input-group/README.md+[picker field contract]: ../src/date-time/README.md#anatomy-and-labelsdiff --git a/packages/dify-ui/docs/selection.md b/packages/dify-ui/docs/selection.mdindex 2edcabc3ca1..167622ceadf 100644--- a/packages/dify-ui/docs/selection.md+++ b/packages/dify-ui/docs/selection.md@@ -13,6 +13,8 @@ domain value type through its public API.- [`Autocomplete`] accepts free-form text with optional suggestions.- [`Combobox`] selects and remembers one or more values from a searchable collection.- [`Select`] chooses from a closed, scannable list without text entry.+- [Date and time pickers] select civil dates, wall times or instants. Their fixed value models+ do not use collection generics; the family guide owns anatomy and commit semantics.Multiple-selection comboboxes follow the Base UI chips composition: chips and the input share theinput group, chips wrap, and the group grows vertically.@@ -149,6 +151,7 @@ current result window, or provide an ID-only label fallback.`CheckboxGroup` follows Base UI and uses `string[]`. Model stronger business ID distinctions atthe domain boundary unless the upstream primitive contract changes.+[Date and time pickers]: ../src/date-time/README.md[`Autocomplete`]: https://base-ui.com/react/components/autocomplete[`Combobox`]: https://base-ui.com/react/components/combobox[`RadioGroup`]: https://base-ui.com/react/components/radiodiff --git a/packages/dify-ui/docs/testing.md b/packages/dify-ui/docs/testing.mdindex ee774f381b3..9c565385497 100644--- a/packages/dify-ui/docs/testing.md+++ b/packages/dify-ui/docs/testing.md@@ -36,6 +36,19 @@ Color contrast is the only globally disabled rule because it is a known design-tadd another global exception. Keep a temporary exception local to the affected story, and do notuse a `play` test in place of an accessibility fix.+## Type contracts++Keep compile-only public API fixtures in `__tests__/types.tsx`; package type checking includes them+without registering runtime tests. Import public subpaths, verify useful inference with+`expectTypeOf`, and use `@ts-expect-error` for intentional API boundaries. Cover nullable callbacks,+value models and unsupported composition, not every forwarded prop. Runtime assertions cannot+prove TypeScript inference, and type fixtures cannot prove focus, DOM semantics or interaction.++A documented example and its `play` belong in one story; do not create an automatic duplicate just+to run the same render. Keep Docs autoplay off for examples that move focus or open portals. Retain+explicit open previews when needed for accessibility checks on popup content. Regressions that do+not teach a distinct usage belong in the unit project rather than extra sidebar entries.+## Animation setupBase UI can wait for `element.getAnimations()` before unmounting transition-driven components.diff --git a/packages/dify-ui/package.json b/packages/dify-ui/package.jsonindex 737f6f09ee4..9ef9a16d00f 100644--- a/packages/dify-ui/package.json+++ b/packages/dify-ui/package.json@@ -61,6 +61,14 @@"types": "./src/dialog/index.tsx","import": "./src/dialog/index.tsx"},+ "./date-picker": {+ "types": "./src/date-time/date-picker/index.tsx",+ "import": "./src/date-time/date-picker/index.tsx"+ },+ "./date-time-picker": {+ "types": "./src/date-time/date-time-picker/index.tsx",+ "import": "./src/date-time/date-time-picker/index.tsx"+ },"./drawer": {"types": "./src/drawer/index.tsx","import": "./src/drawer/index.tsx"@@ -157,6 +165,10 @@"types": "./src/textarea/index.tsx","import": "./src/textarea/index.tsx"},+ "./time-picker": {+ "types": "./src/date-time/time-picker/index.tsx",+ "import": "./src/date-time/time-picker/index.tsx"+ },"./toast": {"types": "./src/toast/index.tsx","import": "./src/toast/index.tsx"@@ -176,6 +188,10 @@"./infotip": {"types": "./src/infotip/index.tsx","import": "./src/infotip/index.tsx"+ },+ "./direction-provider": {+ "types": "./src/direction-provider/index.tsx",+ "import": "./src/direction-provider/index.tsx"}},"scripts": {@@ -188,7 +204,10 @@},"dependencies": {"@base-ui/utils": "catalog:",- "cn": "catalog:"+ "@date-fns/tz": "catalog:",+ "@daypicker/react": "catalog:",+ "cn": "catalog:",+ "date-fns": "catalog:"},"devDependencies": {"@base-ui/react": "catalog:",diff --git a/packages/dify-ui/src/date-time/README.md b/packages/dify-ui/src/date-time/README.mdnew file mode 100644index 00000000000..48a4dbc03b8--- /dev/null+++ b/packages/dify-ui/src/date-time/README.md@@ -0,0 +1,144 @@+# Date and time pickers++These three families share field anatomy, a non-modal popover and keyboard navigation. Choose+from the value's meaning; they do not accept free-form text or arbitrary collection values.++| Public subpath | Value / `onValueChange` | Native form value | Selection commits |+| -------------------------------------- | ---------------------------------------- | ------------------- | ----------------- |+| `@langgenius/dify-ui/date-picker` | `string \| null`, Gregorian `YYYY-MM-DD` | `YYYY-MM-DD` | Selecting a day |+| `@langgenius/dify-ui/time-picker` | `string \| null`, 24-hour `HH:mm` | `HH:mm` | OK |+| `@langgenius/dify-ui/date-time-picker` | `Date \| null`, an instant | ISO 8601 UTC string | OK |++`DateTimePicker` requires an IANA `timeZone` for display and editing. `TimePicker.timeZone` only+controls Now and the initial empty draft; it never converts a stored wall time. Date-only values+have no time zone. Parse API payloads and perform business conversions outside this package.+These fixed value models do not need generics. The public prop types own the complete API.++## Anatomy and labels++Each subpath exports its root, Label, Trigger, Value, Clear, Content and corresponding prop types.+Use one family consistently:++```tsx+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@langgenius/dify-ui/date-picker'++;<form>+ <DatePicker name="start" defaultValue="2025-01-15">+ <DatePickerLabel>Start date</DatePickerLabel>+ <div className="flex items-center gap-1">+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear start date" />+ </div>+ <DatePickerContent />+ </DatePicker>+</form>+```++Provide an accessible name at the call site. Root has no labeling props and does not enforce+Label composition through its types. Prefer one visible Label with its text as children; it names+both Trigger and Content through `aria-labelledby`. Clicking plain label text focuses the actual+trigger 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.++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:++```tsx+<DatePicker>+ <DatePickerTrigger aria-label="Start date" aria-describedby="start-help" />+ <DatePickerContent aria-label="Choose start date" />+</DatePicker>+```++External text can name both parts through `aria-labelledby`; click forwarding remains with its+owner. Explicit names override the automatic Label association. When a Trigger references label+text, its committed Value is appended to the name. An explicit `aria-label` supplies the whole name.+Trigger's `aria-describedby` is combined with required and validation feedback. Do not rely on+placeholder or selected text alone to identify the field.++Trigger is a native button. Its default children contain Value and a decorative icon. If replacing+those children, include exactly one Value; its render callback receives the formatted committed+text (or the placeholder), not the raw value. Put meaningful annotations such as a time-zone suffix+inside Value so they participate in the accessible name. Keep decorative icons `aria-hidden`.+Clear inherits IconButton's `aria-label` / `aria-labelledby` naming contract. Trigger and Clear may+share a visual field container; their placement is caller-owned. Do not nest Clear inside the+native Trigger button.++Content owns the portal, initial focus, calendar, columns and actions. Its props derive from the+Dify Popover content contract, excluding replacement children, `render` and `initialFocus`.+Use `className`/`style` for deliberate presentation overrides. Normal content keeps its natural+height, including the calendar's week count, and flips above or below its trigger. It does not+shrink itself on mobile. An explicit `maxHeight` opts into scrolling the body/columns while keeping+actions visible. A viewport too short for natural content needs a consumer layout decision.++## State and interaction++Use `defaultValue` for uncontrolled fields or `value` with `onValueChange` for controlled fields.+`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()`.++Time and date-time edits, including Now, stay in the open session until OK. Switching date/time+views 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+emit a duplicate value change. In DatePicker, a day selection commits immediately. The month/year+selector only changes the displayed month when confirmed; it does not select a date.++The calendar uses DayPicker's grid navigation. Adjacent-month dates remain selectable and, while+the popup remains open, switch the view to their month. `minDate`, `maxDate` and+`isDateUnavailable` restrict dates. Time availability is evaluated on the complete combination:+intermediate unavailable drafts remain navigable, but OK is disabled with an announced message.++Time and month/year columns use single-select listboxes with `aria-selected` and roving DOM focus.+Selection follows focus within the draft, not the committed field value:++- Up/Down move one option; Page Up/Down move five; Home/End reach the endpoints. Navigation clamps+ at the ends; no `loopFocus` API is exposed.+- Numeric locating accepts ASCII and localized digits. Month names also support typeahead.+- Tab moves between columns and actions, not every option. Escape leaves month/year selection+ first; Escape from the main picker dismisses and restores trigger focus. Tab can leave the popup.+- Hover does not select. Keyboard changes scroll immediately; pointer selection may scroll+ smoothly, respecting reduced motion. Wheel/touch scrolling updates the draft and aligns the+ nearest option at the top when it settles.++`hourCycle` selects 12-hour (default) or 24-hour display; stored wall time remains 24-hour.+TimePicker alone supports `minuteStep` (1, 5, 10, 15, 20 or 30; default 1). Now rounds down to that+step. DateTimePicker edits whole minutes, rejects nonexistent daylight-saving times, preserves an+unchanged instant (including a repeated time), and resolves an edited ambiguous time to the earlier+instant. Business rules can further restrict it through `isTimeUnavailable`.++## Localization and native forms++DatePicker and DateTimePicker accept DayPicker locale objects; TimePicker accepts Intl locale+identifiers. Locale controls formatting and digits, not the calendar system or serialized values.+Action labels and validation copy have English defaults; consumers translate `labels`, field and+clear labels, placeholders, `requiredLabel` and `validationMessage`. Direction inherits+`DirectionProvider` or a local `direction` override and reaches the portaled popup independently of+locale. Set HTML `dir` for the surrounding layout too.++With `name`, the committed value participates in native FormData; an empty field submits `''`.+`form` can associate an external form. Required/invalid fields block native validated submission+and focus the first invalid trigger. Reset restores `defaultValue` and closes the popup; a+controlled 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.++## Examples and verification++The colocated stories own documented configurations and primary interaction flows. Docs leave+popups closed; explicit open previews exercise calendar, month/year and time content with the+configured axe checks. Use the Storybook theme toolbar for light/dark inspection.++Browser unit tests own regressions: label composition, controlled sessions, date constraints,+scroll interruption, sizing, localized input and daylight-saving conversion. The shared+`__tests__/types.tsx` fixture checks public imports, inferred values, nullable callbacks and rejected+configurations during type checking; it is not a runtime test. See [Testing] for commands and+ownership. Automated axe and Chromium tests do not replace physical touch and screen-reader checks.++[Forms]: ../../docs/forms.md+[Testing]: ../../docs/testing.mddiff --git a/packages/dify-ui/src/date-time/__tests__/label.spec.tsx b/packages/dify-ui/src/date-time/__tests__/label.spec.tsxnew file mode 100644index 00000000000..bfc6b98380c--- /dev/null+++ b/packages/dify-ui/src/date-time/__tests__/label.spec.tsx@@ -0,0 +1,199 @@+import type * as React from 'react'+import {+ DatePicker,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@langgenius/dify-ui/date-picker'+import {+ DateTimePicker,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '@langgenius/dify-ui/date-time-picker'+import {+ TimePicker,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+} from '@langgenius/dify-ui/time-picker'+import { createPortal } from 'react-dom'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'++const pickers = [+ {+ name: 'DatePicker',+ wrap: (children: React.ReactNode) => <DatePicker>{children}</DatePicker>,+ Label: DatePickerLabel,+ Trigger: DatePickerTrigger,+ Content: DatePickerContent,+ },+ {+ name: 'TimePicker',+ wrap: (children: React.ReactNode) => <TimePicker>{children}</TimePicker>,+ Label: TimePickerLabel,+ Trigger: TimePickerTrigger,+ Content: TimePickerContent,+ },+ {+ name: 'DateTimePicker',+ wrap: (children: React.ReactNode) => <DateTimePicker timeZone="UTC">{children}</DateTimePicker>,+ Label: DateTimePickerLabel,+ Trigger: DateTimePickerTrigger,+ Content: DateTimePickerContent,+ },+]++it.each(pickers)(+ '$name label focuses only from its text and preserves a nested action',+ async ({ wrap, Label, Trigger, Content }) => {+ const help = vi.fn()+ const screen = await render(+ wrap(+ <>+ <Label>+ <span>Departure</span>+ <button type="button" onClick={help}>+ <span>Help</span>+ </button>+ </Label>+ <Trigger />+ <Content />+ </>,+ ),+ )+ const trigger = screen.getByRole('button', { name: 'Departure Help' })+ await screen.getByText('Departure', { exact: true }).click()+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'false')++ const action = screen.getByRole('button', { name: 'Help', exact: true })+ await screen.getByText('Help', { exact: true }).click()+ await expect.element(action).toHaveFocus()+ expect(help).toHaveBeenCalledTimes(1)+ await userEvent.keyboard('{Enter}')+ expect(help).toHaveBeenCalledTimes(2)+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()++ await userEvent.tab()+ await expect.element(trigger).toHaveFocus()+ await userEvent.keyboard('{Enter}')+ await expect.element(screen.getByRole('dialog', { name: 'Departure Help' })).toBeInTheDocument()+ },+)++it('preserves native focus and typing in label children', async () => {+ const screen = await render(+ <DatePicker>+ <DatePickerLabel>+ Departure+ <a href="https://example.com/help" onClick={(event) => event.preventDefault()}>+ Help+ </a>+ <input aria-label="Note" />+ </DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>,+ )+ const link = screen.getByRole('link', { name: 'Help' })+ await link.click()+ await expect.element(link).toHaveFocus()+ const input = screen.getByRole('textbox', { name: 'Note' })+ await input.click()+ await expect.element(input).toHaveFocus()+ await userEvent.keyboard('Booking')+ await expect.element(input).toHaveValue('Booking')+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+})++it('does not forward clicks from portalled label content to the trigger', async () => {+ const screen = await render(+ <DatePicker>+ <DatePickerLabel>+ Departure+ {createPortal(<input aria-label="Help search" />, document.body)}+ </DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>,+ )+ const input = screen.getByRole('textbox', { name: 'Help search' })+ await input.click()+ await expect.element(input).toHaveFocus()+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+})++it('allows a consumer to cancel label focus forwarding', async () => {+ const screen = await render(+ <>+ <button type="button">Previous control</button>+ <DatePicker>+ <DatePickerLabel onClick={(event) => event.preventDefault()}>Departure</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </>,+ )+ const previous = screen.getByRole('button', { name: 'Previous control' })+ await previous.click()+ await screen.getByText('Departure', { exact: true }).click()+ await expect.element(previous).toHaveFocus()+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+})++it.each(pickers)(+ '$name supports explicitly named parts without a Label',+ async ({ wrap, Trigger, Content }) => {+ const screen = await render(+ wrap(+ <>+ <Trigger aria-label="Departure" />+ <Content aria-label="Choose departure" />+ </>,+ ),+ )+ const trigger = screen.getByRole('button', { name: 'Departure' })+ await trigger.click()+ await expect.element(screen.getByRole('dialog', { name: 'Choose departure' })).toBeVisible()+ await userEvent.keyboard('{Escape}')+ await expect.element(trigger).toHaveFocus()+ },+)++it('combines external label, value and descriptions without losing validation feedback', async () => {+ const screen = await render(+ <>+ <span id="departure-label">Departure</span>+ <p id="departure-help">Choose a working day.</p>+ <DatePicker+ defaultValue="2025-01-15"+ required+ invalid+ validationMessage="This date is unavailable."+ >+ <DatePickerTrigger aria-labelledby="departure-label" aria-describedby="departure-help" />+ <DatePickerContent aria-labelledby="departure-label" />+ </DatePicker>+ </>,+ )+ const trigger = screen.getByRole('button', { name: 'Departure Jan 15, 2025' })+ await expect+ .element(trigger)+ .toHaveAccessibleDescription('Choose a working day. Required This date is unavailable.')+ await trigger.click()+ await expect.element(screen.getByRole('dialog', { name: 'Departure' })).toBeVisible()+})++it('honors explicit names when a Label is also composed', async () => {+ const screen = await render(+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel>Departure</DatePickerLabel>+ <DatePickerTrigger aria-label="Departure date" />+ <DatePickerContent aria-label="Choose departure date" />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Departure date' }).click()+ await expect.element(screen.getByRole('dialog', { name: 'Choose departure date' })).toBeVisible()+})diff --git a/packages/dify-ui/src/date-time/__tests__/localization.spec.tsx b/packages/dify-ui/src/date-time/__tests__/localization.spec.tsxnew file mode 100644index 00000000000..85d581cfad4--- /dev/null+++ b/packages/dify-ui/src/date-time/__tests__/localization.spec.tsx@@ -0,0 +1,155 @@+import { arTN } from '@daypicker/react/locale/ar-TN'+import { enUS } from '@daypicker/react/locale/en-US'+import { faIR } from '@daypicker/react/locale/fa-IR'+import { zhCN } from '@daypicker/react/locale/zh-CN'+import * as React from 'react'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { DatePicker, DatePickerContent, DatePickerLabel, DatePickerTrigger } from '../date-picker'+import {+ DateTimePicker,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '../date-time-picker'+import { TimePicker, TimePickerContent, TimePickerLabel, TimePickerTrigger } from '../time-picker'++// Vitest's Playwright provider inserts non-US text without keydown; these dispatches test+// the localized KeyboardEvent contract, not an installed Persian keyboard layout.+async function typeNativeDigits(text: string) {+ for (const key of text) {+ await React.act(() => {+ document.activeElement!.dispatchEvent(+ new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }),+ )+ })+ }+}++it.each([+ [enUS, '15', '2025', '10', '05'],+ [zhCN, '15', '2025', '10', '05'],+ [arTN, '15', '2025', '10', '05'],+ [faIR, '۱۵', '۲۰۲۵', '۱۰', '۰۵'],+] as const)(+ 'uses consistent numerals across date, year and time views for $0.code',+ async (locale, day, year, hour, minute) => {+ const screen = await render(+ <DateTimePicker+ locale={locale}+ timeZone="UTC"+ hourCycle={24}+ defaultValue={new Date('2025-01-15T10:05:00Z')}+ >+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ const trigger = screen.getByRole('button', { name: /^Meeting / })+ await expect.element(trigger).toMatchTextContent(`${hour}:${minute}`)+ await trigger.click()+ await expect.element(screen.getByRole('gridcell', { selected: true })).toHaveTextContent(day)+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await expect+ .element(screen.getByRole('listbox', { name: 'Year' }).getByRole('option', { name: year }))+ .toHaveAttribute('aria-selected', 'true')+ await screen.getByRole('button', { name: 'Cancel', exact: true }).click()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ await expect+ .element(screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: hour }))+ .toHaveAttribute('aria-selected', 'true')+ await expect+ .element(+ screen.getByRole('listbox', { name: 'Minute' }).getByRole('option', { name: minute }),+ )+ .toHaveAttribute('aria-selected', 'true')+ },+)++it('locates Persian month/year numbers while preserving canonical civil-date submission', async () => {+ const changed = vi.fn()+ const screen = await render(+ <form aria-label="Booking">+ <DatePicker locale={faIR} name="date" defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </form>,+ )+ await screen.getByRole('button', { name: /^Date / }).click()+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await typeNativeDigits('۱۲')+ await expect+ .element(screen.getByRole('listbox', { name: 'Month' }).getByRole('option', { name: 'دسامبر' }))+ .toHaveFocus()+ await userEvent.tab()+ await typeNativeDigits('۲۰۲۶')+ const year = screen.getByRole('option', { name: '۲۰۲۶', exact: true })+ await expect.element(year).toHaveFocus()+ await userEvent.keyboard('{Home}2026')+ await expect.element(year).toHaveFocus()+ await 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(+ new FormData(screen.getByRole('form', { name: 'Booking' }).element() as HTMLFormElement).get(+ 'date',+ ),+ ).toBe('2026-12-15')+})++it('updates an open locale without committing or discarding the time draft and clears the locating buffer', async () => {+ const changed = vi.fn()+ const view = (locale: string) => (+ <form aria-label="Schedule">+ <TimePicker+ locale={locale}+ hourCycle={24}+ name="time"+ defaultValue="10:05"+ onValueChange={changed}+ >+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ </form>+ )+ const screen = await render(view('en-US'))+ await screen.getByRole('button', { name: 'Time 10:05' }).click()+ await userEvent.keyboard('1')+ await screen.rerender(view('fa-IR'))+ await expect+ .element(+ screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: '۱', exact: true }),+ )+ .toHaveFocus()+ await typeNativeDigits('۲')+ await expect+ .element(+ screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: '۲', exact: true }),+ )+ .toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+ await userEvent.keyboard('{Escape}')+ await screen.getByRole('button', { name: 'Time ۱۰:۰۵' }).click()+ await expect+ .element(screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: '۱۰' }))+ .toHaveAttribute('aria-selected', 'true')+ await userEvent.tab()+ await typeNativeDigits('۱۲')+ const minute = screen.getByRole('listbox', { name: 'Minute' }).getByRole('option', { name: '۱۲' })+ await expect.element(minute).toHaveFocus()+ await userEvent.keyboard('{Home}12')+ await expect.element(minute).toHaveFocus()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('10:12')+ expect(+ new FormData(screen.getByRole('form', { name: 'Schedule' }).element() as HTMLFormElement).get(+ 'time',+ ),+ ).toBe('10:12')+})diff --git a/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsx b/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsxnew file mode 100644index 00000000000..27e7b96effc--- /dev/null+++ b/packages/dify-ui/src/date-time/__tests__/typeahead.spec.tsx@@ -0,0 +1,97 @@+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { DatePicker, DatePickerContent, DatePickerLabel, DatePickerTrigger } from '../date-picker'+import { TimePicker, TimePickerContent, TimePickerLabel, TimePickerTrigger } from '../time-picker'++async function openMonthPicker() {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ const months = screen.getByRole('listbox', { name: 'Month', exact: true })+ await expect.element(months.getByRole('option', { name: 'January' })).toHaveFocus()+ return { screen, months, changed }+}++it('keeps a multi-letter month match anchored and recovers immediately after a typo', async () => {+ const { months, changed } = await openMonthPicker()+ await userEvent.keyboard('j')+ await expect.element(months.getByRole('option', { name: 'June' })).toHaveFocus()+ await userEvent.keyboard('u')+ await expect.element(months.getByRole('option', { name: 'June' })).toHaveFocus()+ await userEvent.keyboard('n')+ await expect.element(months.getByRole('option', { name: 'June' })).toHaveFocus()+ await userEvent.keyboard('z')+ await expect.element(months.getByRole('option', { name: 'June' })).toHaveFocus()+ await userEvent.keyboard('mar')+ const march = months.getByRole('option', { name: 'March' })+ await expect.element(march).toHaveFocus()+ await expect.element(march).toHaveAttribute('aria-selected', 'true')+ expect(changed).not.toHaveBeenCalled()+})++it('cycles matching months on repeated letters regardless of letter case', async () => {+ const { months, changed } = await openMonthPicker()+ for (const [key, name] of [+ ['j', 'June'],+ ['J', 'July'],+ ['j', 'January'],+ ] as const) {+ await userEvent.keyboard(key)+ const option = months.getByRole('option', { name })+ await expect.element(option).toHaveFocus()+ await expect.element(option).toHaveAttribute('aria-selected', 'true')+ }+ expect(changed).not.toHaveBeenCalled()+})++it('clears an unfinished year prefix when Tab leaves the column', async () => {+ const { screen, changed } = await openMonthPicker()+ await userEvent.tab()+ const years = screen.getByRole('listbox', { name: 'Year', exact: true })+ await userEvent.keyboard('20')+ await expect.element(years.getByRole('option', { name: '2025' })).toHaveFocus()+ await userEvent.tab({ shift: true })+ await userEvent.tab()+ await userEvent.keyboard('2037')+ await expect.element(years.getByRole('option', { name: '2037' })).toHaveFocus()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: January 2037' }))+ .toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+})++it('preserves repeated digits and starts fresh after returning to a time column', async () => {+ const changed = vi.fn()+ const screen = await render(+ <TimePicker defaultValue="13:30" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ const trigger = screen.getByRole('button', { name: 'Time 1:30 PM' })+ await trigger.click()+ const hours = screen.getByRole('listbox', { name: 'Hour', exact: true })+ await userEvent.keyboard('11')+ await expect.element(hours.getByRole('option', { name: '11', exact: true })).toHaveFocus()+ await userEvent.tab()+ await userEvent.keyboard('55')+ await expect+ .element(screen.getByRole('listbox', { name: 'Minute' }).getByRole('option', { name: '55' }))+ .toHaveFocus()+ await userEvent.tab({ shift: true })+ await userEvent.keyboard('2')+ await expect.element(hours.getByRole('option', { name: '2', exact: true })).toHaveFocus()+ 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')+})diff --git a/packages/dify-ui/src/date-time/__tests__/types.tsx b/packages/dify-ui/src/date-time/__tests__/types.tsxnew file mode 100644index 00000000000..0066147b042--- /dev/null+++ b/packages/dify-ui/src/date-time/__tests__/types.tsx@@ -0,0 +1,230 @@+import type * as React from 'react'+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+ DatePickerValue,+} from '@langgenius/dify-ui/date-picker'+import {+ DateTimePicker,+ DateTimePickerContent,+ DateTimePickerTrigger,+ DateTimePickerValue,+} from '@langgenius/dify-ui/date-time-picker'+import {+ TimePicker,+ TimePickerContent,+ TimePickerTrigger,+ TimePickerValue,+} from '@langgenius/dify-ui/time-picker'+import { expectTypeOf } from 'vite-plus/test'++export function pickerTypeContracts(+ triggerRef: React.Ref<HTMLButtonElement>,+ contentRef: React.Ref<HTMLDivElement>,+) {+ const date = (+ <DatePicker+ value="2026-09-28"+ onValueChange={(value) => {+ expectTypeOf(value).toEqualTypeOf<string | null>()+ value?.toUpperCase()+ }}+ >+ <DatePickerLabel ref={contentRef} className="mb-1">+ Date+ </DatePickerLabel>+ <DatePickerTrigger+ ref={triggerRef}+ className={(state) => (state.open ? 'text-text-accent' : '')}+ >+ <DatePickerValue>{(value) => value.toUpperCase()}</DatePickerValue>+ </DatePickerTrigger>+ <DatePickerContent ref={contentRef} style={(state) => ({ opacity: state.open ? 1 : 0 })} />+ </DatePicker>+ )+ const time = (+ <TimePicker+ locale="zh-CN"+ value="22:23"+ onValueChange={(value) => {+ expectTypeOf(value).toEqualTypeOf<string | null>()+ value?.toUpperCase()+ }}+ >+ <TimePickerTrigger ref={triggerRef}>+ <TimePickerValue>{(value) => `${value} UTC+8`}</TimePickerValue>+ </TimePickerTrigger>+ </TimePicker>+ )+ const instant = (+ <DateTimePicker+ timeZone="Asia/Shanghai"+ value={new Date()}+ onValueChange={(value) => {+ expectTypeOf(value).toEqualTypeOf<Date | null>()+ value?.toISOString()+ }}+ >+ <DateTimePickerTrigger ref={triggerRef} />+ <DateTimePickerContent ref={contentRef} />+ </DateTimePicker>+ )+ const invalidDate = (+ // @ts-expect-error Civil dates cannot accept instants.+ <DatePicker value={new Date()}>{null}</DatePicker>+ )+ const invalidTime = (+ // @ts-expect-error Wall times cannot accept instants.+ <TimePicker value={new Date()}>{null}</TimePicker>+ )+ const invalidInstant = (+ // @ts-expect-error Date-time values are instants, not wire strings.+ <DateTimePicker timeZone="UTC" value="2026-09-28">+ {null}+ </DateTimePicker>+ )+ // @ts-expect-error The caller owns the time zone for an instant.+ const missingZone = <DateTimePicker>{null}</DateTimePicker>+ const ariaNamedTime = (+ <TimePicker>+ <TimePickerTrigger aria-label="Start time" aria-describedby="time-help" />+ <TimePickerContent aria-label="Choose start time" />+ </TimePicker>+ )+ // @ts-expect-error Naming belongs to Label or the named parts, not Root.+ const rootLabel = <TimePicker label="Time">{null}</TimePicker>+ // @ts-expect-error External labels use aria-labelledby on the named parts.+ const rootLabelledBy = <DatePicker labelledBy="date-label">{null}</DatePicker>+ // @ts-expect-error Descriptions belong to the trigger.+ const rootDescribedBy = <DatePicker describedBy="date-help">{null}</DatePicker>+ const invalidCallback = (+ // @ts-expect-error Date callbacks must accept civil strings and clearing.+ <DatePicker onValueChange={(value: Date) => value.getTime()}>{null}</DatePicker>+ )+ const partialCalendarLocale = (+ <DatePicker locale={{ code: 'en-US', labels: { labelNav: 'Calendar navigation' } }}>+ {null}+ </DatePicker>+ )+ const intlLocale = <TimePicker locale={new Intl.Locale('zh-CN')}>{null}</TimePicker>+ const localeFallbacks = <TimePicker locale={['en-GB', 'en-US']}>{null}</TimePicker>+ const openChange = (+ <DatePicker+ onOpenChange={(_open, details) => {+ details.cancel()+ // @ts-expect-error The picker owns its animation lifecycle and exposes no unmount action.+ details.preventUnmountOnClose()+ }}+ >+ {null}+ </DatePicker>+ )+ // @ts-expect-error The generated selection may be any valid date, not a caller-defined subset.+ const genericDate = <DatePicker<'2026-09-28'>>{null}</DatePicker>+ // @ts-expect-error Hover opening is not part of the picker contract.+ const hoverDelay = <DatePickerTrigger delay={100} />+ // @ts-expect-error Picker triggers always render native buttons.+ const customTrigger = <DatePickerTrigger render={<div />} />+ // @ts-expect-error The value ID belongs to the field's accessible-name relationship.+ const customValueId = <DatePickerValue id="unrelated" />+ // @ts-expect-error The label ID belongs to the field's accessible-name relationship.+ const customLabelId = <DatePickerLabel id="unrelated" />+ // @ts-expect-error Clear button dimensions belong to the picker anatomy.+ const clearSize = <DatePickerClear aria-label="Clear date" size="sm" />+ const clearNamed = <DatePickerClear aria-label="Clear date" ref={triggerRef} />+ const clearLabelledBy = <DatePickerClear aria-labelledby="clear-date-text" />+ // @ts-expect-error Clear inherits IconButton's required accessible name.+ const unnamedClear = <DatePickerClear />+ // @ts-expect-error Use the inherited ARIA props instead of a custom label alias.+ const legacyClearLabel = <DatePickerClear label="Clear date" />+ // @ts-expect-error IconButton accepts one accessible-name source.+ const conflictingClearNames = <DatePickerClear aria-label="Clear" aria-labelledby="clear-text" />+ // @ts-expect-error Content focus on entry belongs to the picker.+ const customInitialFocus = <DatePickerContent initialFocus={false} />+ const readonlyPredicate = (+ <DateTimePicker+ timeZone="UTC"+ isTimeUnavailable={(wall) => {+ // @ts-expect-error An availability predicate must not mutate the active draft.+ wall.time = '00:00'+ return false+ }}+ >+ {null}+ </DateTimePicker>+ )+ const nonNullableChange = (+ <TimePicker+ defaultValue="13:30"+ // @ts-expect-error Clearing is part of the callback contract even with an initial value.+ onValueChange={(value: string) => value.toUpperCase()}+ >+ {null}+ </TimePicker>+ )+ const invalidStep = (+ // @ts-expect-error Only steps that divide an hour are supported.+ <TimePicker minuteStep={7}>{null}</TimePicker>+ )+ const invalidHourCycle = (+ // @ts-expect-error Hour cycle is a numeric display choice, not an Intl option string.+ <TimePicker hourCycle="h23">{null}</TimePicker>+ )+ const instantStep = (+ // @ts-expect-error Date-time selection has minute precision and does not expose schedule steps.+ <DateTimePicker timeZone="UTC" minuteStep={15}>+ {null}+ </DateTimePicker>+ )+ const formattedInstant = (+ <DateTimePicker timeZone="UTC">+ <DateTimePickerTrigger>+ <DateTimePickerValue>+ {(value) => {+ expectTypeOf(value).toEqualTypeOf<string>()+ return value+ }}+ </DateTimePickerValue>+ </DateTimePickerTrigger>+ </DateTimePicker>+ )+ return {+ nonNullableChange,+ invalidStep,+ invalidHourCycle,+ instantStep,+ formattedInstant,+ partialCalendarLocale,+ intlLocale,+ localeFallbacks,+ openChange,+ genericDate,+ hoverDelay,+ customTrigger,+ customValueId,+ customLabelId,+ clearSize,+ clearNamed,+ clearLabelledBy,+ unnamedClear,+ legacyClearLabel,+ conflictingClearNames,+ customInitialFocus,+ readonlyPredicate,+ date,+ time,+ instant,+ invalidDate,+ invalidTime,+ invalidInstant,+ missingZone,+ ariaNamedTime,+ rootLabel,+ rootLabelledBy,+ rootDescribedBy,+ invalidCallback,+ }+}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.tsxnew file mode 100644index 00000000000..52d3fa38b28--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/behavior.spec.tsx@@ -0,0 +1,438 @@+import { arTN } from '@daypicker/react/locale/ar-TN'+import { faIR } from '@daypicker/react/locale/fa-IR'+import * as React from 'react'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { DirectionProvider } from '../../../direction-provider'+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '../index'++function Parts() {+ return (+ <>+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear date" />+ <DatePickerContent />+ </>+ )+}++describe('DatePicker keyboard and form contract', () => {+ it('keeps a focus-only label associated across label mounting and custom trigger IDs', async () => {+ function Example() {+ const [visible, setVisible] = React.useState(true)+ return (+ <>+ <button type="button" onClick={() => setVisible(!visible)}>+ Toggle label+ </button>+ <DatePicker defaultValue="2025-01-15">+ {visible && <DatePickerLabel>Departure</DatePickerLabel>}+ <DatePickerTrigger id="custom-departure" aria-label={visible ? undefined : 'Date'} />+ <DatePickerContent aria-label={visible ? undefined : 'Choose date'} />+ </DatePicker>+ </>+ )+ }+ const screen = await render(<Example />)+ const toggle = screen.getByRole('button', { name: 'Toggle label' })+ 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 toggle.click()+ await expect.element(screen.getByRole('button', { name: 'Date' })).toBeInTheDocument()+ await toggle.click()+ await userEvent.tab()+ await expect.element(trigger).toHaveFocus()+ await userEvent.keyboard(' ')+ await expect+ .element(screen.getByRole('dialog', { name: 'Departure', exact: true }))+ .toBeInTheDocument()+ })++ it.each(['disabled', 'readOnly'] as const)(+ 'respects %s when activating the label',+ async (state) => {+ const screen = await render(+ <DatePicker {...{ [state]: true }}>+ <DatePickerLabel>Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByText('Date', { exact: true }).click()+ const trigger = screen.getByRole('button', { name: 'Date', exact: true })+ if (state === 'disabled') await expect.element(trigger).not.toHaveFocus()+ else await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'false')+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+ },+ )++ it('explains an unavailable month draft and lets the user repair it without committing a date', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker+ defaultValue="2025-04-15"+ minDate="2025-03-01"+ maxDate="2025-12-31"+ onValueChange={changed}+ >+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Apr 15, 2025' }).click()+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await userEvent.keyboard('{Home}')+ await expect.element(screen.getByRole('button', { name: 'OK' })).toBeDisabled()+ await expect.element(screen.getByRole('status')).toHaveTextContent('This date is unavailable.')+ await expect+ .element(screen.getByRole('group', { name: 'Choose month and year' }))+ .toHaveAccessibleDescription('This date is unavailable.')+ await userEvent.keyboard('{ArrowDown}{ArrowDown}')+ await expect.element(screen.getByRole('button', { name: 'OK' })).toBeEnabled()+ await expect.element(screen.getByRole('status')).not.toBeInTheDocument()+ await screen.getByRole('button', { name: 'OK' }).click()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: March 2025' }))+ .toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+ })++ it('toggles month selection from the title without applying its draft or resizing the popup', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ const popup = screen.getByRole('dialog', { name: 'Date', exact: true })+ await expect.poll(() => popup.element().getBoundingClientRect().height).toBe(252)+ const height = popup.element().getBoundingClientRect().height+ const title = screen.getByRole('button', { name: 'Choose month and year: January 2025' })+ const titleBounds = title.element().getBoundingClientRect()+ await expect.element(title).toHaveAttribute('aria-expanded', 'false')+ await title.click()+ await expect.element(title).toHaveAttribute('aria-expanded', 'true')+ const columns = screen.getByRole('group', { name: 'Choose month and year' })+ expect(title.element().getAttribute('aria-controls')).toBe(columns.element().id)+ expect(popup.element().getBoundingClientRect().height).toBe(height)+ expect(title.element().getBoundingClientRect().top).toBe(titleBounds.top)+ expect(title.element().getBoundingClientRect().left).toBe(titleBounds.left)+ await userEvent.keyboard('{ArrowDown}')+ await title.click()+ await expect.element(title).toHaveFocus()+ await expect.element(title).toHaveAttribute('aria-expanded', 'false')+ await expect.element(screen.getByRole('grid')).toBeInTheDocument()+ expect(popup.element().getBoundingClientRect().height).toBe(height)+ await userEvent.keyboard('{Enter}')+ await expect+ .element(+ screen.getByRole('listbox', { name: 'Month' }).getByRole('option', { name: 'January' }),+ )+ .toHaveFocus()+ await userEvent.tab({ shift: true })+ await expect.element(title).toHaveFocus()+ await userEvent.keyboard(' ')+ await expect.element(title).toHaveAttribute('aria-expanded', 'false')+ await expect.element(title).toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+ })++ it('moves into month selection, locates a year numerically, and returns focus to the calendar', async () => {+ const screen = await render(+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ await screen.getByRole('button', { name: /Choose month and year/ }).click()+ const months = screen.getByRole('listbox', { name: 'Month' })+ await expect.element(months.getByRole('option', { name: 'January', exact: true })).toHaveFocus()+ await userEvent.keyboard('12')+ await expect+ .element(months.getByRole('option', { name: 'December', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ await userEvent.keyboard('{Home}mar')+ await expect.element(months.getByRole('option', { name: 'March', exact: true })).toHaveFocus()+ await userEvent.keyboard('{End}')+ await userEvent.tab()+ await userEvent.keyboard('2037')+ await expect.element(screen.getByRole('option', { name: '2037', exact: true })).toHaveFocus()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ await expect.element(screen.getByRole('grid')).toBeInTheDocument()+ await expect.poll(() => document.activeElement?.closest('[role="grid"]') !== null).toBe(true)+ await expect+ .element(screen.getByRole('button', { name: /Choose month and year: December 2037/ }))+ .toBeInTheDocument()+ })++ it('keeps a single tab stop in the grid and skips unavailable days', async () => {+ const screen = await render(+ <DatePicker+ defaultValue="2025-01-15"+ minDate="2025-01-14"+ maxDate="2025-01-31"+ isDateUnavailable={(date) => date === '2025-01-16'}+ >+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: /^Date Jan/ }).click()+ await userEvent.keyboard('{ArrowRight}')+ expect(document.activeElement?.getAttribute('aria-label')).toMatch(/January 17/)+ expect(document.querySelectorAll('[role="grid"] button[tabindex="0"]')).toHaveLength(1)+ await expect.element(screen.getByRole('button', { name: 'Previous month' })).toBeDisabled()+ await expect.element(screen.getByRole('button', { name: 'Next month' })).toBeDisabled()+ await userEvent.keyboard('{Escape}')+ await expect.element(screen.getByRole('button', { name: /^Date Jan/ })).toHaveFocus()+ })++ it('validates a required value, serializes a civil date, and resets to the initial value', async () => {+ const submitted = vi.fn()+ const screen = await render(+ <form+ onSubmit={(event) => {+ event.preventDefault()+ submitted(new FormData(event.currentTarget).get('date'))+ }}+ >+ <DatePicker name="date" required validationMessage="Choose a date">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>+ <button type="submit">Submit</button>+ <button type="reset">Reset</button>+ </form>,+ )+ await screen.getByRole('button', { name: 'Submit' }).click()+ expect(submitted).not.toHaveBeenCalled()+ await expect.element(screen.getByRole('button', { name: 'Date', exact: true })).toHaveFocus()+ await expect.element(screen.getByRole('alert')).toHaveTextContent('Choose a date')+ await screen.getByRole('button', { name: 'Date', exact: true }).click()+ await userEvent.keyboard('{Enter}')+ await screen.getByRole('button', { name: 'Submit' }).click()+ expect(submitted).toHaveBeenCalledWith(expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/))+ await screen.getByRole('button', { name: 'Reset' }).click()+ await expect+ .element(screen.getByRole('button', { name: 'Date', exact: true }))+ .toBeInTheDocument()+ await expect.element(screen.getByRole('button', { name: 'Clear date' })).not.toBeInTheDocument()+ })++ it.each(['aria-label', 'aria-labelledby'] as const)(+ 'clears through a %s named button and restores trigger focus',+ async (naming) => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <div>+ <DatePickerTrigger />+ <span id="clear-date-text" className="sr-only">+ Clear date+ </span>+ <DatePickerClear+ {...(naming === 'aria-label'+ ? { 'aria-label': 'Clear date' }+ : { 'aria-labelledby': 'clear-date-text' })}+ />+ </div>+ <DatePickerContent />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Clear date' }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith(null)+ await expect.element(screen.getByRole('button', { name: 'Date', exact: true })).toHaveFocus()+ await expect+ .element(screen.getByRole('button', { name: 'Clear date' }))+ .not.toBeInTheDocument()+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+ },+ )++ it('keeps read-only values in form data while preventing edits', async () => {+ const onChange = vi.fn()+ const screen = await render(+ <form id="readonly-form">+ <DatePicker name="date" readOnly defaultValue="2025-01-15" onValueChange={onChange}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>+ </form>,+ )+ const trigger = screen.getByRole('button', { name: /^Date Jan/ })+ await userEvent.tab()+ await expect.element(trigger).toHaveFocus()+ await userEvent.keyboard('{Enter}')+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+ expect(+ new FormData(document.querySelector<HTMLFormElement>('#readonly-form')!).get('date'),+ ).toBe('2025-01-15')+ expect(onChange).not.toHaveBeenCalled()+ })+})++it('moves across an adjacent month with the keyboard', async () => {+ const screen = await render(+ <DatePicker defaultValue="2025-01-31">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 31, 2025' }).click()+ await userEvent.keyboard('{ArrowRight}')+ await expect+ .element(screen.getByRole('button', { name: 'Saturday, February 1st, 2025', exact: true }))+ .toHaveFocus()+ await expect.element(screen.getByRole('status')).toHaveTextContent('February 2025')+ expect(+ Array.from(document.querySelectorAll('[aria-live="polite"]')).filter(+ (element) => element.textContent === 'February 2025',+ ),+ ).toHaveLength(1)+ await userEvent.keyboard('{Enter}')+ await expect.element(screen.getByRole('button', { name: 'Date Feb 1, 2025' })).toHaveFocus()+})++it('opens on the allowed month and retains a visible focus target if every date is unavailable', async () => {+ const screen = await render(+ <DatePicker minDate="2037-02-01" maxDate="2037-02-28" isDateUnavailable={() => true}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date', exact: true }).click()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: February 2037' }))+ .toHaveFocus()+})++it('keeps adjacent-month dates selectable by pointer', async () => {+ const screen = await render(+ <DatePicker defaultValue="2025-01-15">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ await screen.getByRole('button', { name: 'Saturday, February 1st, 2025', exact: true }).click()+ await expect.element(screen.getByRole('button', { name: 'Date Feb 1, 2025' })).toHaveFocus()+})++it('supports month/year paging and week endpoints without committing during navigation', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker defaultValue="2025-01-31" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 31, 2025' }).click()+ await userEvent.keyboard('{PageDown}')+ await expect+ .element(screen.getByRole('button', { name: 'Friday, February 28th, 2025', exact: true }))+ .toHaveFocus()+ await userEvent.keyboard('{Shift>}{PageDown}{/Shift}')+ await expect+ .element(screen.getByRole('button', { name: 'Saturday, February 28th, 2026', exact: true }))+ .toHaveFocus()+ await userEvent.keyboard('{Home}')+ await expect+ .element(screen.getByRole('button', { name: 'Sunday, February 22nd, 2026', exact: true }))+ .toHaveFocus()+ await userEvent.keyboard('{End}')+ await expect+ .element(screen.getByRole('button', { name: 'Saturday, February 28th, 2026', exact: true }))+ .toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+})++it('localizes full dates and reverses horizontal calendar navigation in RTL', async () => {+ const screen = await render(+ <DirectionProvider direction="rtl">+ <DatePicker locale={arTN} defaultValue="2025-01-15">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>+ </DirectionProvider>,+ )+ await screen.getByRole('button', { name: /^Date / }).click()+ await expect+ .element(screen.getByRole('dialog', { name: 'Date', exact: true }))+ .toHaveAttribute('dir', 'rtl')+ await userEvent.keyboard('{ArrowLeft}')+ const nextLabel = 'الخميس، 16 جانفي 2025'+ await expect.element(screen.getByRole('button', { name: nextLabel, exact: true })).toHaveFocus()+})++it('focuses the first invalid picker inside a native fieldset', async () => {+ const screen = await render(+ <form>+ <fieldset>+ <legend>Trip</legend>+ <DatePicker required>+ <DatePickerLabel className="sr-only">Departure</DatePickerLabel>+ <Parts />+ </DatePicker>+ <DatePicker required>+ <DatePickerLabel className="sr-only">Return</DatePickerLabel>+ <Parts />+ </DatePicker>+ </fieldset>+ <button type="submit">Submit trip</button>+ </form>,+ )+ await screen.getByRole('button', { name: 'Submit trip' }).click()+ await expect.element(screen.getByRole('button', { name: 'Departure', exact: true })).toHaveFocus()+})++it('lets a picker override inherited direction independently of its formatting locale', async () => {+ const screen = await render(+ <DirectionProvider direction="rtl">+ <DatePicker direction="ltr" locale={arTN} defaultValue="2025-01-15">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>+ </DirectionProvider>,+ )+ const trigger = screen.getByRole('button', { name: /^Date / })+ await expect.element(trigger).toHaveAttribute('dir', 'ltr')+ await trigger.click()+ await expect+ .element(screen.getByRole('dialog', { name: 'Date', exact: true }))+ .toHaveAttribute('dir', 'ltr')+ await userEvent.keyboard('{ArrowRight}')+ const nextLabel = 'الخميس، 16 جانفي 2025'+ await expect.element(screen.getByRole('button', { name: nextLabel, exact: true })).toHaveFocus()+})++it('keeps Persian month labels in the Gregorian calendar used by the value', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker locale={faIR} defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <Parts />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: /^Date / }).click()+ await screen.getByRole('button', { name: /Choose month and year/ }).click()+ await expect+ .element(screen.getByRole('option', { name: 'ژانویه' }))+ .toHaveAttribute('aria-selected', 'true')+ await screen.getByRole('option', { name: 'فوریه' }).click()+ await screen.getByRole('button', { name: 'OK' }).click()+ const dateName = 'شنبه ۱۵ فوریه ۲۰۲۵'+ await screen.getByRole('button', { name: dateName }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('2025-02-15')+})diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/date-value.spec.ts b/packages/dify-ui/src/date-time/date-picker/__tests__/date-value.spec.tsnew file mode 100644index 00000000000..2a6b0a7cf03--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/date-value.spec.ts@@ -0,0 +1,15 @@+import { formatDateValue, parseDateValue } from '../date-value'++it.each(['2025-02-30', '2025-02', '2025-2-03', '2025-02-03T00:00:00Z', '0000-01-01'])(+ 'rejects noncanonical or impossible civil dates: %s',+ (value) => {+ expect(parseDateValue(value)).toBeNull()+ },+)++it.each(['2024-02-29', '2025-02-28', '0099-01-01'])(+ 'roundtrips valid civil dates without native Date year coercion: %s',+ (value) => {+ expect(formatDateValue(parseDateValue(value)!)).toBe(value)+ },+)diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx b/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsxnew file mode 100644index 00000000000..638eacac780--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/gesture.spec.tsx@@ -0,0 +1,92 @@+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { DatePicker, DatePickerContent, DatePickerLabel, DatePickerTrigger } from '../index'++async function openMonths() {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker+ defaultValue="2025-01-15"+ minDate="2020-01-01"+ maxDate="2030-12-31"+ onValueChange={changed}+ >+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent style={{ maxHeight: 210 }} />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: 'Date Jan 15, 2025' }).click()+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ const months = screen.getByRole('listbox', { name: 'Month' })+ const years = screen.getByRole('listbox', { name: 'Year' })+ await expect.element(months.getByRole('option', { name: 'January' })).toHaveFocus()+ return { screen, months, years, changed }+}++// Synthetic intent with real Chromium scrolling, matching the time-column gesture tests.+function startTouch(column: Element, top: number) {+ column.dispatchEvent(new Event('touchstart'))+ column.scrollTo({ top, behavior: 'instant' })+ column.dispatchEvent(new Event('scroll'))+}++it('shares top alignment across click, keyboard and touch and applies both moving month/year columns', async () => {+ const { screen, months, years, changed } = await openMonths()+ const popup = screen.getByRole('dialog', { name: 'Date', exact: true }).element()+ const bounds = popup.getBoundingClientRect()+ const apply = screen.getByRole('button', { name: 'OK', exact: true })+ const cancel = screen.getByRole('button', { name: 'Cancel', exact: true })+ for (const button of [apply, cancel]) {+ const rect = button.element().getBoundingClientRect()+ expect(rect.top).toBeGreaterThanOrEqual(bounds.top)+ expect(rect.bottom).toBeLessThanOrEqual(bounds.bottom)+ }+ expect(popup.scrollHeight).toBe(popup.clientHeight)+ expect(months.element().clientHeight).toBeLessThan(192)+ await months.getByRole('option', { name: 'April' }).click({ scroll: 'none' })+ await expect.poll(() => months.element().scrollTop).toBe(78)+ await userEvent.keyboard('{ArrowDown}')+ await expect.element(months.getByRole('option', { name: 'May' })).toHaveFocus()+ expect(months.element().scrollTop).toBe(104)+ startTouch(months.element(), 136)+ startTouch(years.element(), 188)+ await expect+ .element(months.getByRole('option', { name: 'June' }))+ .toHaveAttribute('aria-selected', 'true')+ await expect+ .element(years.getByRole('option', { name: '2027' }))+ .toHaveAttribute('aria-selected', 'true')+ expect(months.element().scrollTop).toBe(136)+ expect(years.element().scrollTop).toBe(188)+ await apply.click()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: June 2027' }))+ .toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+ await expect+ .element(screen.getByRole('button', { name: 'Date Jan 15, 2025' }))+ .toBeInTheDocument()+})++it('settles month gestures without losing a concurrent year draft and cancels them without applying', async () => {+ const { screen, months, years, changed } = await openMonths()+ startTouch(months.element(), 136)+ startTouch(years.element(), 188)+ for (const column of [months.element(), years.element()]) {+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ }+ await expect+ .element(months.getByRole('option', { name: 'June' }))+ .toHaveAttribute('aria-selected', 'true')+ await expect+ .element(years.getByRole('option', { name: '2027' }))+ .toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => months.element().scrollTop).toBe(130)+ await screen.getByRole('button', { name: 'Cancel', exact: true }).click()+ await expect+ .element(screen.getByRole('button', { name: 'Choose month and year: January 2025' }))+ .toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+})diff --git a/packages/dify-ui/src/date-time/date-picker/__tests__/index.spec.tsx b/packages/dify-ui/src/date-time/date-picker/__tests__/index.spec.tsxnew file mode 100644index 00000000000..965908e33e5--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/__tests__/index.spec.tsx@@ -0,0 +1,47 @@+import { zhCN } from '@daypicker/react/locale/zh-CN'+import * as React from 'react'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { DatePicker, DatePickerContent, DatePickerLabel, DatePickerTrigger } from '../index'++it('confirms the selected day without clearing it or emitting a duplicate change', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DatePicker defaultValue="2025-01-15" onValueChange={changed}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>,+ )+ const trigger = screen.getByRole('button', { name: 'Date Jan 15, 2025' })+ await trigger.click()+ await userEvent.keyboard('{Enter}')+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'false')+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+})++it('preserves localized today and selection semantics in the styled day button', async () => {+ vi.setSystemTime(new Date('2026-09-28T12:00:00Z'))+ try {+ const screen = await render(+ <DatePicker locale={zhCN} defaultValue="2026-09-28">+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>,+ )+ await screen.getByRole('button', { name: /^Date / }).click()+ const today = screen.getByRole('button', { name: '今天,2026年9月28日 星期一,已选择' })+ await expect.element(today).toHaveAttribute('aria-current', 'date')+ await expect.element(today).toHaveTextContent('28')+ await expect.element(today).toHaveFocus()+ await userEvent.keyboard('{ArrowRight}')+ await expect+ .element(screen.getByRole('button', { name: '2026年9月29日 星期二' }))+ .not.toHaveAttribute('aria-current')+ } finally {+ vi.useRealTimers()+ }+})diff --git a/packages/dify-ui/src/date-time/date-picker/calendar-grid.tsx b/packages/dify-ui/src/date-time/date-picker/calendar-grid.tsxnew file mode 100644index 00000000000..248f9541550--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/calendar-grid.tsx@@ -0,0 +1,191 @@+import type { DayPickerProps, NavProps } from '@daypicker/react'+import { TZDate } from '@date-fns/tz'+import { DayButton, DayFlag, DayPicker, SelectionState, UI } from '@daypicker/react'+import * as React from 'react'+import { useDirection } from '../../direction-provider'+import { IconButton } from '../../icon-button'+import { formatDateValue, parseDateValue } from './date-value'++type CalendarGridProps = {+ numberingSystem: string+ navigation: {+ monthLabel: string+ monthTrigger: React.ReactNode+ previousMonth: string+ nextMonth: string+ }+ value: string | null+ onSelect: (value: string) => void+ displayMonth: string+ onDisplayMonthChange: (value: string) => void+ locale?: DayPickerProps['locale']+ timeZone?: string+ focusOnMount?: boolean+ minDate?: string+ maxDate?: string+ isDateUnavailable?: (date: string) => boolean+}++function toCalendarDate(value: string): Date {+ const parsed = parseDateValue(value)+ if (!parsed) throw new RangeError(`Invalid calendar date: ${value}`)+ return parsed+}++function fromCalendarDate(date: Date): string {+ return formatDateValue(new TZDate(date.getTime(), 'UTC'))+}++function StyledDayButton(props: React.ComponentProps<typeof DayButton>) {+ return (+ <DayButton {...props} aria-current={props.modifiers.today ? 'date' : undefined}>+ {props.children}+ {props.modifiers.today && !props.modifiers.selected && (+ <span+ aria-hidden="true"+ className="absolute bottom-1 left-1/2 size-1 -translate-x-1/2 rounded-full bg-components-button-primary-bg"+ />+ )}+ </DayButton>+ )+}++const NavigationContext = React.createContext<CalendarGridProps['navigation'] | null>(null)++function CalendarNavigation({+ previousMonth,+ nextMonth,+ onPreviousClick,+ onNextClick,+ ...navProps+}: NavProps) {+ const navigation = React.useContext(NavigationContext)!+ return (+ <nav {...navProps} className="flex h-10 items-center justify-between px-2 pt-2">+ {navigation.monthTrigger}+ <div className="flex">+ <IconButton+ size="lg"+ aria-label={navigation.previousMonth}+ disabled={!previousMonth}+ onClick={onPreviousClick}+ >+ <span+ className="i-ri-arrow-up-s-line size-4 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ aria-hidden="true"+ />+ </IconButton>+ <IconButton+ size="lg"+ aria-label={navigation.nextMonth}+ disabled={!nextMonth}+ onClick={onNextClick}+ >+ <span+ className="i-ri-arrow-down-s-line size-4 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ aria-hidden="true"+ />+ </IconButton>+ </div>+ </nav>+ )+}++const calendarClassNames = {+ [UI.Root]: 'w-63',+ [UI.Months]: 'w-full',+ [UI.Month]: 'w-full',+ [UI.MonthCaption]: 'sr-only',+ [UI.MonthGrid]: 'block w-full',+ [UI.Weekdays]: 'flex h-7 items-center gap-0.5 border-b-[0.5px] border-divider-regular px-2',+ [UI.Weekday]: 'flex h-7 w-8 items-center justify-center text-text-tertiary system-2xs-medium',+ [UI.Weeks]: 'flex flex-col gap-0.5 p-2',+ [UI.Week]: 'flex h-8 gap-0.5',+ [UI.Day]: 'flex size-8 items-center justify-center p-0 text-center',+ [UI.DayButton]:+ 'relative flex size-8 items-center justify-center rounded-lg text-text-secondary system-sm-medium hover:bg-state-base-hover focus-visible:outline-2 focus-visible:outline-state-accent-solid disabled:cursor-default',+ [SelectionState.selected]:+ '[&>button]:bg-components-button-primary-bg [&>button]:text-components-button-primary-text [&>button]:hover:bg-components-button-primary-bg forced-colors:[&>button]:outline forced-colors:[&>button]:outline-[Highlight]',+ [DayFlag.outside]:+ '[&:not([aria-selected=true])>button]:text-text-tertiary [&:not([aria-selected=true])>button]:hover:text-text-secondary',+ [DayFlag.disabled]:+ '[&>button]:cursor-not-allowed [&>button]:text-text-quaternary [&>button]:hover:bg-transparent',+} as const++function CalendarGrid({+ numberingSystem,+ navigation,+ value,+ onSelect,+ displayMonth,+ onDisplayMonthChange,+ locale,+ timeZone,+ focusOnMount,+ minDate,+ maxDate,+ isDateUnavailable,+}: CalendarGridProps) {+ const [today] = React.useState(() =>+ toCalendarDate(formatDateValue(timeZone ? new TZDate(Date.now(), timeZone) : new Date())),+ )+ const direction = useDirection()+ const selected = value ? toCalendarDate(value) : undefined+ const calendarRef = React.useRef<HTMLDivElement>(null)+ const restoreSelectionFocusRef = React.useRef(false)+ React.useLayoutEffect(() => {+ if (!restoreSelectionFocusRef.current) return+ restoreSelectionFocusRef.current = false+ // DayPicker keys day buttons by both date and display month, so outside-day selection remounts them.+ calendarRef.current?.querySelector<HTMLElement>('[role="grid"] button[tabindex="0"]')?.focus()+ }, [displayMonth])++ /* oxlint-disable jsx-a11y/no-autofocus -- DayPicker restores focus after an explicit view change, rather than autofocusing a page input. */+ return (+ <NavigationContext value={navigation}>+ <div ref={calendarRef} className="min-h-0 overflow-y-auto overscroll-none">+ <DayPicker+ mode="single"+ required+ dir={direction}+ selected={selected}+ onSelect={(date) => {+ if (!date) return+ const next = fromCalendarDate(date)+ const nextMonth = `${next.slice(0, 7)}-01`+ if (nextMonth !== displayMonth) {+ restoreSelectionFocusRef.current = true+ onDisplayMonthChange(nextMonth)+ }+ onSelect(next)+ }}+ month={toCalendarDate(displayMonth)}+ onMonthChange={(month) =>+ onDisplayMonthChange(`${fromCalendarDate(month).slice(0, 7)}-01`)+ }+ timeZone="UTC"+ today={today}+ autoFocus={focusOnMount}+ startMonth={minDate ? toCalendarDate(minDate) : toCalendarDate('0001-01-01')}+ endMonth={maxDate ? toCalendarDate(maxDate) : toCalendarDate('9999-12-31')}+ locale={locale}+ // DayPicker forwards this to Intl; its literal union lists only a subset of valid Intl identifiers.+ numerals={numberingSystem as NonNullable<DayPickerProps['numerals']>}+ showOutsideDays+ disabled={(date) => {+ const day = fromCalendarDate(date)+ return Boolean(+ (minDate && day < minDate) || (maxDate && day > maxDate) || isDateUnavailable?.(day),+ )+ }}+ components={{ DayButton: StyledDayButton, Nav: CalendarNavigation }}+ classNames={calendarClassNames}+ />+ </div>+ </NavigationContext>+ )+ /* oxlint-enable jsx-a11y/no-autofocus */+}++export { CalendarGrid, fromCalendarDate, toCalendarDate }+export type { CalendarGridProps }diff --git a/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx b/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsxnew file mode 100644index 00000000000..7a9d0edfc22--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/calendar-panel.tsx@@ -0,0 +1,255 @@+import type { DayPickerProps } from '@daypicker/react'+import type { OptionColumnHandle } from '../internal/option-column'+import * as React from 'react'+import { Button } from '../../button'+import { OptionColumn } from '../internal/option-column'+import { PickerColumns, PickerPanel, PickerPanelHeader } from '../internal/picker-panel'+import { usePickerNumbers } from '../internal/use-picker-numbers'+import { CalendarGrid, toCalendarDate } from './calendar-grid'++type CalendarPanelLabels = {+ previousMonth: string+ nextMonth: string+ chooseMonthAndYear: string+ month: string+ year: string+ cancel: string+ apply: string+ unavailable: string+}++type CalendarPanelProps = {+ value: string | null+ onSelect: (date: string) => void+ displayMonth: string+ onDisplayMonthChange: (month: string) => void+ locale?: DayPickerProps['locale']+ timeZone?: string+ minDate?: string+ maxDate?: string+ isDateUnavailable?: (date: string) => boolean+ labels: CalendarPanelLabels+ footer?: React.ReactNode+}++function CalendarPanel({+ value,+ onSelect,+ displayMonth,+ onDisplayMonthChange,+ locale,+ timeZone,+ minDate,+ maxDate,+ isDateUnavailable,+ labels,+ footer,+}: CalendarPanelProps) {+ const [monthPickerHeight, setMonthPickerHeight] = React.useState<number | null>(null)+ const choosingMonth = monthPickerHeight !== null+ const monthPickerId = React.useId()+ const errorId = React.useId()+ const [draftMonth, setDraftMonth] = React.useState(displayMonth)+ const [focusCalendar, setFocusCalendar] = React.useState(false)+ const panelRef = React.useRef<HTMLDivElement>(null)+ const headerRef = React.useRef<HTMLButtonElement>(null)+ const monthRef = React.useRef<OptionColumnHandle>(null)+ const yearRef = React.useRef<OptionColumnHandle>(null)+ React.useEffect(() => {+ if (choosingMonth || !focusCalendar) return+ const frame = requestAnimationFrame(() => {+ if (!panelRef.current?.querySelector('[role="grid"] button[tabindex="0"]'))+ headerRef.current?.focus()+ })+ return () => cancelAnimationFrame(frame)+ }, [choosingMonth, focusCalendar])+ const year = Number(draftMonth.slice(0, 4))+ const month = Number(draftMonth.slice(5, 7))+ const minYear = minDate+ ? Number(minDate.slice(0, 4))+ : Math.min(1900, Number(displayMonth.slice(0, 4)))+ const maxYear = maxDate+ ? Number(maxDate.slice(0, 4))+ : Math.max(2100, Number(displayMonth.slice(0, 4)))+ const numbers = usePickerNumbers(locale?.code)+ const monthFormatting = React.useMemo(() => {+ const options = { month: 'long', calendar: 'gregory', timeZone: 'UTC' } as const+ const formatter = new Intl.DateTimeFormat(locale?.code ?? 'en-US', options)+ return {+ caption: new Intl.DateTimeFormat(locale?.code ?? 'en-US', { ...options, year: 'numeric' }),+ options: Array.from({ length: 12 }, (_, index) => ({+ value: index + 1,+ label: formatter.format(new Date(Date.UTC(2025, index, 1))),+ })),+ }+ }, [locale?.code])+ const monthLabel = monthFormatting.caption.format(toCalendarDate(displayMonth))+ function outOfBounds(candidate: string) {+ return Boolean(+ (minDate && candidate.slice(0, 7) < minDate.slice(0, 7)) ||+ (maxDate && candidate.slice(0, 7) > maxDate.slice(0, 7)),+ )+ }+ function handleEscape(event: React.KeyboardEvent<HTMLElement>) {+ if (event.key === 'Escape') {+ event.preventDefault()+ event.stopPropagation()+ finish(false)+ }+ }+ const unavailable = outOfBounds(draftMonth)+ function focusPopup() {+ panelRef.current?.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true })+ }+ function finish(apply: boolean) {+ let next = draftMonth+ if (apply) {+ next = `${String(yearRef.current?.settle() ?? year).padStart(4, '0')}-${String(monthRef.current?.settle() ?? month).padStart(2, '0')}-01`+ setDraftMonth(next)+ if (outOfBounds(next)) return+ }+ focusPopup()+ setFocusCalendar(apply)+ if (apply) onDisplayMonthChange(next)+ setMonthPickerHeight(null)+ if (!apply) requestAnimationFrame(() => headerRef.current?.focus())+ }+ const monthTrigger = (+ <Button+ ref={headerRef}+ variant="ghost"+ type="button"+ aria-label={`${labels.chooseMonthAndYear}: ${monthLabel}`}+ aria-expanded={choosingMonth}+ aria-controls={choosingMonth ? monthPickerId : undefined}+ className="gap-0.5 px-2 text-sm leading-5 font-semibold text-text-primary"+ onKeyDown={choosingMonth ? handleEscape : undefined}+ onClick={() => {+ if (choosingMonth) {+ finish(false)+ return+ }+ const height = panelRef.current?.offsetHeight+ if (height === undefined) return+ focusPopup()+ setDraftMonth(displayMonth)+ setMonthPickerHeight(height)+ }}+ >+ {monthLabel}+ <span+ aria-hidden="true"+ className={`${choosingMonth ? 'i-ri-arrow-up-s-line' : 'i-ri-arrow-down-s-line'} size-4 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none`}+ />+ </Button>+ )+ return (+ <PickerPanel+ ref={panelRef}+ style={monthPickerHeight === null ? undefined : { height: monthPickerHeight }}+ header={+ choosingMonth && (+ <PickerPanelHeader className="items-start px-2 pt-2">{monthTrigger}</PickerPanelHeader>+ )+ }+ message={+ choosingMonth &&+ unavailable && (+ <p id={errorId} role="status" className="px-2 system-xs-regular text-text-destructive">+ {labels.unavailable}+ </p>+ )+ }+ footer={+ choosingMonth ? (+ <>+ <Button+ size="small"+ variant="secondary"+ className="flex-1"+ onKeyDown={handleEscape}+ onClick={() => finish(false)}+ >+ {labels.cancel}+ </Button>+ <Button+ size="small"+ variant="primary"+ className="flex-1"+ disabled={unavailable}+ aria-describedby={unavailable ? errorId : undefined}+ onKeyDown={handleEscape}+ onClick={() => finish(true)}+ >+ {labels.apply}+ </Button>+ </>+ ) : (+ footer+ )+ }+ >+ {choosingMonth ? (+ <PickerColumns+ id={monthPickerId}+ role="group"+ aria-label={labels.chooseMonthAndYear}+ aria-describedby={unavailable ? errorId : undefined}+ >+ <OptionColumn+ ref={monthRef}+ onEscape={() => finish(false)}+ focusOnMount+ normalizeDigits={numbers.normalizeDigits}+ label={labels.month}+ value={month}+ options={monthFormatting.options}+ onValueChange={(next) =>+ setDraftMonth(+ (previous) => `${previous.slice(0, 4)}-${String(next).padStart(2, '0')}-01`,+ )+ }+ />+ <OptionColumn+ ref={yearRef}+ onEscape={() => finish(false)}+ normalizeDigits={numbers.normalizeDigits}+ label={labels.year}+ value={year}+ options={Array.from({ length: maxYear - minYear + 1 }, (_, index) => ({+ value: minYear + index,+ label: numbers.formatInteger(minYear + index),+ }))}+ onValueChange={(next) =>+ setDraftMonth(+ (previous) => `${String(next).padStart(4, '0')}-${previous.slice(5, 7)}-01`,+ )+ }+ />+ </PickerColumns>+ ) : (+ <CalendarGrid+ numberingSystem={numbers.numberingSystem}+ navigation={{+ monthLabel,+ monthTrigger,+ previousMonth: labels.previousMonth,+ nextMonth: labels.nextMonth,+ }}+ focusOnMount={focusCalendar}+ value={value}+ onSelect={onSelect}+ displayMonth={displayMonth}+ onDisplayMonthChange={onDisplayMonthChange}+ locale={locale}+ timeZone={timeZone}+ minDate={minDate}+ maxDate={maxDate}+ isDateUnavailable={isDateUnavailable}+ />+ )}+ </PickerPanel>+ )+}+export { CalendarPanel }+export type { CalendarPanelLabels, CalendarPanelProps }diff --git a/packages/dify-ui/src/date-time/date-picker/date-value.ts b/packages/dify-ui/src/date-time/date-picker/date-value.tsnew file mode 100644index 00000000000..575005870ba--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/date-value.ts@@ -0,0 +1,27 @@+import { tz } from '@date-fns/tz'+import { format, isValid, parseISO } from 'date-fns'++function parseDateValue(value: string): Date | null {+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000')) return null+ const date = parseISO(value, { in: tz('UTC') })+ return isValid(date) ? date : null+}++function formatDateValue(date: Date): string {+ return format(date, 'yyyy-MM-dd')+}++function requireDateValue(value: string | null): Date | null {+ if (value === null) return null+ const date = parseDateValue(value)+ if (!date) throw new RangeError(`Invalid calendar date: ${value}`)+ return date+}++function getInitialMonth(date: string, minDate?: string, maxDate?: string): string {+ const visibleDate =+ minDate && date < minDate ? minDate : maxDate && date > maxDate ? maxDate : date+ return `${visibleDate.slice(0, 7)}-01`+}++export { formatDateValue, getInitialMonth, parseDateValue, requireDateValue }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.tsxnew file mode 100644index 00000000000..81310f91fb0--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/index.stories.tsx@@ -0,0 +1,279 @@+import type { Meta, StoryObj } from '@storybook/react-vite'+import { arTN } from '@daypicker/react/locale/ar-TN'+import * as React from 'react'+import { expect, waitFor, within } from 'storybook/test'+import { Button } from '../../button'+import { DirectionProvider } from '../../direction-provider'+import {+ DateTimePicker,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '../date-time-picker'+import { TimePicker, TimePickerContent, TimePickerLabel, TimePickerTrigger } from '../time-picker'+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from './index'++const meta = {+ title: 'Base/Form/Date Picker',+ component: DatePicker,+ args: { children: null },+ parameters: {+ layout: 'centered',+ docs: { story: { autoplay: false } },+ a11y: { config: { rules: [{ id: 'color-contrast', enabled: true }] } },+ },+ tags: ['autodocs'],+} satisfies Meta<typeof DatePicker>++export default meta+type Story = StoryObj<typeof meta>++function DatePickerDemo() {+ const [value, setValue] = React.useState<string | null>('2025-01-15')+ return (+ <div className="grid gap-1">+ <DatePicker value={value} onValueChange={setValue}>+ <DatePickerLabel>Start date</DatePickerLabel>+ <div className="flex items-center gap-1">+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear start date" />+ </div>+ <DatePickerContent />+ </DatePicker>+ </div>+ )+}++export const Default: Story = {+ render: () => <DatePickerDemo />,+ play: async ({ canvasElement, userEvent }) => {+ const canvas = within(canvasElement)+ const body = within(canvasElement.ownerDocument.body)+ const trigger = canvas.getByRole('button', { name: 'Start date Jan 15, 2025' })+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ await userEvent.click(trigger)+ await waitFor(() =>+ expect(body.getByRole('button', { name: /Wednesday, January 15th, 2025/ })).toHaveFocus(),+ )+ await userEvent.keyboard('{ArrowRight}{Enter}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await expect(trigger).toHaveAccessibleName('Start date Jan 16, 2025')+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ },+}++function NativeFormDemo() {+ const id = React.useId()+ const [submitted, setSubmitted] = React.useState<Record<string, FormDataEntryValue> | null>(null)+ return (+ <form+ aria-label="Schedule"+ className="grid w-80 max-w-full gap-4"+ onSubmit={(event) => {+ event.preventDefault()+ setSubmitted(Object.fromEntries(new FormData(event.currentTarget)))+ }}+ onReset={() => setSubmitted(null)}+ >+ <fieldset className="grid min-w-0 gap-3">+ <legend className="mb-2 system-md-semibold text-text-primary">Schedule</legend>+ <div className="grid gap-1">+ <DatePicker name="date" required validationMessage="Choose a start date.">+ <DatePickerLabel>Start date (required)</DatePickerLabel>+ <DatePickerTrigger aria-describedby={`${id}-date-help`} />+ <DatePickerContent />+ </DatePicker>+ <p id={`${id}-date-help`} className="system-xs-regular text-text-secondary">+ Choose a calendar date; no time zone is stored.+ </p>+ </div>+ <div className="grid gap-1">+ <TimePicker name="time" defaultValue="13:30">+ <TimePickerLabel>Start time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ </div>+ <div className="grid gap-1">+ <DateTimePicker+ name="reminder"+ timeZone="UTC"+ defaultValue={new Date('2025-01-15T13:30:00Z')}+ >+ <DateTimePickerLabel>Reminder (UTC)</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ </div>+ </fieldset>+ <div className="flex gap-2">+ <Button type="submit">Save</Button>+ <Button type="reset" variant="secondary">+ Reset+ </Button>+ </div>+ {submitted && (+ <output aria-label="Submitted values" className="system-xs-regular break-all">+ {JSON.stringify(submitted)}+ </output>+ )}+ </form>+ )+}++export const NativeForm: Story = {+ render: () => <NativeFormDemo />,+ parameters: {+ docs: {+ description: {+ story:+ 'Native form, fieldset, picker labels and FormData. Labels focus their triggers without opening the popup; descriptions and committed values are announced with the visible label. Save validates the required date, and Reset restores defaults. No Base UI Field or Form registration is involved.',+ },+ },+ },+ play: async ({ canvasElement, userEvent }) => {+ const canvas = within(canvasElement)+ const body = within(canvasElement.ownerDocument.body)+ const trigger = canvas.getByRole('button', { name: 'Start date (required)' })+ await userEvent.click(canvas.getByRole('button', { name: 'Save' }))+ await expect(canvas.queryByRole('status', { name: 'Submitted values' })).not.toBeInTheDocument()+ await expect(trigger).toHaveFocus()+ await expect(trigger).toHaveAttribute('aria-invalid', 'true')+ await expect(trigger).toHaveAccessibleDescription(+ /Choose a calendar date; no time zone is stored.*Choose a start date/,+ )+ for (const [label, name] of [+ ['Start date (required)', 'Start date (required)'],+ ['Start time', 'Start time 1:30 PM'],+ ['Reminder (UTC)', 'Reminder (UTC) Jan 15, 2025, 1:30 PM'],+ ] as const) {+ await userEvent.click(canvas.getByText(label, { exact: true }))+ const field = canvas.getByRole('button', { name })+ await expect(field).toHaveFocus()+ await expect(field).toHaveAttribute('aria-expanded', 'false')+ await expect(body.queryByRole('dialog')).not.toBeInTheDocument()+ }+ await userEvent.click(canvas.getByText('Start date (required)', { exact: true }))+ await userEvent.keyboard('{Enter}')+ const dialog = await body.findByRole('dialog', { name: 'Start date (required)' })+ await waitFor(() => expect(dialog).toBeVisible())+ await waitFor(() =>+ expect(dialog.contains(canvasElement.ownerDocument.activeElement)).toBe(true),+ )+ await userEvent.keyboard('{Enter}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await userEvent.click(canvas.getByRole('button', { name: 'Save' }))+ const submitted = canvas.getByRole('status', { name: 'Submitted values' })+ const values = JSON.parse(submitted.textContent!)+ await expect(values).toEqual({+ date: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/),+ time: '13:30',+ reminder: '2025-01-15T13:30:00.000Z',+ })+ await userEvent.click(canvas.getByRole('button', { name: 'Reset' }))+ await waitFor(() => expect(trigger).toHaveAccessibleName('Start date (required)'))+ await expect(trigger).not.toHaveAttribute('aria-invalid', 'true')+ await expect(canvas.queryByRole('status', { name: 'Submitted values' })).not.toBeInTheDocument()+ },+}++export const Empty: Story = {+ render: () => (+ <DatePicker>+ <DatePickerLabel className="sr-only">Start date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ ),+}+export const Disabled: Story = {+ render: () => (+ <DatePicker defaultValue="2025-01-15" disabled>+ <DatePickerLabel className="sr-only">Start date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerClear aria-label="Clear start date" />+ <DatePickerContent />+ </DatePicker>+ ),+}+export const ReadOnly: Story = {+ render: () => (+ <DatePicker defaultValue="2025-01-15" readOnly>+ <DatePickerLabel className="sr-only">Start date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ ),+}++export const Calendar: Story = {+ ...Default,+ name: 'Calendar (open preview)',+ tags: ['!autodocs'],+ play: async ({ canvasElement, userEvent }) => {+ await userEvent.click(+ within(canvasElement).getByRole('button', { name: 'Start date Jan 15, 2025' }),+ )+ const grid = await within(canvasElement.ownerDocument.body).findByRole('grid')+ await waitFor(() => expect(grid).toBeVisible())+ },+}++export const RTL: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'DirectionProvider supplies interaction direction; dir sets the surrounding HTML direction. The picker carries direction into its portaled popup. Calendar dates use the Arabic locale; action labels retain the English defaults.',+ },+ },+ },+ render: () => (+ <div dir="rtl">+ <DirectionProvider direction="rtl">+ <DatePicker locale={arTN} defaultValue="2025-01-15">+ <DatePickerLabel className="sr-only">Start date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </DirectionProvider>+ </div>+ ),+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ const trigger = within(canvasElement).getByRole('button', { name: /^Start date / })+ await userEvent.click(trigger)+ const dialog = await body.findByRole('dialog', { name: 'Start date' })+ await expect(dialog).toHaveAttribute('dir', 'rtl')+ await waitFor(() =>+ expect(body.getByRole('button', { name: /^الأربعاء، 15 جانفي 2025/ })).toHaveFocus(),+ )+ await userEvent.keyboard('{ArrowLeft}')+ await expect(body.getByRole('button', { name: 'الخميس، 16 جانفي 2025' })).toHaveFocus()+ await userEvent.keyboard('{ArrowRight}')+ await expect(body.getByRole('button', { name: /^الأربعاء، 15 جانفي 2025/ })).toHaveFocus()+ const heading = body.getByRole('button', { name: /Choose month and year:/ })+ await userEvent.click(heading)+ const months = await body.findByRole('listbox', { name: 'Month' })+ const years = body.getByRole('listbox', { name: 'Year' })+ await expect(months.getBoundingClientRect().left).toBeGreaterThan(+ years.getBoundingClientRect().left,+ )+ await userEvent.keyboard('{Escape}')+ await waitFor(() =>+ expect(body.getByRole('button', { name: /Choose month and year:/ })).toHaveFocus(),+ )+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await userEvent.keyboard('{Enter}')+ await waitFor(() => expect(body.getByRole('grid')).toBeVisible())+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ },+}diff --git a/packages/dify-ui/src/date-time/date-picker/index.tsx b/packages/dify-ui/src/date-time/date-picker/index.tsxnew file mode 100644index 00000000000..b19ef7b597f--- /dev/null+++ b/packages/dify-ui/src/date-time/date-picker/index.tsx@@ -0,0 +1,180 @@+'use client'++import type { CalendarPanelLabels, CalendarPanelProps } from '../date-picker/calendar-panel'+import type {+ PickerClearProps,+ PickerContentProps,+ PickerFieldProps,+ PickerLabelProps,+ PickerTriggerProps,+ PickerValueProps,+} from '../internal/picker-parts'+import { useControlled } from '@base-ui/utils/useControlled'+import { enUS } from '@daypicker/react/locale/en-US'+import * as React from 'react'+import { CalendarPanel } from '../date-picker/calendar-panel'+import { formatDateValue, getInitialMonth, requireDateValue } from '../date-picker/date-value'+import {+ PickerClear,+ PickerContent,+ PickerLabel,+ PickerRoot,+ PickerTrigger,+ PickerValue,+ usePickerContext,+} from '../internal/picker-parts'++type DatePickerProps = PickerFieldProps &+ Pick<CalendarPanelProps, 'locale' | 'minDate' | 'maxDate' | 'isDateUnavailable'> & {+ /** A Gregorian YYYY-MM-DD civil date; null represents an empty field. */+ value?: string | null+ defaultValue?: string | null+ /** Called on day confirmation, clearing or form reset. */+ onValueChange?: (value: string | null) => void+ labels?: Partial<CalendarPanelLabels>+ }+type ContextValue = Omit<+ DatePickerProps,+ 'value' | 'defaultValue' | 'onValueChange' | 'children'+> & {+ value: Exclude<DatePickerProps['value'], undefined>+ commit: NonNullable<DatePickerProps['onValueChange']>+}+const Context = React.createContext<ContextValue | null>(null)+function useContext() {+ const context = React.useContext(Context)+ if (!context) throw new Error('DatePicker parts require DatePicker.')+ return context+}+const defaultLabels: CalendarPanelLabels = {+ previousMonth: 'Previous month',+ nextMonth: 'Next month',+ chooseMonthAndYear: 'Choose month and year',+ month: 'Month',+ year: 'Year',+ cancel: 'Cancel',+ apply: 'OK',+ unavailable: 'This date is unavailable.',+}++function DatePicker({+ value: valueProp,+ defaultValue = null,+ onValueChange,+ children,+ ...props+}: DatePickerProps) {+ const [value, setValue] = useControlled({+ controlled: valueProp,+ default: defaultValue,+ name: 'DatePicker',+ })+ requireDateValue(value)+ if (props.minDate) requireDateValue(props.minDate)+ if (props.maxDate) requireDateValue(props.maxDate)+ if (props.minDate && props.maxDate && props.minDate > props.maxDate)+ throw new RangeError('minDate exceeds maxDate')+ const unavailable = Boolean(+ value &&+ ((props.minDate && value < props.minDate) ||+ (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+ {...props}+ invalid={props.invalid || unavailable}+ validationMessage={+ unavailable+ ? (props.labels?.unavailable ?? defaultLabels.unavailable)+ : props.validationMessage+ }+ placeholder={props.placeholder ?? 'Select date'}+ displayValue={+ value+ ? new Intl.DateTimeFormat(props.locale?.code ?? 'en-US', {+ year: 'numeric',+ calendar: 'gregory',+ month: 'short',+ day: 'numeric',+ timeZone: 'UTC',+ }).format(requireDateValue(value)!)+ : ''+ }+ serializedValue={value ?? ''}+ onClear={() => commit(null)}+ onReset={() => {+ setValue(defaultValue)+ if (defaultValue !== value) onValueChange?.(defaultValue)+ }}+ >+ {children}+ </PickerRoot>+ </Context.Provider>+ )+}+type DatePickerTriggerProps = PickerTriggerProps+type DatePickerContentProps = PickerContentProps+type DatePickerClearProps = PickerClearProps+type DatePickerLabelProps = PickerLabelProps+type DatePickerValueProps = PickerValueProps+const DatePickerTrigger = PickerTrigger+const DatePickerClear = PickerClear+const DatePickerLabel = PickerLabel+const DatePickerValue = PickerValue+function DatePickerContent(props: DatePickerContentProps) {+ const { value } = useContext()+ return (+ <PickerContent {...props}>+ <Session key={value ?? ''} />+ </PickerContent>+ )+}+function Session() {+ const { value, commit, locale = enUS, minDate, maxDate, isDateUnavailable, labels } = useContext()+ const { close } = usePickerContext()+ const [displayMonth, setDisplayMonth] = React.useState(() =>+ getInitialMonth(value ?? formatDateValue(new Date()), minDate, maxDate),+ )+ return (+ <CalendarPanel+ value={value}+ onSelect={(next) => {+ commit(next)+ close()+ }}+ displayMonth={displayMonth}+ onDisplayMonthChange={setDisplayMonth}+ locale={locale}+ minDate={minDate}+ maxDate={maxDate}+ isDateUnavailable={isDateUnavailable}+ labels={{ ...defaultLabels, ...labels }}+ />+ )+}++export {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+ DatePickerValue,+}+export type {+ DatePickerClearProps,+ DatePickerContentProps,+ DatePickerLabelProps,+ DatePickerProps,+ DatePickerTriggerProps,+ DatePickerValueProps,+}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.tsxnew file mode 100644index 00000000000..5ff2a0ff554--- /dev/null+++ b/packages/dify-ui/src/date-time/date-time-picker/__tests__/index.spec.tsx@@ -0,0 +1,263 @@+import * as React from 'react'+import { page, userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import {+ DateTimePicker,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '../index'++it('keeps the natural calendar and month-picker height around a centered mobile trigger', async () => {+ const viewport = { width: window.innerWidth, height: window.innerHeight }+ await page.viewport(390, 640)+ try {+ const screen = await render(+ <div style={{ position: 'fixed', top: 318, left: 40 }}>+ <DateTimePicker timeZone="UTC" defaultValue={new Date('2025-01-15T13:30:00Z')}>+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ </div>,+ )+ const trigger = screen.getByRole('button', { name: /^Meeting / })+ await trigger.click()+ const popup = screen.getByRole('dialog', { name: 'Meeting', exact: true }).element()+ await expect.poll(() => popup.getBoundingClientRect().height).toBe(292)+ function expectVisiblePanel() {+ const bounds = popup.getBoundingClientRect()+ expect(bounds.top).toBeGreaterThanOrEqual(0)+ expect(bounds.bottom).toBeLessThanOrEqual(window.innerHeight)+ const anchor = trigger.element().getBoundingClientRect()+ expect(bounds.bottom <= anchor.top - 8 || bounds.top >= anchor.bottom + 8).toBe(true)+ expect(popup.scrollHeight).toBe(popup.clientHeight)+ const apply = screen+ .getByRole('button', { name: 'OK', exact: true })+ .element()+ .getBoundingClientRect()+ expect(apply.bottom).toBeLessThanOrEqual(bounds.bottom)+ }+ expectVisiblePanel()+ for (const element of popup.querySelectorAll<HTMLElement>('*')) {+ if (getComputedStyle(element).overflowY === 'auto')+ expect(element.scrollHeight).toBe(element.clientHeight)+ }+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ expect(popup.getBoundingClientRect().height).toBe(292)+ expectVisiblePanel()+ expect(screen.getByRole('listbox', { name: 'Month' }).element().clientHeight).toBe(192)+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ expectVisiblePanel()+ expect(screen.getByRole('listbox', { name: 'Hour' }).element().clientHeight).toBe(192)+ await userEvent.keyboard('{Escape}')+ await expect.element(screen.getByRole('button', { name: /^Meeting / })).toHaveFocus()+ } finally {+ await page.viewport(viewport.width, viewport.height)+ }+})++it.each([+ ['Tuesday, December 31st, 2024', 'December 2024', '2024-12-31'],+ ['Saturday, February 1st, 2025', 'February 2025', '2025-02-01'],+])('navigates to %s on selection and commits only on OK', async (day, month, date) => {+ const changed = vi.fn()+ const screen = await render(+ <DateTimePicker+ timeZone="UTC"+ defaultValue={new Date('2025-01-15T13:30:00Z')}+ onValueChange={changed}+ >+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ const trigger = screen.getByRole('button', { name: 'Meeting Jan 15, 2025, 1:30 PM' })+ await trigger.click()+ await screen.getByRole('button', { name: day, exact: true }).click()+ await expect.element(screen.getByRole('grid', { name: month })).toBeInTheDocument()+ await expect.element(screen.getByRole('status')).toHaveTextContent(month)+ await expect.element(screen.getByRole('button', { name: `${day}, selected` })).toHaveFocus()+ await expect.element(trigger).toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+ await userEvent.keyboard('{Escape}')+ await expect.element(trigger).toHaveFocus()+ await trigger.click()+ 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`))+})++it.each([+ ['2026-02-15', 258],+ ['2025-01-15', 292],+ ['2025-03-15', 326],+] as const)(+ 'preserves the %s calendar height when toggling month selection',+ async (date, height) => {+ const screen = await render(+ <DateTimePicker timeZone="UTC" defaultValue={new Date(`${date}T13:30:00Z`)}>+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ await screen.getByRole('button', { name: /^Meeting / }).click()+ const popup = screen.getByRole('dialog', { name: 'Meeting', exact: true }).element()+ await expect.poll(() => popup.getBoundingClientRect().height).toBe(height)+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ expect(popup.getBoundingClientRect().height).toBe(height)+ expect(popup.scrollHeight).toBe(popup.clientHeight)+ const footer = screen.getByRole('button', { name: 'OK' }).element().getBoundingClientRect()+ expect(footer.bottom).toBeLessThanOrEqual(popup.getBoundingClientRect().bottom)+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await expect.element(screen.getByRole('grid')).toBeInTheDocument()+ expect(popup.getBoundingClientRect().height).toBe(height)+ },+)++it.each(['ltr', 'rtl'] as const)(+ 'keeps focused time options visible after switching a height-limited %s popup',+ async (direction) => {+ const screen = await render(+ <DateTimePicker+ direction={direction}+ timeZone="UTC"+ defaultValue={new Date('2025-01-15T13:30:00Z')}+ >+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent style={{ maxHeight: 210 }} />+ </DateTimePicker>,+ )+ await screen.getByRole('button', { name: /^Meeting / }).click()+ const calendarPopup = screen.getByRole('dialog', { name: 'Meeting', exact: true }).element()+ await expect.poll(() => calendarPopup.getBoundingClientRect().height).toBe(210)+ const calendarHeight = calendarPopup.getBoundingClientRect().height+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ expect(calendarPopup.getBoundingClientRect().height).toBe(calendarHeight)+ await screen.getByRole('button', { name: /Choose month and year:/ }).click()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ const hours = screen.getByRole('listbox', { name: 'Hour' })+ const first = hours.getByRole('option', { name: '1', exact: true })+ await expect.element(first).toHaveFocus()+ const popup = screen.getByRole('dialog', { name: 'Meeting', exact: true })+ function fullyVisible(element: Element) {+ const bounds = popup.element().getBoundingClientRect()+ const option = element.getBoundingClientRect()+ return option.top >= bounds.top && option.bottom <= bounds.bottom+ }+ await expect.poll(() => fullyVisible(first.element())).toBe(true)+ expect(fullyVisible(screen.getByRole('button', { name: 'Now', exact: true }).element())).toBe(+ true,+ )+ expect(fullyVisible(screen.getByRole('button', { name: 'OK', exact: true }).element())).toBe(+ true,+ )+ expect(popup.element().scrollHeight).toBe(popup.element().clientHeight)+ expect(hours.element().clientHeight).toBeLessThan(192)+ await userEvent.keyboard('{End}')+ const last = hours.getByRole('option', { name: '12', exact: true })+ await expect.element(last).toHaveFocus()+ await expect.poll(() => fullyVisible(last.element())).toBe(true)+ expect(hours.element().scrollTop).toBe((last.element() as HTMLElement).offsetTop)+ },+)++describe('DateTimePicker', () => {+ it('discards a draft on Escape and leaves the existing instant unchanged on OK', async () => {+ const original = new Date('2024-11-03T06:30:00.000Z')+ const onValueChange = vi.fn()+ const screen = await render(+ <DateTimePicker timeZone="America/New_York" value={original} onValueChange={onValueChange}>+ <DateTimePickerLabel className="sr-only">Meeting time</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )++ await screen.getByRole('button', { name: /Meeting time / }).click()+ await expect.element(screen.getByRole('grid')).toBeInTheDocument()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ await expect.element(screen.getByRole('listbox', { name: 'Hour' })).toBeInTheDocument()+ await userEvent.keyboard('{Escape}')+ expect(onValueChange).not.toHaveBeenCalled()++ await screen.getByRole('button', { name: /Meeting time / }).click()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(onValueChange).not.toHaveBeenCalled()+ })+})++it('rejects a daylight-saving gap and lets the user repair it before committing', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DateTimePicker+ timeZone="America/New_York"+ defaultValue={new Date('2025-03-09T06:30:00Z')}+ onValueChange={changed}+ >+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ await screen.getByRole('button', { name: /^Meeting / }).click()+ await screen.getByRole('button', { name: /Pick Time:/ }).click()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ await expect+ .element(screen.getByRole('status'))+ .toHaveTextContent('This date or time is unavailable.')+ await expect.element(screen.getByRole('button', { name: 'OK', exact: true })).toBeDisabled()+ expect(changed).not.toHaveBeenCalled()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '3', exact: true })+ .click()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed.mock.calls[0]?.[0].toISOString()).toBe('2025-03-09T07:30:00.000Z')+})++it.each([+ ['Asia/Shanghai', '10:23 PM'],+ ['America/New_York', '10:23 AM'],+])(+ 'keeps Now in the draft and commits the current instant in %s',+ async (timeZone, displayTime) => {+ vi.setSystemTime(new Date('2026-09-28T14:23:00Z'))+ try {+ const changed = vi.fn()+ const screen = await render(+ <DateTimePicker+ timeZone={timeZone}+ defaultValue={new Date('2025-01-15T13:30:00Z')}+ onValueChange={changed}+ >+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>,+ )+ await screen.getByRole('button', { name: /^Meeting / }).click()+ await screen.getByRole('button', { name: 'Now' }).click()+ await expect+ .element(screen.getByRole('button', { name: `Pick Time: ${displayTime}` }))+ .toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith(new Date('2026-09-28T14:23:00Z'))+ await expect+ .element(screen.getByRole('button', { name: `Meeting Sep 28, 2026, ${displayTime}` }))+ .toHaveFocus()+ } finally {+ vi.useRealTimers()+ }+ },+)diff --git a/packages/dify-ui/src/date-time/date-time-picker/__tests__/zoned-value.spec.ts b/packages/dify-ui/src/date-time/date-time-picker/__tests__/zoned-value.spec.tsnew file mode 100644index 00000000000..ece75782b82--- /dev/null+++ b/packages/dify-ui/src/date-time/date-time-picker/__tests__/zoned-value.spec.ts@@ -0,0 +1,25 @@+import { getPossibleInstants, resolveZonedWallTime } from '../zoned-value'++describe('zoned date-time resolution', () => {+ it('rejects a wall time skipped by daylight saving', () => {+ expect(getPossibleInstants({ date: '2024-03-10', time: '02:30' }, 'America/New_York')).toEqual(+ [],+ )+ })++ it('preserves a previously selected instant during a repeated wall time', () => {+ const wall = { date: '2024-11-03', time: '01:30' }+ const candidates = getPossibleInstants(wall, 'America/New_York')+ expect(candidates).toHaveLength(2)+ expect(candidates[0]?.toISOString()).toBe('2024-11-03T05:30:00.000Z')+ expect(candidates[1]?.toISOString()).toBe('2024-11-03T06:30:00.000Z')+ expect(resolveZonedWallTime(wall, 'America/New_York', candidates[1])).toEqual(candidates[1])+ })+})++it('preserves sub-minute precision for an unchanged repeated wall time', () => {+ const original = new Date('2024-11-03T06:30:42.123Z')+ expect(+ resolveZonedWallTime({ date: '2024-11-03', time: '01:30' }, 'America/New_York', original),+ ).toEqual(original)+})diff --git a/packages/dify-ui/src/date-time/date-time-picker/index.stories.tsx b/packages/dify-ui/src/date-time/date-time-picker/index.stories.tsxnew file mode 100644index 00000000000..b0cd3c05020--- /dev/null+++ b/packages/dify-ui/src/date-time/date-time-picker/index.stories.tsx@@ -0,0 +1,227 @@+import type { Meta, StoryObj } from '@storybook/react-vite'+import { arTN } from '@daypicker/react/locale/ar-TN'+import { faIR } from '@daypicker/react/locale/fa-IR'+import * as React from 'react'+import { expect, waitFor, within } from 'storybook/test'+import {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from './index'++const meta = {+ title: 'Base/Form/Date Time Picker',+ component: DateTimePicker,+ args: {+ timeZone: 'UTC',+ children: null,+ },+ parameters: {+ layout: 'centered',+ docs: { story: { autoplay: false } },+ a11y: { config: { rules: [{ id: 'color-contrast', enabled: true }] } },+ },+ tags: ['autodocs'],+} satisfies Meta<typeof DateTimePicker>++export default meta+type Story = StoryObj<typeof meta>++function DateTimePickerDemo({ timeZone = 'UTC' }: { timeZone?: string }) {+ const [value, setValue] = React.useState<Date | null>(() => new Date('2025-01-15T13:30:00Z'))+ return (+ <div className="grid gap-1">+ <DateTimePicker timeZone={timeZone} value={value} onValueChange={setValue}>+ <DateTimePickerLabel>Meeting time</DateTimePickerLabel>+ <div className="flex items-center gap-1">+ <DateTimePickerTrigger />+ <DateTimePickerClear aria-label="Clear meeting time" />+ </div>+ <DateTimePickerContent />+ </DateTimePicker>+ </div>+ )+}++export const Default: Story = {+ render: () => <DateTimePickerDemo />,+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ const trigger = within(canvasElement).getByRole('button', {+ name: 'Meeting time Jan 15, 2025, 1:30 PM',+ })+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ await userEvent.click(trigger)+ await userEvent.click(await body.findByRole('button', { name: 'Thursday, January 16th, 2025' }))+ await expect(trigger).toHaveAccessibleName('Meeting time Jan 15, 2025, 1:30 PM')+ await userEvent.click(body.getByRole('button', { name: /Pick Time:/ }))+ const hours = within(await body.findByRole('listbox', { name: 'Hour' }))+ await waitFor(() => expect(hours.getByRole('option', { name: '1' })).toHaveFocus())+ await userEvent.keyboard('{ArrowDown}')+ await userEvent.click(body.getByRole('button', { name: 'OK' }))+ await waitFor(() => expect(trigger).toHaveFocus())+ await expect(trigger).toHaveAccessibleName('Meeting time Jan 16, 2025, 2:30 PM')+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ },+}++export const RTL: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'A local direction override applies to both calendar and time views, including the portaled popup. Dates use Arabic formatting with English action labels. Changing views preserves the draft; Escape discards it.',+ },+ },+ },+ render: () => (+ <DateTimePicker+ direction="rtl"+ locale={arTN}+ timeZone="Asia/Shanghai"+ defaultValue={new Date('2025-01-15T13:30:00Z')}+ hourCycle={24}+ >+ <DateTimePickerLabel className="sr-only">Meeting time</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ ),+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ const trigger = within(canvasElement).getByRole('button', { name: /^Meeting time / })+ await userEvent.click(trigger)+ await expect(await body.findByRole('dialog', { name: 'Meeting time' })).toHaveAttribute(+ 'dir',+ 'rtl',+ )+ await userEvent.click(body.getByRole('button', { name: /Pick Time:/ }))+ const hours = await body.findByRole('listbox', { name: 'Hour' })+ const minutes = body.getByRole('listbox', { name: 'Minute' })+ await expect(hours.getBoundingClientRect().left).toBeGreaterThan(+ minutes.getBoundingClientRect().left,+ )+ await waitFor(() => expect(within(hours).getByRole('option', { name: '21' })).toHaveFocus())+ await userEvent.keyboard('{End}{ArrowDown}')+ await expect(within(hours).getByRole('option', { name: '23' })).toHaveFocus()+ await userEvent.click(body.getByRole('button', { name: 'Pick Date' }))+ await waitFor(() => expect(body.getByRole('grid')).toBeVisible())+ await userEvent.click(body.getByRole('button', { name: /Pick Time:/ }))+ await waitFor(() =>+ expect(+ within(body.getByRole('listbox', { name: 'Hour' })).getByRole('option', { name: '23' }),+ ).toHaveFocus(),+ )+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await userEvent.keyboard('{Enter}')+ await userEvent.click(await body.findByRole('button', { name: /Pick Time:/ }))+ await waitFor(() =>+ expect(+ within(body.getByRole('listbox', { name: 'Hour' })).getByRole('option', { name: '21' }),+ ).toHaveFocus(),+ )+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ },+}++export const NewYork: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'This example displays dates and Now in America/New_York, independently of your browser time zone.',+ },+ },+ },+ render: () => <DateTimePickerDemo timeZone="America/New_York" />,+}++export const Calendar = {+ render: () => <DateTimePickerDemo />,+ name: 'Calendar (open preview)',+ tags: ['!autodocs'],+ play: async ({ canvasElement, userEvent }) => {+ await userEvent.click(within(canvasElement).getByRole('button', { name: /^Meeting time / }))+ const dialog = await within(canvasElement.ownerDocument.body).findByRole('dialog', {+ name: 'Meeting time',+ })+ await waitFor(() => expect(dialog).toBeVisible())+ },+} satisfies Story+export const ConstrainedHeight: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'An explicit 210px maxHeight opts into scrolling for the calendar and individual columns while keeping confirmation actions visible. Normal content uses its natural height; this is not the mobile default.',+ },+ },+ },+ render: () => (+ <DateTimePicker timeZone="UTC" defaultValue={new Date('2025-01-15T13:30:00Z')}>+ <DateTimePickerLabel className="sr-only">Meeting time</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent style={{ maxHeight: 210 }} />+ </DateTimePicker>+ ),+}++export const Time: Story = {+ ...Calendar,+ name: 'Time (open preview)',+ play: async (context) => {+ await Calendar.play(context)+ const { canvasElement, userEvent } = context+ await userEvent.click(+ await within(canvasElement.ownerDocument.body).findByRole('button', { name: /Pick Time:/ }),+ )+ },+}+export const MonthAndYear: Story = {+ ...Calendar,+ name: 'Month and year (open preview)',+ play: async (context) => {+ await Calendar.play(context)+ const { canvasElement, userEvent } = context+ await userEvent.click(+ await within(canvasElement.ownerDocument.body).findByRole('button', {+ name: /Choose month and year:/,+ }),+ )+ },+}+export const PersianNumbers: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'Persian numerals across calendar, year and time columns. Native and ASCII digits both locate options. Values remain Gregorian and serialize independently of locale. Action labels use the English defaults; locale does not translate application copy.',+ },+ },+ },+ render: () => (+ <div dir="rtl" className="grid gap-1">+ <DateTimePicker+ locale={faIR}+ direction="rtl"+ timeZone="UTC"+ hourCycle={24}+ defaultValue={new Date('2025-01-15T10:05:00Z')}+ >+ <DateTimePickerLabel>Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ <DateTimePickerContent />+ </DateTimePicker>+ </div>+ ),+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ await userEvent.click(within(canvasElement).getByRole('button', { name: /^Meeting / }))+ const dialog = await body.findByRole('dialog', { name: 'Meeting' })+ await waitFor(() => expect(within(dialog).getByRole('grid')).toBeVisible())+ },+}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.tsxnew file mode 100644index 00000000000..70728b668a4--- /dev/null+++ b/packages/dify-ui/src/date-time/date-time-picker/index.tsx@@ -0,0 +1,358 @@+'use client'++import type { CalendarPanelLabels, CalendarPanelProps } from '../date-picker/calendar-panel'+import type {+ PickerClearProps,+ PickerContentProps,+ PickerFieldProps,+ PickerLabelProps,+ PickerTriggerProps,+ PickerValueProps,+} from '../internal/picker-parts'+import type { TimePanelHandle, TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'+import type { ZonedWallTime } from './zoned-value'+import { useControlled } from '@base-ui/utils/useControlled'+import { enUS } from '@daypicker/react/locale/en-US'+import * as React from 'react'+import { Button } from '../../button'+import { CalendarPanel } from '../date-picker/calendar-panel'+import { getInitialMonth, requireDateValue } from '../date-picker/date-value'+import { PickerPanel, PickerPanelHeader } from '../internal/picker-panel'+import {+ PickerClear,+ PickerContent,+ PickerLabel,+ PickerRoot,+ PickerTrigger,+ PickerValue,+ usePickerContext,+} from '../internal/picker-parts'+import { TimePanel } from '../time-picker/time-panel'+import { getZonedWallTime, resolveZonedWallTime } from './zoned-value'++type DateTimePickerLabels = CalendarPanelLabels &+ TimePanelLabels & { pickTime: string; backToDate: string; now: string }+type DateTimePickerProps = PickerFieldProps &+ Pick<CalendarPanelProps, 'locale' | 'minDate' | 'maxDate' | 'isDateUnavailable'> &+ Pick<TimePanelProps, 'hourCycle'> & {+ /** An instant displayed in timeZone; null represents an empty field. */+ value?: Date | null+ defaultValue?: Date | null+ /** Called on OK, clearing or form reset; popup draft edits do not emit changes. */+ onValueChange?: (value: Date | null) => void+ timeZone: string+ isTimeUnavailable?: (wall: Readonly<ZonedWallTime>) => boolean+ labels?: Partial<DateTimePickerLabels>+ }+type ContextValue = Omit<+ DateTimePickerProps,+ 'value' | 'defaultValue' | 'onValueChange' | 'children'+> & {+ value: Exclude<DateTimePickerProps['value'], undefined>+ commit: NonNullable<DateTimePickerProps['onValueChange']>+}+const Context = React.createContext<ContextValue | null>(null)+function useContext() {+ const context = React.useContext(Context)+ if (!context) throw new Error('DateTimePicker parts require DateTimePicker.')+ return context+}+const defaultLabels: DateTimePickerLabels = {+ previousMonth: 'Previous month',+ nextMonth: 'Next month',+ chooseMonthAndYear: 'Choose month and year',+ month: 'Month',+ year: 'Year',+ cancel: 'Cancel',+ apply: 'OK',+ hour: 'Hour',+ minute: 'Minute',+ period: 'Period',+ am: 'AM',+ pm: 'PM',+ pickTime: 'Pick Time',+ backToDate: 'Pick Date',+ now: 'Now',+ unavailable: 'This date or time is unavailable.',+}++function DateTimePicker({+ value: valueProp,+ defaultValue = null,+ onValueChange,+ children,+ ...props+}: DateTimePickerProps) {+ const [value, setValue] = useControlled({+ controlled: valueProp,+ default: defaultValue,+ name: 'DateTimePicker',+ })+ if (value && Number.isNaN(value.getTime())) throw new RangeError('Invalid DateTimePicker value')+ if (props.minDate) requireDateValue(props.minDate)+ if (props.maxDate) requireDateValue(props.maxDate)+ if (props.minDate && props.maxDate && props.minDate > props.maxDate)+ throw new RangeError('minDate exceeds maxDate')+ const wall = value ? getZonedWallTime(value, props.timeZone) : null+ const unavailable = Boolean(+ wall &&+ ((props.minDate && wall.date < props.minDate) ||+ (props.maxDate && wall.date > props.maxDate) ||+ 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+ {...props}+ invalid={props.invalid || unavailable}+ validationMessage={+ unavailable+ ? (props.labels?.unavailable ?? defaultLabels.unavailable)+ : props.validationMessage+ }+ placeholder={props.placeholder ?? 'Select date and time'}+ displayValue={+ value+ ? new Intl.DateTimeFormat(props.locale?.code ?? 'en-US', {+ year: 'numeric',+ calendar: 'gregory',+ month: 'short',+ day: 'numeric',+ hour: 'numeric',+ minute: '2-digit',+ timeZone: props.timeZone,+ hour12: props.hourCycle !== 24,+ }).format(value)+ : ''+ }+ serializedValue={value?.toISOString() ?? ''}+ onClear={() => commit(null)}+ onReset={() => {+ setValue(defaultValue)+ if (defaultValue?.getTime() !== value?.getTime()) onValueChange?.(defaultValue)+ }}+ >+ {children}+ </PickerRoot>+ </Context.Provider>+ )+}+type DateTimePickerTriggerProps = PickerTriggerProps+type DateTimePickerContentProps = PickerContentProps+type DateTimePickerClearProps = PickerClearProps+type DateTimePickerLabelProps = PickerLabelProps+type DateTimePickerValueProps = PickerValueProps+const DateTimePickerTrigger = PickerTrigger+const DateTimePickerClear = PickerClear+const DateTimePickerLabel = PickerLabel+const DateTimePickerValue = PickerValue+function DateTimePickerContent(props: DateTimePickerContentProps) {+ const { value, timeZone } = useContext()+ return (+ <PickerContent {...props}>+ <Session key={`${value?.getTime() ?? ''}-${timeZone}`} />+ </PickerContent>+ )+}+function Session() {+ const {+ value,+ commit,+ timeZone,+ locale = enUS,+ minDate,+ maxDate,+ isDateUnavailable,+ isTimeUnavailable,+ labels,+ hourCycle,+ } = useContext()+ const { close } = usePickerContext()+ const panelRef = React.useRef<TimePanelHandle>(null)+ const [draft, setDraft] = React.useState(() => getZonedWallTime(value ?? new Date(), timeZone))+ const [displayMonth, setDisplayMonth] = React.useState(() =>+ getInitialMonth(draft.date, minDate, maxDate),+ )+ const [view, setView] = React.useState<'date' | 'time'>('date')+ const ref = React.useRef<HTMLDivElement>(null)+ const text = { ...defaultLabels, ...labels }+ function availableInstant(candidate: typeof draft) {+ const instant = resolveZonedWallTime(candidate, timeZone, value)+ if (+ !instant ||+ (minDate && candidate.date < minDate) ||+ (maxDate && candidate.date > maxDate) ||+ isDateUnavailable?.(candidate.date) ||+ isTimeUnavailable?.(candidate)+ )+ return null+ return instant+ }+ const unavailable = !availableInstant(draft)+ const timeText = new Intl.DateTimeFormat(locale.code ?? 'en-US', {+ hour: 'numeric',+ minute: '2-digit',+ hour12: hourCycle !== 24,+ timeZone: 'UTC',+ }).format(new Date(`2025-01-01T${draft.time}:00Z`))+ const [scrollRequest, requestScroll] = React.useReducer((value: number) => value + 1, 0)+ function setNow() {+ requestScroll()+ const next = getZonedWallTime(new Date(), timeZone)+ setDraft(next)+ setDisplayMonth(getInitialMonth(next.date, minDate, maxDate))+ }+ const errorId = React.useId()+ React.useEffect(() => {+ const frame = requestAnimationFrame(() => {+ const target =+ ref.current?.querySelector<HTMLElement>(+ '[role="grid"] button[tabindex="0"], [role="option"][aria-selected="true"]',+ ) ?? ref.current?.querySelector<HTMLElement>('button:not(:disabled)')+ target?.focus({ preventScroll: true })+ target?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'instant' })+ })+ return () => cancelAnimationFrame(frame)+ }, [view])+ function changeView(next: 'date' | 'time') {+ if (view === 'time') {+ const time = panelRef.current?.settle() ?? draft.time+ setDraft((previous) => ({ ...previous, time }))+ }+ ref.current?.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true })+ setView(next)+ }+ const apply = (+ <Button+ variant="primary"+ className="min-w-16"+ size="small"+ disabled={unavailable}+ aria-describedby={unavailable ? errorId : undefined}+ onClick={() => {+ const next = { ...draft, time: panelRef.current?.settle() ?? draft.time }+ setDraft(next)+ const instant = availableInstant(next)+ if (instant) {+ commit(instant)+ close()+ }+ }}+ >+ {text.apply}+ </Button>+ )+ return (+ <div ref={ref} className="flex min-h-0 flex-col overflow-hidden">+ {view === 'date' ? (+ <CalendarPanel+ value={draft.date}+ onSelect={(date) => setDraft({ ...draft, date })}+ displayMonth={displayMonth}+ onDisplayMonthChange={setDisplayMonth}+ locale={locale}+ timeZone={timeZone}+ minDate={minDate}+ maxDate={maxDate}+ isDateUnavailable={isDateUnavailable}+ labels={text}+ footer={+ <>+ <Button+ size="small"+ variant="secondary-accent"+ className="gap-1 px-1.5"+ aria-label={`${text.pickTime}: ${timeText}`}+ onClick={() => changeView('time')}+ >+ <span+ className="i-ri-time-line size-3 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ aria-hidden="true"+ />+ {timeText}+ </Button>+ <div className="flex gap-1">+ <Button size="small" variant="ghost-accent" onClick={setNow}>+ {text.now}+ </Button>+ {apply}+ </div>+ </>+ }+ />+ ) : (+ <PickerPanel+ header={<PickerPanelHeader>{text.pickTime}</PickerPanelHeader>}+ footer={+ <>+ <Button+ size="small"+ variant="secondary-accent"+ className="gap-1 px-1.5"+ onClick={() => changeView('date')}+ >+ <span+ aria-hidden="true"+ className="i-ri-calendar-line size-3 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ />+ {text.backToDate}+ </Button>+ <div className="flex gap-1">+ <Button size="small" variant="ghost-accent" onClick={setNow}>+ {text.now}+ </Button>+ {apply}+ </div>+ </>+ }+ >+ <TimePanel+ ref={panelRef}+ scrollRequest={scrollRequest}+ value={draft.time}+ onValueChange={(update) =>+ setDraft((previous) => ({ ...previous, time: update(previous.time) }))+ }+ labels={text}+ locale={locale.code}+ hourCycle={hourCycle}+ />+ </PickerPanel>+ )}+ {unavailable && (+ <p+ id={errorId}+ role="status"+ className="shrink-0 px-2 system-xs-regular text-text-destructive"+ >+ {text.unavailable}+ </p>+ )}+ </div>+ )+}++export {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+ DateTimePickerValue,+}+export type {+ DateTimePickerClearProps,+ DateTimePickerContentProps,+ DateTimePickerLabelProps,+ DateTimePickerProps,+ DateTimePickerTriggerProps,+ DateTimePickerValueProps,+}diff --git a/packages/dify-ui/src/date-time/date-time-picker/zoned-value.ts b/packages/dify-ui/src/date-time/date-time-picker/zoned-value.tsnew file mode 100644index 00000000000..17bb32f5db8--- /dev/null+++ b/packages/dify-ui/src/date-time/date-time-picker/zoned-value.ts@@ -0,0 +1,53 @@+import { TZDate, tzOffset, tzScan } from '@date-fns/tz'+import { parseDateValue } from '../date-picker/date-value'+import { parseTimeValue } from '../time-picker/time-value'++type ZonedWallTime = { date: string; time: string }++function getZonedWallTime(value: Date, timeZone: string): ZonedWallTime {+ const zoned = new TZDate(value.getTime(), timeZone)+ const date = `${String(zoned.getFullYear()).padStart(4, '0')}-${String(zoned.getMonth() + 1).padStart(2, '0')}-${String(zoned.getDate()).padStart(2, '0')}`+ const time = `${String(zoned.getHours()).padStart(2, '0')}:${String(zoned.getMinutes()).padStart(2, '0')}`+ return { date, time }+}++function getPossibleInstants({ date, time }: ZonedWallTime, timeZone: string): Date[] {+ const civil = parseDateValue(date)+ const clock = parseTimeValue(time)+ if (!civil || !clock) return []++ const localDate = new Date(0)+ localDate.setUTCFullYear(civil.getFullYear(), civil.getMonth(), civil.getDate())+ localDate.setUTCHours(clock.hour, clock.minute, 0, 0)+ const localEpoch = localDate.getTime()+ const start = new Date(localEpoch - 48 * 60 * 60 * 1000)+ const end = new Date(localEpoch + 48 * 60 * 60 * 1000)+ const offsets = new Set([tzOffset(timeZone, start), tzOffset(timeZone, end)])+ for (const transition of tzScan(timeZone, { start, end })) {+ offsets.add(transition.offset)+ offsets.add(transition.offset - transition.change)+ }++ return [...offsets]+ .map((offset) => new Date(localEpoch - offset * 60 * 1000))+ .filter((candidate) => {+ const wall = getZonedWallTime(candidate, timeZone)+ return wall.date === date && wall.time === time+ })+ .sort((a, b) => a.getTime() - b.getTime())+}++function resolveZonedWallTime(+ wall: ZonedWallTime,+ timeZone: string,+ preferredInstant?: Date | null,+): Date | null {+ if (preferredInstant) {+ const original = getZonedWallTime(preferredInstant, timeZone)+ if (original.date === wall.date && original.time === wall.time) return preferredInstant+ }+ return getPossibleInstants(wall, timeZone)[0] ?? null+}++export { getPossibleInstants, getZonedWallTime, resolveZonedWallTime }+export type { ZonedWallTime }diff --git a/packages/dify-ui/src/date-time/internal/option-column.tsx b/packages/dify-ui/src/date-time/internal/option-column.tsxnew file mode 100644index 00000000000..c8ba8bac7af--- /dev/null+++ b/packages/dify-ui/src/date-time/internal/option-column.tsx@@ -0,0 +1,313 @@+'use client'++import { useStableCallback } from '@base-ui/utils/useStableCallback'+import { useTimeout } from '@base-ui/utils/useTimeout'+import * as React from 'react'+import { cn } from '../../cn'++type OptionColumnHandle = { settle: () => number }++type OptionColumnProps = {+ ref?: React.Ref<OptionColumnHandle>+ label: string+ normalizeDigits: (text: string) => string+ value: number+ options: { value: number; label: string }[]+ onValueChange: (value: number) => void+ onEscape?: () => void+ scrollRequest?: number+ focusOnMount?: boolean+}++function OptionColumn({+ ref: handleRef,+ label,+ normalizeDigits,+ value,+ options,+ onValueChange,+ focusOnMount,+ onEscape,+ scrollRequest = 0,+}: OptionColumnProps) {+ const ref = React.useRef<HTMLDivElement>(null)+ const id = React.useId()+ const selectedIndex = options.findIndex((option) => option.value === value)+ const tabbableIndex = Math.max(0, selectedIndex)+ const searchRef = React.useRef({ text: '', time: 0, startIndex: 0 })+ React.useEffect(() => {+ searchRef.current = { text: '', time: 0, startIndex: 0 }+ }, [normalizeDigits])+ const gestureRef = React.useRef({ active: false, moved: false, touching: false })+ const quietTimer = useTimeout()+ const cancelGesture = useStableCallback(() => {+ quietTimer.clear()+ gestureRef.current.active = false+ gestureRef.current.moved = false+ })++ function scrollToOption(option: HTMLElement, smooth = false) {+ const column = ref.current+ if (!column) return+ column.scrollTo({+ top: option.offsetTop,+ behavior:+ smooth &&+ !column.ownerDocument.defaultView?.matchMedia('(prefers-reduced-motion: reduce)').matches+ ? 'smooth'+ : 'instant',+ })+ }+ function nearestOption() {+ const column = ref.current+ if (!column) return undefined+ return Array.from(column.querySelectorAll<HTMLElement>('[role="option"]')).reduce<+ HTMLElement | undefined+ >(+ (nearest, option) =>+ !nearest ||+ Math.abs(option.offsetTop - column.scrollTop) <+ Math.abs(nearest.offsetTop - column.scrollTop)+ ? option+ : nearest,+ undefined,+ )+ }+ React.useImperativeHandle(handleRef, () => ({+ settle() {+ const option =+ gestureRef.current.active && gestureRef.current.moved ? nearestOption() : undefined+ cancelGesture()+ if (option) {+ scrollToOption(option)+ return Number(option.dataset.optionValue)+ }+ return value+ },+ }))+ const finishGesture = React.useEffectEvent(() => {+ if (!gestureRef.current.active || gestureRef.current.touching) return+ const option = gestureRef.current.moved ? nearestOption() : undefined+ cancelGesture()+ if (!option) return+ const next = Number(option.dataset.optionValue)+ if (next !== value) onValueChange(next)+ if (ref.current?.contains(ref.current.ownerDocument.activeElement))+ option.focus({ preventScroll: true })+ scrollToOption(option, true)+ })+ const updateGesture = React.useEffectEvent(() => {+ const option = nearestOption()+ if (!option) return+ const next = Number(option.dataset.optionValue)+ if (next !== value) onValueChange(next)+ })+ React.useEffect(() => {+ const column = ref.current+ if (!column) return+ const supportsScrollEnd = 'onscrollend' in column+ function begin() {+ quietTimer.clear()+ if (!gestureRef.current.active) {+ gestureRef.current = {+ ...gestureRef.current,+ active: true,+ moved: false,+ }+ }+ quietTimer.start(150, () => {+ if (gestureRef.current.touching) return+ if (!gestureRef.current.moved) cancelGesture()+ else if (!supportsScrollEnd) finishGesture()+ })+ }+ function onWheel(event: WheelEvent) {+ if (!event.ctrlKey && event.deltaY !== 0) begin()+ }+ function onTouchStart() {+ gestureRef.current.touching = true+ begin()+ }+ function onTouchEnd() {+ gestureRef.current.touching = false+ if (!gestureRef.current.moved) cancelGesture()+ if (!supportsScrollEnd && gestureRef.current.moved) scheduleFinish()+ }+ function scheduleFinish() {+ quietTimer.clear()+ quietTimer.start(150, () => finishGesture())+ }+ function onScroll() {+ if (!gestureRef.current.active) return+ gestureRef.current.moved = true+ updateGesture()+ if (!supportsScrollEnd) scheduleFinish()+ }+ function onScrollEnd() {+ finishGesture()+ }+ column.addEventListener('wheel', onWheel, { passive: true })+ column.addEventListener('touchstart', onTouchStart, { passive: true })+ column.addEventListener('touchend', onTouchEnd, { passive: true })+ column.addEventListener('touchcancel', onTouchEnd, { passive: true })+ column.addEventListener('scroll', onScroll, { passive: true })+ if (supportsScrollEnd) column.addEventListener('scrollend', onScrollEnd)+ return () => {+ cancelGesture()+ column.removeEventListener('wheel', onWheel)+ column.removeEventListener('touchstart', onTouchStart)+ column.removeEventListener('touchend', onTouchEnd)+ column.removeEventListener('touchcancel', onTouchEnd)+ column.removeEventListener('scroll', onScroll)+ column.removeEventListener('scrollend', onScrollEnd)+ }+ }, [cancelGesture, quietTimer])++ // Entry and Now are explicit positioning commands, never gesture-driven selections.+ React.useLayoutEffect(() => {+ cancelGesture()+ const column = ref.current+ const selected = column?.querySelector<HTMLElement>('[aria-selected="true"]')+ if (selected && column) {+ column.scrollTo({+ top: selected.offsetTop,+ behavior: 'instant',+ })+ }+ }, [scrollRequest, cancelGesture])++ React.useEffect(() => {+ if (!focusOnMount) return+ const frame = requestAnimationFrame(() =>+ ref.current+ ?.querySelector<HTMLElement>('[aria-selected="true"]')+ ?.focus({ preventScroll: true }),+ )+ return () => cancelAnimationFrame(frame)+ }, [focusOnMount])++ function focusValue(next: number, smooth = false) {+ cancelGesture()+ onValueChange(next)+ const option = ref.current?.querySelector<HTMLElement>(`[data-option-value="${next}"]`)+ if (!option) return+ option.focus({ preventScroll: true })+ scrollToOption(option, smooth)+ }++ return (+ <div+ role="listbox"+ tabIndex={-1}+ aria-orientation="vertical"+ ref={ref}+ aria-label={label}+ className="relative flex h-full min-h-0 min-w-0 flex-1 scrollbar-none flex-col items-stretch gap-0.5 overflow-y-auto overscroll-none scroll-auto after:pointer-events-none after:h-[max(0px,calc(100%-1.625rem))] after:shrink-0 after:content-['']"+ onBlur={(event) => {+ if (!event.currentTarget.contains(event.relatedTarget))+ searchRef.current = { text: '', time: 0, startIndex: 0 }+ }}+ onKeyDown={(event) => {+ if (event.key === 'Escape') cancelGesture()+ if (event.key === 'Escape' && onEscape) {+ event.preventDefault()+ event.stopPropagation()+ onEscape()+ return+ }+ if (event.altKey || event.ctrlKey || event.metaKey || event.nativeEvent.isComposing) return+ if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End'].includes(event.key))+ searchRef.current = { text: '', time: 0, startIndex: 0 }+ if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown'].includes(event.key)) {+ event.preventDefault()+ event.stopPropagation()+ const currentOption =+ gestureRef.current.active && gestureRef.current.moved+ ? nearestOption()+ : (event.target as HTMLElement)+ const currentValue = Number(currentOption?.dataset.optionValue)+ const currentIndex = Math.max(+ 0,+ options.findIndex((option) => option.value === currentValue),+ )+ const step = event.key.startsWith('Page') ? 5 : 1+ const delta = event.key.endsWith('Up') ? -step : step+ const nextIndex = Math.max(0, Math.min(options.length - 1, currentIndex + delta))+ const option = options[nextIndex]+ if (option) focusValue(option.value)+ return+ }+ if (event.key === 'Home' || event.key === 'End') {+ event.preventDefault()+ event.stopPropagation()+ const option = event.key === 'Home' ? options[0] : options.at(-1)+ if (option) focusValue(option.value)+ } else if (+ !event.ctrlKey &&+ !event.metaKey &&+ !event.altKey &&+ !event.nativeEvent.isComposing &&+ Array.from(event.key).length === 1 &&+ event.key !== ' '+ ) {+ event.preventDefault()+ event.stopPropagation()+ const now = Date.now()+ const previous = searchRef.current+ let text = now - previous.time < 1000 ? previous.text : ''+ let startIndex = text ? previous.startIndex : tabbableIndex + 1+ const key = event.key.toLowerCase()+ // Repeated letters cycle; repeated digits must still form values such as 11 or 55.+ if (+ text === key &&+ !/^\d$/.test(normalizeDigits(key)) &&+ !options.some((option) => option.label.toLowerCase().startsWith(key + key))+ ) {+ text = ''+ startIndex = tabbableIndex + 1+ }+ text += key+ searchRef.current = { text, time: now, startIndex }+ const normalized = normalizeDigits(text)+ const numeric = /^\d+$/.test(normalized)+ let match = numeric+ ? options.find((option) => option.value === Number(normalized))+ : undefined+ if (!numeric) {+ for (let offset = 0; offset < options.length; offset++) {+ const option = options[(startIndex + offset) % options.length]!+ if (option.label.toLowerCase().startsWith(text)) {+ match = option+ break+ }+ }+ }+ if (match) focusValue(match.value)+ else if (!numeric) searchRef.current = { text: '', time: 0, startIndex: 0 }+ }+ }}+ >+ {options.map((option, index) => (+ <button+ key={option.value}+ id={`${id}-${option.value}`}+ type="button"+ role="option"+ aria-selected={option.value === value}+ tabIndex={index === tabbableIndex ? 0 : -1}+ data-option-value={option.value}+ onClick={(event) => focusValue(option.value, event.detail > 0)}+ className={cn(+ 'aria-selected:bg-components-button-ghost-bg-hover',+ 'flex min-h-6 shrink-0 items-center justify-center rounded-md px-1 system-xs-medium text-text-secondary tabular-nums hover:not-aria-selected:bg-state-base-hover-subtle focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-state-accent-solid forced-colors:aria-selected:outline forced-colors:aria-selected:outline-[Highlight]',+ )}+ >+ {option.label}+ </button>+ ))}+ </div>+ )+}++export { OptionColumn }+export type { OptionColumnHandle }diff --git a/packages/dify-ui/src/date-time/internal/picker-panel.tsx b/packages/dify-ui/src/date-time/internal/picker-panel.tsxnew file mode 100644index 00000000000..5b74df6e8ee--- /dev/null+++ b/packages/dify-ui/src/date-time/internal/picker-panel.tsx@@ -0,0 +1,42 @@+import type * as React from 'react'+import { cn } from '../../cn'++type PickerPanelProps = React.ComponentProps<'div'> & {+ header?: React.ReactNode+ children: React.ReactNode+ footer?: React.ReactNode+ message?: React.ReactNode+}++function PickerPanel({ header, children, footer, message, className, ...props }: PickerPanelProps) {+ return (+ <div {...props} className={cn('flex min-h-0 grow flex-col overflow-hidden', className)}>+ {header}+ {children}+ {message && <div className="shrink-0">{message}</div>}+ {footer && (+ <div className="flex h-10 shrink-0 items-center justify-between gap-1 border-t-[0.5px] border-divider-regular px-2">+ {footer}+ </div>+ )}+ </div>+ )+}++function PickerPanelHeader({ className, ...props }: React.ComponentProps<'div'>) {+ return (+ <div+ {...props}+ className={cn(+ 'flex h-11 shrink-0 items-center border-b-[0.5px] border-divider-regular px-4 system-md-semibold text-text-primary',+ className,+ )}+ />+ )+}++function PickerColumns({ className, ...props }: React.ComponentProps<'div'>) {+ return <div {...props} className={cn('flex h-52 min-h-0 grow gap-1 p-2', className)} />+}++export { PickerColumns, PickerPanel, PickerPanelHeader }diff --git a/packages/dify-ui/src/date-time/internal/picker-parts.tsx b/packages/dify-ui/src/date-time/internal/picker-parts.tsxnew file mode 100644index 00000000000..6c783e1298c--- /dev/null+++ b/packages/dify-ui/src/date-time/internal/picker-parts.tsx@@ -0,0 +1,400 @@+'use client'++import type { IconButtonProps } from '../../icon-button'+import type { PopoverContentProps, PopoverProps, PopoverTriggerProps } from '../../popover'+import { useMergedRefs } from '@base-ui/utils/useMergedRefs'+import * as React from 'react'+import { cn } from '../../cn'+import { DirectionProvider, useDirection } from '../../direction-provider'+import { formLabelClassName } from '../../form-control-shared'+import { IconButton } from '../../icon-button'+import { Popover, PopoverContent, PopoverTrigger } from '../../popover'++type PickerOpenChangeDetails = Omit<+ Parameters<NonNullable<PopoverProps['onOpenChange']>>[1],+ 'preventUnmountOnClose'+>++type PickerFieldProps = Pick<PopoverProps, 'open' | 'defaultOpen'> & {+ /** Overrides DirectionProvider for this field and its popup; independent of locale. */+ direction?: DirectionProvider.Props['direction']+ placeholder?: string+ disabled?: boolean+ readOnly?: boolean+ required?: boolean+ requiredLabel?: string+ invalid?: boolean+ name?: string+ form?: string+ validationMessage?: string+ onOpenChange?: (open: boolean, details: PickerOpenChangeDetails) => void+ children: React.ReactNode+}++type PickerContextValue = Omit<PickerFieldProps, 'children'> & {+ displayValue: string+ serializedValue: string+ triggerId: string+ valueId: string+ labelId: string | undefined+ setLabelId: React.Dispatch<React.SetStateAction<string | undefined>>+ errorId: string+ requiredId: string+ triggerRef: React.RefObject<HTMLButtonElement | null>+ clear: () => void+ close: () => void+}++const PickerContext = React.createContext<PickerContextValue | null>(null)++function usePickerContext() {+ const context = React.useContext(PickerContext)+ if (!context) throw new Error('Picker parts must be inside their picker root.')+ return context+}++function PickerRoot({+ displayValue,+ serializedValue,+ onClear,+ onReset,+ children,+ ...props+}: PickerFieldProps & {+ displayValue: string+ serializedValue: string+ onClear: () => void+ onReset: () => void+}) {+ const inheritedDirection = useDirection()+ const direction = props.direction ?? inheritedDirection+ const id = React.useId()+ const [labelId, setLabelId] = React.useState<string>()+ const triggerRef = React.useRef<HTMLButtonElement>(null)+ const inputRef = React.useRef<HTMLInputElement>(null)+ const actionsRef = React.useRef<NonNullable<PopoverProps['actionsRef']>['current']>(null)+ const [validationAttempted, setValidationAttempted] = React.useState(false)+ const errorMessage = props.invalid+ ? (props.validationMessage ?? 'Choose a valid value.')+ : validationAttempted && props.required && !serializedValue+ ? (props.validationMessage ?? 'Choose a value.')+ : undefined+ const invalid = Boolean(errorMessage)+ React.useEffect(() => {+ inputRef.current?.setCustomValidity(+ props.invalid ? (props.validationMessage ?? 'Choose a valid value.') : '',+ )+ }, [props.invalid, props.validationMessage])+ const onResetEvent = React.useEffectEvent(onReset)+ React.useEffect(() => {+ const form = inputRef.current?.form+ if (!form) return+ function reset(event: Event) {+ queueMicrotask(() => {+ if (event.defaultPrevented) return+ setValidationAttempted(false)+ onResetEvent()+ actionsRef.current?.close()+ })+ }+ form.addEventListener('reset', reset)+ return () => form.removeEventListener('reset', reset)+ }, [props.form])++ return (+ <DirectionProvider direction={direction}>+ <PickerContext.Provider+ value={{+ ...props,+ direction,+ invalid,+ displayValue,+ serializedValue,+ triggerId: `${id}-trigger`,+ valueId: `${id}-value`,+ labelId,+ setLabelId,+ errorId: `${id}-error`,+ requiredId: `${id}-required`,+ triggerRef,+ clear: () => {+ if (props.disabled || props.readOnly) return+ triggerRef.current?.focus()+ onClear()+ actionsRef.current?.close()+ },+ close: () => actionsRef.current?.close(),+ }}+ >+ {props.required && (+ <span id={`${id}-required`} className="sr-only">+ {props.requiredLabel ?? 'Required'}+ </span>+ )}+ <input+ ref={inputRef}+ hidden+ tabIndex={-1}+ type="text"+ autoComplete="off"+ name={props.name}+ form={props.form}+ value={serializedValue}+ required={props.required}+ disabled={props.disabled}+ readOnly={props.readOnly}+ onChange={() => {}}+ onInvalid={(event) => {+ event.preventDefault()+ setValidationAttempted(true)+ const firstInvalid = inputRef.current?.form+ ? Array.from(inputRef.current.form.elements).find((element) =>+ element.matches('input:invalid, select:invalid, textarea:invalid'),+ )+ : undefined+ if (!firstInvalid || firstInvalid === inputRef.current) triggerRef.current?.focus()+ }}+ />+ <Popover+ open={props.open}+ defaultOpen={props.defaultOpen}+ onOpenChange={(open, details) => {+ if (open && (props.disabled || props.readOnly)) details.cancel()+ props.onOpenChange?.(open, details)+ }}+ actionsRef={actionsRef}+ >+ {children}+ </Popover>+ {errorMessage && (+ <span id={`${id}-error`} role="alert" className="system-xs-regular text-text-destructive">+ {errorMessage}+ </span>+ )}+ </PickerContext.Provider>+ </DirectionProvider>+ )+}++type PickerLabelProps = Omit<React.ComponentProps<'div'>, 'id'>++function isLabelTextInteraction(event: React.SyntheticEvent<HTMLDivElement>) {+ const path = event.nativeEvent.composedPath()+ const boundary = path.indexOf(event.currentTarget)+ const ElementConstructor = event.currentTarget.ownerDocument.defaultView?.Element+ if (boundary < 0 || !ElementConstructor) return false+ return !path+ .slice(0, boundary)+ .some(+ (target) =>+ target instanceof ElementConstructor &&+ target.matches(+ 'button,a[href],input,select,textarea,summary,[tabindex],[contenteditable]:not([contenteditable="false"]),[role="button"],[role="link"]',+ ),+ )+}++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+ triggerRef.current?.focus({ focusVisible: true })+ }}+ >+ {children}+ </div>+ )+}++type PickerTriggerProps = Omit<+ PopoverTriggerProps,+ 'handle' | 'payload' | 'openOnHover' | 'delay' | 'closeDelay' | 'render' | 'nativeButton' | 'ref'+> & {+ ref?: React.Ref<HTMLButtonElement>+}+function PickerTrigger({+ ref,+ children,+ className,+ disabled,+ 'aria-label': ariaLabel,+ 'aria-labelledby': ariaLabelledBy,+ 'aria-describedby': ariaDescribedBy,+ ...props+}: PickerTriggerProps) {+ const field = usePickerContext()+ const mergedRef = useMergedRefs(field.triggerRef, ref)+ const labelId = ariaLabelledBy ?? (ariaLabel ? undefined : field.labelId)+ return (+ <PopoverTrigger+ id={field.triggerId}+ dir={field.direction}+ aria-label={ariaLabel}+ aria-labelledby={+ labelId+ ? [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+ }+ aria-invalid={field.invalid || undefined}+ aria-disabled={field.readOnly || undefined}+ {...props}+ ref={mergedRef}+ disabled={field.disabled || disabled}+ className={(state) =>+ cn(+ 'flex h-8 w-63 max-w-full items-center justify-between gap-0.5 rounded-lg bg-components-input-bg-normal ps-3 pe-2 text-start system-sm-regular text-components-input-text-filled',+ 'hover:bg-state-base-hover-alt focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid data-disabled:cursor-not-allowed data-disabled:bg-components-input-bg-disabled data-popup-open:bg-state-base-hover-alt',+ !field.serializedValue && 'text-text-tertiary in-data-[theme=dark]:text-text-secondary',+ typeof className === 'function' ? className(state) : className,+ )+ }+ >+ {children ?? (+ <>+ <PickerValue />+ <span+ className="i-ri-calendar-line size-4 shrink-0 text-text-tertiary forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ aria-hidden="true"+ />+ </>+ )}+ </PopoverTrigger>+ )+}++type PickerValueProps = Omit<React.ComponentProps<'span'>, 'children' | 'id'> & {+ /** Receives the formatted committed value, or the placeholder when empty. */+ children?: React.ReactNode | ((displayValue: string) => React.ReactNode)+}+function PickerValue({ children, ...props }: PickerValueProps) {+ const field = usePickerContext()+ const displayValue = field.serializedValue ? field.displayValue : (field.placeholder ?? '')+ return (+ <span {...props} id={field.valueId}>+ {typeof children === 'function' ? children(displayValue) : (children ?? displayValue)}+ </span>+ )+}++// Preserve IconButton's accessible-name union when removing picker-owned props.+type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never++type PickerClearProps = DistributiveOmit<+ IconButtonProps,+ 'children' | 'size' | 'render' | 'nativeButton' | 'ref'+> & {+ ref?: React.Ref<HTMLButtonElement>+}+function PickerClear({ onClick, disabled, ...props }: PickerClearProps) {+ const field = usePickerContext()+ if (!field.serializedValue || field.readOnly) return null+ return (+ <IconButton+ {...props}+ size="lg"+ disabled={field.disabled || disabled}+ onClick={(event) => {+ onClick?.(event)+ if (!event.defaultPrevented) field.clear()+ }}+ >+ <span+ className="i-ri-close-line size-4 forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ aria-hidden="true"+ />+ </IconButton>+ )+}++type PickerContentProps = Omit<PopoverContentProps, 'children' | 'initialFocus' | 'render'>+function PickerContent({+ children,+ ref,+ className,+ 'aria-label': ariaLabel,+ 'aria-labelledby': ariaLabelledBy,+ ...props+}: PickerContentProps & { children: React.ReactNode }) {+ const { labelId } = usePickerContext()+ const direction = useDirection()+ const popupRef = React.useRef<HTMLDivElement>(null)+ const mergedRef = useMergedRefs(popupRef, ref)+ return (+ <PopoverContent+ placement="bottom-start"+ aria-label={ariaLabel}+ aria-labelledby={ariaLabelledBy ?? (ariaLabel ? undefined : labelId)}+ dir={direction}+ {...props}+ ref={mergedRef}+ className={(state) =>+ cn(+ 'forced-colors:[&_button:focus-visible]:outline-2 forced-colors:[&_button:focus-visible]:outline-[Highlight] forced-colors:[&_button:focus-visible]:outline-solid',+ 'flex w-63 max-w-(--available-width) flex-col overflow-hidden border-0 p-0 inset-ring-[0.5px] inset-ring-components-panel-border backdrop-blur-[5px]',+ typeof className === 'function' ? className(state) : className,+ )+ }+ initialFocus={() =>+ popupRef.current?.querySelector<HTMLElement>(+ '[data-picker-initial-focus], [role="grid"] button[tabindex="0"], [role="option"][aria-selected="true"]',+ ) ??+ popupRef.current?.querySelector<HTMLElement>('button:not(:disabled)') ??+ true+ }+ render={(popupProps, state) => <div {...popupProps}>{state.open ? children : null}</div>}+ >+ {children}+ </PopoverContent>+ )+}++export {+ PickerClear,+ PickerContent,+ PickerLabel,+ PickerRoot,+ PickerTrigger,+ PickerValue,+ usePickerContext,+}+export type {+ PickerClearProps,+ PickerContentProps,+ PickerFieldProps,+ PickerLabelProps,+ PickerTriggerProps,+ PickerValueProps,+}diff --git a/packages/dify-ui/src/date-time/internal/use-picker-numbers.ts b/packages/dify-ui/src/date-time/internal/use-picker-numbers.tsnew file mode 100644index 00000000000..a065de8304e--- /dev/null+++ b/packages/dify-ui/src/date-time/internal/use-picker-numbers.ts@@ -0,0 +1,20 @@+import * as React from 'react'++function usePickerNumbers(locale: Intl.LocalesArgument = 'en-US') {+ return React.useMemo(() => {+ const integer = new Intl.NumberFormat(locale, { useGrouping: false })+ const minute = new Intl.NumberFormat(locale, { useGrouping: false, minimumIntegerDigits: 2 })+ const digits = new Map(+ Array.from({ length: 10 }, (_, digit) => [integer.format(digit), String(digit)]),+ )+ return {+ numberingSystem: integer.resolvedOptions().numberingSystem,+ formatInteger: integer.format,+ formatMinute: minute.format,+ normalizeDigits: (text: string) =>+ Array.from(text, (char) => digits.get(char) ?? char).join(''),+ }+ }, [locale])+}++export { usePickerNumbers }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.tsxnew file mode 100644index 00000000000..82d9f7c8eb4--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/__tests__/index.spec.tsx@@ -0,0 +1,311 @@+import * as React from 'react'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { Dialog, DialogContent, DialogTitle } from '../../../dialog'+import { DirectionProvider } from '../../../direction-provider'+import { Field, FieldLabel } from '../../../field'+import {+ TimePicker,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+} from '../index'++it('allows a valid time to be reached through temporarily unavailable combinations', async () => {+ const changed = vi.fn()+ const screen = await render(+ <TimePicker+ defaultValue="09:30"+ onValueChange={changed}+ isTimeUnavailable={(time) => !['09:30', '10:00'].includes(time)}+ >+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 9:30 AM' }).click()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '10', exact: true })+ .click()+ await expect.element(screen.getByRole('button', { name: 'OK' })).toBeDisabled()+ await screen+ .getByRole('listbox', { name: 'Minute' })+ .getByRole('option', { name: '00', exact: true })+ .click()+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('10:00')+})++it('starts a fresh draft when controlled open changes without an open request', async () => {+ const changed = vi.fn()+ const view = (open: boolean, value: string) => (+ <TimePicker value={value} open={open} onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ )+ const screen = await render(view(true, '13:30'))+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ await screen.rerender(view(false, '13:30'))+ await screen.rerender(view(true, '09:45'))+ await expect+ .element(+ screen.getByRole('listbox', { name: 'Hour' }).getByRole('option', { name: '9', exact: true }),+ )+ .toHaveAttribute('aria-selected', 'true')+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(changed).not.toHaveBeenCalled()+})++it('honors canceled close requests without discarding the active draft', async () => {+ const changed = vi.fn()+ const screen = await render(+ <TimePicker+ defaultValue="13:30"+ onValueChange={changed}+ onOpenChange={(open, details) => {+ if (!open && details.reason === 'escape-key') details.cancel()+ }}+ >+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ await userEvent.keyboard('{Escape}')+ await expect+ .element(screen.getByRole('dialog', { name: 'Time', exact: true }))+ .toBeInTheDocument()+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('14:30')+})++it('supports 24-hour navigation and numeric minute locating', async () => {+ const changed = vi.fn()+ const screen = await render(+ <TimePicker hourCycle={24} defaultValue="13:30" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 13:30' }).click()+ await userEvent.keyboard('{End}')+ await userEvent.tab()+ await userEvent.keyboard('45')+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('23:45')+})++it('isolates draft option names and values from an enclosing field', async () => {+ const screen = await render(+ <form id="time-form">+ <Field name="appointment">+ <FieldLabel>Appointment</FieldLabel>+ <TimePicker name="appointment" defaultValue="13:30">+ <TimePickerLabel className="sr-only">Appointment</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ </Field>+ </form>,+ )+ await screen.getByRole('button', { name: 'Appointment 1:30 PM' }).click()+ await screen+ .getByRole('listbox', { name: 'Hour' })+ .getByRole('option', { name: '2', exact: true })+ .click()+ expect([+ ...new FormData(document.querySelector<HTMLFormElement>('#time-form')!).entries(),+ ]).toEqual([['appointment', '13:30']])+ const ids = [...document.querySelectorAll('[role="option"]')].map((element) => element.id)+ expect(new Set(ids).size).toBe(ids.length)+ await screen.getByRole('button', { name: 'OK' }).click()+ expect(+ new FormData(document.querySelector<HTMLFormElement>('#time-form')!).get('appointment'),+ ).toBe('14:30')+})++it('repositions all time columns when Now is clicked again without committing', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(new Date('2025-01-15T13:30:00Z').getTime())+ const changed = vi.fn()+ const screen = await render(+ <TimePicker timeZone="UTC" defaultValue="13:30" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ const column = screen.getByRole('listbox', { name: 'Minute' }).element()+ const selected = screen+ .getByRole('listbox', { name: 'Minute' })+ .getByRole('option', { name: '30', exact: true })+ .element() as HTMLElement+ await expect.poll(() => column.scrollTop).toBe(selected.offsetTop)+ column.scrollTo({ top: 0, behavior: 'instant' })+ await expect.poll(() => column.scrollTop).toBe(0)+ expect(changed).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'Now', exact: true }).click()+ await expect.poll(() => column.scrollTop).toBe(selected.offsetTop)+ await expect.element(screen.getByRole('button', { name: 'Now', exact: true })).toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+ vi.restoreAllMocks()+})++it('keeps a quarter-hour field reachable and rounds Now down to its current interval', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(new Date('2025-01-15T13:37:00Z').getTime())+ const changed = vi.fn()+ const screen = await render(+ <TimePicker timeZone="UTC" minuteStep={15} defaultValue="09:00" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 9:00 AM' }).click()+ expect(+ screen.getByRole('listbox', { name: 'Minute' }).element().querySelectorAll('[role="option"]'),+ ).toHaveLength(4)+ await screen.getByRole('button', { name: 'Now', exact: true }).click()+ expect(changed).not.toHaveBeenCalled()+ await expect+ .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')+ vi.restoreAllMocks()+})++it('discards a draft when Tab leaves the nonmodal picker inside a modal dialog', async () => {+ const changed = vi.fn()+ const screen = await render(+ <Dialog defaultOpen>+ <DialogContent>+ <DialogTitle>Settings</DialogTitle>+ <TimePicker defaultValue="13:30" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ <button type="button">Save settings</button>+ </DialogContent>+ </Dialog>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ await userEvent.keyboard('{ArrowDown}')+ await userEvent.tab()+ await userEvent.tab()+ await userEvent.tab()+ await expect.element(screen.getByRole('button', { name: 'Now', exact: true })).toHaveFocus()+ await userEvent.tab()+ await expect.element(screen.getByRole('button', { name: 'OK', exact: true })).toHaveFocus()+ await userEvent.tab()+ await expect.element(screen.getByRole('button', { name: 'Save settings' })).toHaveFocus()+ await expect+ .element(screen.getByRole('dialog', { name: 'Time', exact: true }))+ .not.toBeInTheDocument()+ await expect+ .element(screen.getByRole('dialog', { name: 'Settings', exact: true }))+ .toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+})++it('aligns pointer selections and immediately positions keyboard selections at the same top anchor', async () => {+ const screen = await render(+ <TimePicker defaultValue="13:30">+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ const hours = screen.getByRole('listbox', { name: 'Hour' })+ const column = hours.element()+ expect(column.scrollTop).toBe(0)+ await userEvent.keyboard('{ArrowDown}')+ await expect.element(hours.getByRole('option', { name: '2', exact: true })).toHaveFocus()+ expect(column.scrollTop).toBe(26)+ // Disable Playwright's retry alignment so the test measures the component's scrolling.+ await hours.getByRole('option', { name: '3', exact: true }).click({ scroll: 'none' })+ await expect.poll(() => column.scrollTop).toBe(52)+ await userEvent.keyboard('12')+ const last = hours.getByRole('option', { name: '12', exact: true }).element() as HTMLElement+ await expect.element(last).toHaveFocus()+ expect(column.scrollTop).toBe(last.offsetTop)+ await userEvent.keyboard('{Home}')+ expect(column.scrollTop).toBe(0)+ await userEvent.keyboard('{PageDown}')+ await expect.element(hours.getByRole('option', { name: '6', exact: true })).toHaveFocus()+ await userEvent.keyboard('{End}{ArrowDown}')+ await expect.element(last).toHaveFocus()+})++it('preserves draft selection after focus leaves and does not select hovered options', async () => {+ const changed = vi.fn()+ const screen = await render(+ <DirectionProvider direction="rtl">+ <TimePicker defaultValue="13:30" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ </DirectionProvider>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ await expect+ .element(screen.getByRole('dialog', { name: 'Time', exact: true }))+ .toHaveAttribute('dir', 'rtl')+ const hours = screen.getByRole('listbox', { name: 'Hour' })+ const minutes = screen.getByRole('listbox', { name: 'Minute' })+ expect(hours.element().getBoundingClientRect().left).toBeGreaterThan(+ minutes.element().getBoundingClientRect().left,+ )+ await userEvent.keyboard('{ArrowDown}')+ const selectedHour = hours.getByRole('option', { name: '2', exact: true })+ await expect.element(selectedHour).toHaveFocus()+ await expect.element(selectedHour).toHaveAttribute('aria-selected', 'true')+ await userEvent.tab()+ await expect.element(minutes.getByRole('option', { name: '30', exact: true })).toHaveFocus()+ await userEvent.hover(hours.getByRole('option', { name: '3', exact: true }))+ await expect.element(selectedHour).toHaveAttribute('aria-selected', 'true')+ await expect+ .element(hours.getByRole('option', { name: '3', exact: true }))+ .toHaveAttribute('aria-selected', 'false')+ expect(changed).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('14:30')+})++it('announces the complete custom displayed value including its timezone', async () => {+ const screen = await render(+ <TimePicker defaultValue="13:30">+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger>+ <TimePickerValue>+ {(displayValue) => (+ <>+ <span>{displayValue}</span> <span>UTC+08:00</span>+ </>+ )}+ </TimePickerValue>+ </TimePickerTrigger>+ <TimePickerContent />+ </TimePicker>,+ )+ await expect+ .element(screen.getByRole('button', { name: 'Time 1:30 PM UTC+08:00', exact: true }))+ .toBeVisible()+})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.tsxnew file mode 100644index 00000000000..92b9f25390b--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/__tests__/wheel.spec.tsx@@ -0,0 +1,229 @@+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { TimePicker, TimePickerContent, TimePickerLabel, TimePickerTrigger } from '../index'++async function renderPicker() {+ const changed = vi.fn()+ const screen = await render(+ <TimePicker defaultValue="13:30" timeZone="UTC" onValueChange={changed}>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>,+ )+ await screen.getByRole('button', { name: 'Time 1:30 PM' }).click()+ const hours = screen.getByRole('listbox', { name: 'Hour' })+ return { screen, hours, column: hours.element(), changed }+}++// Intent events are synthetic; scroll geometry, focus, smooth settling and submission use Chromium.+function moveGesture(column: Element, top: number, touch = false) {+ column.dispatchEvent(touch ? new Event('touchstart') : new WheelEvent('wheel', { deltaY: top }))+ column.scrollTo({ top, behavior: 'instant' })+ column.dispatchEvent(new Event('scroll'))+}++it('snaps a wheel gesture to the top and selects a draft without committing', async () => {+ const { screen, hours, column, changed } = await renderPicker()+ moveGesture(column, 67)+ column.dispatchEvent(new Event('scrollend'))+ await expect+ .element(hours.getByRole('option', { name: '4', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => column.scrollTop).toBe(78)+ expect(changed).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')+})++it('highlights the nearest top row during touch without snapping or moving focus until release', async () => {+ const { screen, hours, column, changed } = await renderPicker()+ const first = hours.getByRole('option', { name: '1', exact: true })+ const selectedBackground = getComputedStyle(first.element()).backgroundColor+ moveGesture(column, 67, true)+ const fourth = hours.getByRole('option', { name: '4', exact: true })+ await expect.element(fourth).toHaveAttribute('aria-selected', 'true')+ expect(getComputedStyle(fourth.element()).backgroundColor).toBe(selectedBackground)+ await expect.element(first).toHaveAttribute('aria-selected', 'false')+ await expect.element(first).toHaveFocus()+ expect(column.scrollTop).toBe(67)+ column.scrollTo({ top: 92, behavior: 'instant' })+ column.dispatchEvent(new Event('scroll'))+ const fifth = hours.getByRole('option', { name: '5', exact: true })+ await expect.element(fifth).toHaveAttribute('aria-selected', 'true')+ expect(column.scrollTop).toBe(92)+ expect(changed).not.toHaveBeenCalled()+ await expect.element(screen.getByRole('button', { name: 'Time 1:30 PM' })).toBeInTheDocument()+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ await expect.poll(() => column.scrollTop).toBe(104)+ await expect.element(fifth).toHaveFocus()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('17:30')+})++it('keeps a clicked target selected throughout positioning after interrupting a gesture', async () => {+ const { screen, hours, column, changed } = await renderPicker()+ moveGesture(column, 67, true)+ await expect+ .element(hours.getByRole('option', { name: '4', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ const target = hours.getByRole('option', { name: '6', exact: true })+ await target.click({ scroll: 'none' })+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ await expect.element(target).toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => column.scrollTop).toBe(130)+ await expect.element(target).toHaveAttribute('aria-selected', 'true')+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('18:30')+})++it('aligns AM and PM to the same top anchor for keyboard, click and touch selection', async () => {+ const { screen, changed } = await renderPicker()+ const period = screen.getByRole('listbox', { name: 'Period' })+ const column = period.element()+ const am = period.getByRole('option', { name: 'AM' })+ const pm = period.getByRole('option', { name: 'PM' })+ expect(column.scrollTop).toBe(26)+ await pm.click({ scroll: 'none' })+ await userEvent.keyboard('{ArrowUp}')+ await expect.element(am).toHaveFocus()+ expect(column.scrollTop).toBe(0)+ await pm.click({ scroll: 'none' })+ await expect.poll(() => column.scrollTop).toBe(26)+ moveGesture(column, 6, true)+ await expect.element(am).toHaveAttribute('aria-selected', 'true')+ expect(column.scrollTop).toBe(6)+ expect(changed).not.toHaveBeenCalled()+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('01:30')+})++it('settles both moving columns synchronously when OK is clicked', async () => {+ const { screen, column, changed } = await renderPicker()+ const minutes = screen.getByRole('listbox', { name: 'Minute' }).element()+ moveGesture(column, 67, true)+ moveGesture(minutes, 1050, true)+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('16:40')+})++it('continues keyboard navigation from the moving candidate and ignores its late scrollend', async () => {+ const { hours, column, changed } = await renderPicker()+ moveGesture(column, 67, true)+ await userEvent.keyboard('{ArrowDown}')+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ await expect.element(hours.getByRole('option', { name: '5', exact: true })).toHaveFocus()+ await expect+ .element(hours.getByRole('option', { name: '5', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ expect(column.scrollTop).toBe(104)+ expect(changed).not.toHaveBeenCalled()+})++it('lets Now override all moving columns and keeps focus on Now', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(new Date('2025-01-15T13:30:00Z').getTime())+ try {+ const { screen, hours, column, changed } = await renderPicker()+ moveGesture(column, 67, true)+ await screen.getByRole('button', { name: 'Now', exact: true }).click()+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ await expect+ .element(hours.getByRole('option', { name: '1', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ expect(column.scrollTop).toBe(0)+ await expect.element(screen.getByRole('button', { name: 'Now', exact: true })).toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+ } finally {+ vi.restoreAllMocks()+ }+})++it('discards an unfinished gesture on Escape and ignores detached scroll events', async () => {+ const { screen, column, changed } = await renderPicker()+ moveGesture(column, 67, true)+ await userEvent.keyboard('{Escape}')+ column.dispatchEvent(new Event('touchend'))+ column.dispatchEvent(new Event('scrollend'))+ await expect.element(screen.getByRole('button', { name: 'Time 1:30 PM' })).toHaveFocus()+ expect(changed).not.toHaveBeenCalled()+})++it('does not interpret an edge wheel or programmatic scrolling as selection', async () => {+ const { hours, column } = await renderPicker()+ column.dispatchEvent(new WheelEvent('wheel', { deltaY: -100 }))+ column.dispatchEvent(new Event('scrollend'))+ await expect+ .element(hours.getByRole('option', { name: '1', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ column.scrollTo({ top: 78, behavior: 'instant' })+ column.dispatchEvent(new Event('scroll'))+ column.dispatchEvent(new Event('scrollend'))+ await expect+ .element(hours.getByRole('option', { name: '1', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+})++it('does not lose an unfinished selection when only a modifier key is pressed', async () => {+ const { screen, column, changed } = await renderPicker()+ moveGesture(column, 67, true)+ await userEvent.keyboard('{Shift}')+ await screen.getByRole('button', { name: 'OK', exact: true }).click()+ expect(changed).toHaveBeenCalledExactlyOnceWith('16:30')+})++it('recognizes scrolling when the compositor moves before the passive wheel callback', async () => {+ const { hours, column } = await renderPicker()+ column.scrollTo({ top: 67, behavior: 'instant' })+ column.dispatchEvent(new WheelEvent('wheel', { deltaY: 67 }))+ column.dispatchEvent(new Event('scroll'))+ column.dispatchEvent(new Event('scrollend'))+ await expect+ .element(hours.getByRole('option', { name: '4', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => column.scrollTop).toBe(78)+})++it('settles through the quiet fallback when scrollend is unavailable', async () => {+ let owner: object | null = HTMLElement.prototype+ while (owner && !Object.hasOwn(owner, 'onscrollend')) owner = Object.getPrototypeOf(owner)+ expect(owner).not.toBeNull()+ const descriptor = Object.getOwnPropertyDescriptor(owner!, 'onscrollend')!+ Reflect.deleteProperty(owner!, 'onscrollend')+ try {+ const { hours, column } = await renderPicker()+ moveGesture(column, 67, true)+ column.dispatchEvent(new Event('touchend'))+ await expect+ .element(hours.getByRole('option', { name: '4', exact: true }))+ .toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => column.scrollTop).toBe(78)+ } finally {+ Object.defineProperty(owner!, 'onscrollend', descriptor)+ }+})++it('settles the fallback after a final wheel event produces no additional scroll', async () => {+ let owner: object | null = HTMLElement.prototype+ while (owner && !Object.hasOwn(owner, 'onscrollend')) owner = Object.getPrototypeOf(owner)+ expect(owner).not.toBeNull()+ const descriptor = Object.getOwnPropertyDescriptor(owner!, 'onscrollend')!+ Reflect.deleteProperty(owner!, 'onscrollend')+ try {+ const { hours, column } = await renderPicker()+ moveGesture(column, 67)+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ )+ column.dispatchEvent(new WheelEvent('wheel', { deltaY: 1 }))+ await expect+ .element(hours.getByRole('option', { name: '4' }))+ .toHaveAttribute('aria-selected', 'true')+ await expect.poll(() => column.scrollTop).toBe(78)+ } finally {+ Object.defineProperty(owner!, 'onscrollend', descriptor)+ }+})diff --git a/packages/dify-ui/src/date-time/time-picker/index.stories.tsx b/packages/dify-ui/src/date-time/time-picker/index.stories.tsxnew file mode 100644index 00000000000..80fcb339b57--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/index.stories.tsx@@ -0,0 +1,187 @@+import type { Meta, StoryObj } from '@storybook/react-vite'+import * as React from 'react'+import { expect, waitFor, within } from 'storybook/test'+import { DirectionProvider } from '../../direction-provider'+import {+ TimePicker,+ TimePickerClear,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+} from './index'++const meta = {+ title: 'Base/Form/Time Picker',+ component: TimePicker,+ args: { children: null },+ parameters: {+ layout: 'centered',+ docs: { story: { autoplay: false } },+ a11y: { config: { rules: [{ id: 'color-contrast', enabled: true }] } },+ },+ tags: ['autodocs'],+} satisfies Meta<typeof TimePicker>++export default meta+type Story = StoryObj<typeof meta>++function TimePickerDemo() {+ const [value, setValue] = React.useState<string | null>('13:30')+ return (+ <div className="grid gap-1">+ <TimePicker value={value} onValueChange={setValue}>+ <TimePickerLabel>Start time</TimePickerLabel>+ <div className="flex items-center gap-1">+ <TimePickerTrigger />+ <TimePickerClear aria-label="Clear start time" />+ </div>+ <TimePickerContent />+ </TimePicker>+ </div>+ )+}++export const Default: Story = {+ render: () => <TimePickerDemo />,+ play: async ({ canvasElement, userEvent }) => {+ const canvas = within(canvasElement)+ const body = within(canvasElement.ownerDocument.body)+ const trigger = canvas.getByRole('button', { name: 'Start time 1:30 PM' })+ await expect(trigger).toHaveAttribute('aria-expanded', 'false')+ trigger.focus()+ await userEvent.keyboard('{Enter}')+ let hours = within(await body.findByRole('listbox', { name: 'Hour' }))+ await waitFor(() => expect(hours.getByRole('option', { name: '1' })).toHaveFocus())+ await userEvent.keyboard('{ArrowDown}{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await expect(trigger).toHaveAccessibleName('Start time 1:30 PM')+ await userEvent.keyboard('{Enter}')+ hours = within(await body.findByRole('listbox', { name: 'Hour' }))+ await waitFor(() => expect(hours.getByRole('option', { name: '1' })).toHaveFocus())+ await userEvent.keyboard('{ArrowDown}')+ await expect(hours.getByRole('option', { name: '2' })).toHaveFocus()+ await expect(hours.getByRole('option', { name: '2' })).toHaveAttribute('aria-selected', 'true')+ await expect(trigger).toHaveAccessibleName('Start time 1:30 PM')+ await userEvent.click(body.getByRole('button', { name: 'OK' }))+ const updatedTrigger = canvas.getByRole('button', { name: 'Start time 2:30 PM' })+ await waitFor(() => expect(updatedTrigger).toHaveFocus())+ await userEvent.keyboard('{Enter}')+ const dialog = await body.findByRole('dialog', { name: 'Start time' })+ await waitFor(() => expect(dialog).toBeVisible())+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(updatedTrigger).toHaveFocus())+ },+}++export const RTL: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'RTL reverses column placement, not vertical navigation. Arrow and Page keys stop at the endpoints; Home/End and numeric typing provide quick positioning. Escape discards the draft. Formatting locale remains independent of direction.',+ },+ },+ },+ render: () => (+ <div dir="rtl">+ <DirectionProvider direction="rtl">+ <TimePickerDemo />+ </DirectionProvider>+ </div>+ ),+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ const trigger = within(canvasElement).getByRole('button', { name: 'Start time 1:30 PM' })+ await userEvent.click(trigger)+ await expect(await body.findByRole('dialog', { name: 'Start time' })).toHaveAttribute(+ 'dir',+ 'rtl',+ )+ const hours = body.getByRole('listbox', { name: 'Hour' })+ const minutes = body.getByRole('listbox', { name: 'Minute' })+ await waitFor(() => expect(within(hours).getByRole('option', { name: '1' })).toHaveFocus())+ await expect(hours.getBoundingClientRect().left).toBeGreaterThan(+ minutes.getBoundingClientRect().left,+ )+ await userEvent.tab()+ await expect(within(minutes).getByRole('option', { name: '30' })).toHaveFocus()+ await userEvent.keyboard('{Home}{ArrowUp}{PageUp}')+ await expect(within(minutes).getByRole('option', { name: '00' })).toHaveFocus()+ await userEvent.keyboard('{End}{ArrowDown}{PageDown}')+ const last = within(minutes).getByRole('option', { name: '59' })+ await expect(last).toHaveFocus()+ await expect(last).toHaveAttribute('aria-selected', 'true')+ await userEvent.tab()+ await expect(+ within(body.getByRole('listbox', { name: 'Period' })).getByRole('option', { name: 'PM' }),+ ).toHaveFocus()+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ await expect(trigger).toHaveAccessibleName('Start time 1:30 PM')+ await userEvent.keyboard('{Enter}')+ await waitFor(() => expect(body.getByRole('dialog', { name: 'Start time' })).toBeVisible())+ await expect(+ within(body.getByRole('listbox', { name: 'Minute' })).getByRole('option', { name: '30' }),+ ).toHaveAttribute('aria-selected', 'true')+ await userEvent.keyboard('{Escape}')+ await waitFor(() => expect(trigger).toHaveFocus())+ },+}++export const UnavailableTime: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'Unavailable combinations can be explored but cannot be confirmed. Change another column to reach a valid time; only OK commits the draft.',+ },+ },+ },+ render: () => (+ <TimePicker defaultValue="09:00" isTimeUnavailable={(time) => time === '10:00'}>+ <TimePickerLabel className="sr-only">Start time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ ),+ play: async ({ canvasElement, userEvent }) => {+ const body = within(canvasElement.ownerDocument.body)+ await userEvent.click(within(canvasElement).getByRole('button', { name: 'Start time 9:00 AM' }))+ await userEvent.click(+ within(await body.findByRole('listbox', { name: 'Hour' })).getByRole('option', {+ name: '10',+ }),+ )+ await expect(body.getByRole('button', { name: 'OK' })).toBeDisabled()+ await expect(body.getByRole('status')).toHaveTextContent('This date or time is unavailable.')+ },+}++export const Schedule: Story = {+ parameters: {+ docs: {+ description: {+ story:+ 'A 24-hour schedule with quarter-hour steps and a composed value. The time zone determines Now, not the stored HH:mm wall time. Keep meaningful suffixes inside Value so they are included in the trigger name.',+ },+ },+ },+ render: () => (+ <div className="grid gap-1">+ <TimePicker defaultValue="13:30" hourCycle={24} minuteStep={15} timeZone="UTC">+ <TimePickerLabel>Update time</TimePickerLabel>+ <TimePickerTrigger>+ <TimePickerValue>+ {(value) => (+ <>+ {value} <span className="text-text-tertiary">UTC+0</span>+ </>+ )}+ </TimePickerValue>+ </TimePickerTrigger>+ <TimePickerContent />+ </TimePicker>+ </div>+ ),+}diff --git a/packages/dify-ui/src/date-time/time-picker/index.tsx b/packages/dify-ui/src/date-time/time-picker/index.tsxnew file mode 100644index 00000000000..c9eb531c38a--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/index.tsx@@ -0,0 +1,259 @@+'use client'++import type {+ PickerClearProps,+ PickerContentProps,+ PickerFieldProps,+ PickerLabelProps,+ PickerTriggerProps,+ PickerValueProps,+} from '../internal/picker-parts'+import type { TimePanelHandle, TimePanelLabels, TimePanelProps } from '../time-picker/time-panel'+import { useControlled } from '@base-ui/utils/useControlled'+import { TZDate } from '@date-fns/tz'+import * as React from 'react'+import { Button } from '../../button'+import { PickerPanel, PickerPanelHeader } from '../internal/picker-panel'+import {+ PickerClear,+ PickerContent,+ PickerLabel,+ PickerRoot,+ PickerTrigger,+ PickerValue,+ usePickerContext,+} from '../internal/picker-parts'+import { TimePanel } from '../time-picker/time-panel'+import { formatTimeValue, requireTimeValue } from '../time-picker/time-value'++type TimePickerLabels = TimePanelLabels & {+ title: string+ now: string+ apply: string+ unavailable: string+}+type TimePickerProps = PickerFieldProps &+ Pick<TimePanelProps, 'hourCycle' | 'minuteStep'> & {+ /** A 24-hour HH:mm wall time, independent of a date or time zone. */+ value?: string | null+ defaultValue?: string | null+ /** Called on OK, clearing or form reset; popup draft edits do not emit changes. */+ onValueChange?: (value: string | null) => void+ isTimeUnavailable?: (value: string) => boolean+ locale?: Intl.LocalesArgument+ /** IANA zone used for Now and the initial empty draft; it does not convert value. */+ timeZone?: string+ labels?: Partial<TimePickerLabels>+ }+type ContextValue = Omit<+ TimePickerProps,+ 'value' | 'defaultValue' | 'onValueChange' | 'children'+> & {+ value: Exclude<TimePickerProps['value'], undefined>+ commit: NonNullable<TimePickerProps['onValueChange']>+}+const Context = React.createContext<ContextValue | null>(null)+function useContext() {+ const context = React.useContext(Context)+ if (!context) throw new Error('TimePicker parts require TimePicker.')+ return context+}+const defaultLabels: TimePickerLabels = {+ title: 'Pick Time',+ hour: 'Hour',+ minute: 'Minute',+ period: 'Period',+ am: 'AM',+ pm: 'PM',+ now: 'Now',+ unavailable: 'This date or time is unavailable.',+ apply: 'OK',+}++function TimePicker({+ value: valueProp,+ defaultValue = null,+ onValueChange,+ children,+ ...props+}: TimePickerProps) {+ const [value, setValue] = useControlled({+ controlled: valueProp,+ default: defaultValue,+ name: 'TimePicker',+ })+ requireTimeValue(value)+ const unavailable = Boolean(+ 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+ {...props}+ invalid={props.invalid || unavailable}+ validationMessage={+ unavailable+ ? (props.labels?.unavailable ?? defaultLabels.unavailable)+ : props.validationMessage+ }+ placeholder={props.placeholder ?? 'Select time'}+ displayValue={+ value+ ? new Intl.DateTimeFormat(props.locale ?? 'en-US', {+ hour: 'numeric',+ minute: '2-digit',+ hour12: props.hourCycle !== 24,+ timeZone: 'UTC',+ }).format(new Date(`2025-01-01T${value}:00Z`))+ : ''+ }+ serializedValue={value ?? ''}+ onClear={() => commit(null)}+ onReset={() => {+ setValue(defaultValue)+ if (defaultValue !== value) onValueChange?.(defaultValue)+ }}+ >+ {children}+ </PickerRoot>+ </Context.Provider>+ )+}+type TimePickerTriggerProps = PickerTriggerProps+type TimePickerContentProps = PickerContentProps+type TimePickerClearProps = PickerClearProps+type TimePickerLabelProps = PickerLabelProps+type TimePickerValueProps = PickerValueProps+function TimePickerTrigger({ children, ...props }: TimePickerTriggerProps) {+ return (+ <PickerTrigger {...props}>+ {children ?? (+ <>+ <PickerValue />+ <span+ aria-hidden="true"+ className="i-ri-time-line size-4 shrink-0 text-text-tertiary forced-colors:text-[ButtonText] forced-colors:forced-color-adjust-none"+ />+ </>+ )}+ </PickerTrigger>+ )+}+const TimePickerClear = PickerClear+const TimePickerLabel = PickerLabel+const TimePickerValue = PickerValue+function TimePickerContent(props: TimePickerContentProps) {+ const { value, timeZone } = useContext()+ return (+ <PickerContent {...props}>+ <Session key={`${value ?? ''}-${timeZone ?? ''}`} />+ </PickerContent>+ )+}+function currentTime(timeZone?: string, minuteStep = 1) {+ const now = timeZone ? new TZDate(Date.now(), timeZone) : new Date()+ return formatTimeValue({+ hour: now.getHours(),+ minute: Math.floor(now.getMinutes() / minuteStep) * minuteStep,+ })+}+function Session() {+ const {+ value,+ commit,+ isTimeUnavailable,+ labels,+ locale,+ hourCycle,+ timeZone,+ minuteStep = 1,+ } = useContext()+ const { close } = usePickerContext()+ const panelRef = React.useRef<TimePanelHandle>(null)+ const [draft, setDraft] = React.useState(() => value ?? currentTime(timeZone, minuteStep))+ const text = { ...defaultLabels, ...labels }+ const unavailable = Boolean(+ isTimeUnavailable?.(draft) || Number(draft.slice(3)) % minuteStep !== 0,+ )+ const [scrollRequest, requestScroll] = React.useReducer((value: number) => value + 1, 0)+ const errorId = React.useId()+ return (+ <PickerPanel+ header={<PickerPanelHeader>{text.title}</PickerPanelHeader>}+ message={+ unavailable && (+ <p id={errorId} role="status" className="px-2 system-xs-regular text-text-destructive">+ {text.unavailable}+ </p>+ )+ }+ footer={+ <>+ <Button+ size="small"+ variant="ghost-accent"+ onClick={() => {+ setDraft(currentTime(timeZone, minuteStep))+ requestScroll()+ }}+ >+ {text.now}+ </Button>+ <Button+ variant="primary"+ className="min-w-16"+ size="small"+ disabled={unavailable}+ aria-describedby={unavailable ? errorId : undefined}+ onClick={() => {+ const next = panelRef.current?.settle() ?? draft+ setDraft(next)+ if (!isTimeUnavailable?.(next) && Number(next.slice(3)) % minuteStep === 0) {+ commit(next)+ close()+ }+ }}+ >+ {text.apply}+ </Button>+ </>+ }+ >+ <TimePanel+ ref={panelRef}+ minuteStep={minuteStep}+ scrollRequest={scrollRequest}+ value={draft}+ onValueChange={setDraft}+ labels={text}+ locale={locale}+ hourCycle={hourCycle}+ />+ </PickerPanel>+ )+}++export {+ TimePicker,+ TimePickerClear,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+}+export type {+ TimePickerClearProps,+ TimePickerContentProps,+ TimePickerLabelProps,+ TimePickerProps,+ TimePickerTriggerProps,+ TimePickerValueProps,+}diff --git a/packages/dify-ui/src/date-time/time-picker/time-panel.tsx b/packages/dify-ui/src/date-time/time-picker/time-panel.tsxnew file mode 100644index 00000000000..73851dcfba4--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/time-panel.tsx@@ -0,0 +1,103 @@+import type { OptionColumnHandle } from '../internal/option-column'+import * as React from 'react'+import { OptionColumn } from '../internal/option-column'+import { PickerColumns } from '../internal/picker-panel'+import { usePickerNumbers } from '../internal/use-picker-numbers'+import { formatTimeValue, parseTimeValue } from './time-value'++type TimePanelLabels = { hour: string; minute: string; period: string; am: string; pm: string }+type TimePanelHandle = { settle: () => string }+type TimePanelProps = {+ ref?: React.Ref<TimePanelHandle>+ value: string+ onValueChange: (update: (value: string) => string) => void+ labels: TimePanelLabels+ locale?: Intl.LocalesArgument+ hourCycle?: 12 | 24+ scrollRequest?: number+ minuteStep?: 1 | 5 | 10 | 15 | 20 | 30+}++function TimePanel({+ ref,+ value,+ onValueChange,+ labels,+ locale,+ hourCycle = 12,+ scrollRequest,+ minuteStep = 1,+}: TimePanelProps) {+ const numbers = usePickerNumbers(locale)+ const current = parseTimeValue(value)+ if (!current) throw new RangeError(`Invalid time of day: ${value}`)+ const period = current.hour < 12 ? 0 : 1+ const displayHour = hourCycle === 24 ? current.hour : current.hour % 12 || 12+ const hourRef = React.useRef<OptionColumnHandle>(null)+ const minuteRef = React.useRef<OptionColumnHandle>(null)+ const periodRef = React.useRef<OptionColumnHandle>(null)+ React.useImperativeHandle(ref, () => ({+ settle() {+ const hour = hourRef.current?.settle() ?? displayHour+ const minute = minuteRef.current?.settle() ?? current.minute+ const meridiem = periodRef.current?.settle() ?? period+ return formatTimeValue({+ hour: hourCycle === 24 ? hour : (hour % 12) + meridiem * 12,+ minute,+ })+ },+ }))+ function update(part: 'hour' | 'minute' | 'period', next: number) {+ onValueChange((previous) => {+ const time = parseTimeValue(previous)!+ if (part === 'minute') time.minute = next+ else if (part === 'period') time.hour = (time.hour % 12) + next * 12+ else time.hour = hourCycle === 24 ? next : (next % 12) + Math.floor(time.hour / 12) * 12+ return formatTimeValue(time)+ })+ }+ return (+ <PickerColumns>+ <OptionColumn+ ref={hourRef}+ scrollRequest={scrollRequest}+ normalizeDigits={numbers.normalizeDigits}+ label={labels.hour}+ value={displayHour}+ options={Array.from({ length: hourCycle }, (_, index) => {+ const hour = hourCycle === 24 ? index : index + 1+ return { value: hour, label: numbers.formatInteger(hour) }+ })}+ onValueChange={(hour) => update('hour', hour)}+ />+ <OptionColumn+ ref={minuteRef}+ scrollRequest={scrollRequest}+ normalizeDigits={numbers.normalizeDigits}+ label={labels.minute}+ value={current.minute}+ options={Array.from({ length: 60 / minuteStep }, (_, index) => ({+ value: index * minuteStep,+ label: numbers.formatMinute(index * minuteStep),+ }))}+ onValueChange={(minute) => update('minute', minute)}+ />+ {hourCycle === 12 && (+ <OptionColumn+ ref={periodRef}+ scrollRequest={scrollRequest}+ normalizeDigits={numbers.normalizeDigits}+ label={labels.period}+ value={period}+ options={[+ { value: 0, label: labels.am },+ { value: 1, label: labels.pm },+ ]}+ onValueChange={(next) => update('period', next)}+ />+ )}+ </PickerColumns>+ )+}+export { TimePanel }+export type { TimePanelHandle, TimePanelLabels, TimePanelProps }diff --git a/packages/dify-ui/src/date-time/time-picker/time-value.ts b/packages/dify-ui/src/date-time/time-picker/time-value.tsnew file mode 100644index 00000000000..08b80097816--- /dev/null+++ b/packages/dify-ui/src/date-time/time-picker/time-value.ts@@ -0,0 +1,25 @@+const timePattern = /^(\d{2}):(\d{2})$/++type TimeParts = { hour: number; minute: number }++function parseTimeValue(value: string): TimeParts | null {+ const match = timePattern.exec(value)+ if (!match) return null+ const hour = Number(match[1])+ const minute = Number(match[2])+ return hour < 24 && minute < 60 ? { hour, minute } : null+}++function formatTimeValue({ hour, minute }: TimeParts): string {+ return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`+}++function requireTimeValue(value: string | null): TimeParts | null {+ if (value === null) return null+ const time = parseTimeValue(value)+ if (!time) throw new RangeError(`Invalid time of day: ${value}`)+ return time+}++export { formatTimeValue, parseTimeValue, requireTimeValue }+export type { TimeParts }diff --git a/packages/dify-ui/src/direction-provider/index.tsx b/packages/dify-ui/src/direction-provider/index.tsxnew file mode 100644index 00000000000..7b3a072b021--- /dev/null+++ b/packages/dify-ui/src/direction-provider/index.tsx@@ -0,0 +1,4 @@+'use client'++export { DirectionProvider, useDirection } from '@base-ui/react/direction-provider'+export type { DirectionProviderProps } from '@base-ui/react/direction-provider'diff --git a/packages/dify-ui/vite.config.ts b/packages/dify-ui/vite.config.tsindex 3c2aa500cf3..96795f13c4d 100644--- a/packages/dify-ui/vite.config.ts+++ b/packages/dify-ui/vite.config.ts@@ -16,7 +16,14 @@ export default defineConfig({tsconfigPaths: true,},optimizeDeps: {- include: ['vite-plus/test/browser'],+ include: [+ 'vite-plus/test/browser',+ '@daypicker/react/locale/en-US',+ '@daypicker/react/locale/ar-TN',+ '@daypicker/react/locale/fa-IR',+ '@base-ui/utils/useStableCallback',+ '@base-ui/utils/useTimeout',+ ],},test: {browser: {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a1773814bd6..167f697220c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -185,6 +185,12 @@ catalogs:'@cucumber/cucumber':specifier: 13.2.1version: 13.2.1+ '@date-fns/tz':+ specifier: 1.4.1+ version: 1.4.1+ '@daypicker/react':+ specifier: 10.0.1+ version: 10.0.1'@egoist/tailwindcss-icons':specifier: 1.9.2version: 1.9.2@@ -443,6 +449,9 @@ catalogs:cron-parser:specifier: 5.10.1version: 5.10.1+ date-fns:+ specifier: 4.1.0+ version: 4.1.0dayjs:specifier: 1.11.23version: 1.11.23@@ -1120,13 +1129,22 @@ importers:'@base-ui/utils':specifier: 'catalog:'+ '@date-fns/tz':+ specifier: 'catalog:'+ version: 1.4.1+ '@daypicker/react':+ specifier: 'catalog:'+ version: 10.0.1(@types/[email protected])([email protected])cn:specifier: 'catalog:'version: 0.4.0+ date-fns:+ specifier: 'catalog:'+ version: 4.1.0devDependencies:'@base-ui/react':specifier: 'catalog:'+ version: 1.8.0(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])'@chromatic-com/storybook':specifier: 'catalog:'version: 5.3.1([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])(@typescript/[email protected])(@vitest/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])))@@ -1406,7 +1424,10 @@ importers:version: 1.35.4(@amplitude/[email protected])'@base-ui/react':specifier: 'catalog:'+ version: 1.8.0(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ '@daypicker/react':+ specifier: 'catalog:'+ version: 10.0.1(@types/[email protected])([email protected])'@floating-ui/react':specifier: 'catalog:'@@ -1503,6 +1524,9 @@ importers:cron-parser:specifier: 'catalog:'version: 5.10.1+ date-fns:+ specifier: 'catalog:'+ version: 4.1.0dayjs:specifier: 'catalog:'version: 1.11.23@@ -2178,6 +2202,19 @@ packages:'@cucumber/[email protected]':resolution: {integrity: sha512-7Uo6dYST8xZbHwwemXCt7Kv80Yh/SE85DyOed1/FTwxRXs3NYVOCm6e/h8DxlhTGIpD6rYXfpY3nHnIXAFMBlw==}+ '@date-fns/[email protected]':+ resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}++ '@daypicker/[email protected]':+ resolution: {integrity: sha512-lH4YQz4iMBWP8hsI1bD9Eg0T7t503IkSUR/WDGGkV5mKZvwVv+ukCkJz7yN+uVFBv7vHTK+ww7a5EvlkeFwPYQ==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/react': '>=16.8.0'+ react: '>=16.8.0'+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@devframes/[email protected]':resolution: {integrity: sha512-UAlfCYRP2LYmv3D/eiltJGUMiZIRtimNHUfBnx9CRL3FqEGbPUyA9yDaXdnFu9isg5kXkWoE3pQ78xYEW8Mu5Q==}peerDependencies:@@ -6398,6 +6435,9 @@ packages:resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==}+ resolution: {integrity: sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==}+resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==}@@ -8623,6 +8663,16 @@ packages:react: ^16.13.1 || ^17.0.0 || ^18.0.0 || ^19.0.0react-dom: ^16.13.1 || ^17.0.0 || ^18.0.0 || ^19.0.0+ resolution: {integrity: sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/react': '>=16.8.0'+ react: '>=16.8.0'+ peerDependenciesMeta:+ '@types/react':+ optional: true+resolution: {integrity: sha512-ZtAp5XTO5HRzQctjPU0ybY0RRCQO19X/8fxn3w7y2VVTUbGHDKULPTL4ky3vB05euSgG5NpALhEhDPvQ56wvXg==}peerDependencies:@@ -10094,7 +10144,7 @@ snapshots:'@babel/helper-string-parser': 7.29.7'@babel/helper-validator-identifier': 7.29.7- '@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ '@base-ui/[email protected](@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])':dependencies:'@babel/runtime': 7.29.7'@base-ui/utils': 0.4.0(@types/[email protected])([email protected]([email protected]))([email protected])@@ -10104,7 +10154,9 @@ snapshots:react-dom: 19.3.0([email protected])use-sync-external-store: 1.6.0([email protected])optionalDependencies:+ '@date-fns/tz': 1.4.1'@types/react': 19.3.0+ date-fns: 4.1.0'@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -10300,6 +10352,15 @@ snapshots:'@cucumber/[email protected]': {}+ '@date-fns/[email protected]': {}++ dependencies:+ react: 19.3.0+ react-day-picker: 10.0.1(@types/[email protected])([email protected])+ optionalDependencies:+ '@types/react': 19.3.0+'@devframes/[email protected]([email protected](@typescript/[email protected])([email protected]))':dependencies:birpc: 4.0.0@@ -13975,6 +14036,8 @@ snapshots:d3: 7.9.0lodash-es: 4.18.1+ [email protected]: {}+@@ -16632,6 +16695,14 @@ snapshots:react: 19.3.0react-dom: 19.3.0([email protected])+ dependencies:+ '@date-fns/tz': 1.4.1+ date-fns: 4.1.0+ react: 19.3.0+ optionalDependencies:+ '@types/react': 19.3.0+[email protected](@typescript/[email protected]):dependencies:typescript: '@typescript/[email protected]'@@ -18054,6 +18125,8 @@ time:'@base-ui/[email protected]': '2026-09-04T08:49:31.070Z''@chromatic-com/[email protected]': '2026-09-02T13:43:27.595Z''@cucumber/[email protected]': '2026-08-04T07:20:28.681Z'+ '@date-fns/[email protected]': '2025-08-12T12:16:20.094Z'+ '@daypicker/[email protected]': '2026-05-15T09:47:16.146Z''@egoist/[email protected]': '2026-01-31T10:48:44.594Z''@eslint-community/[email protected]': '2026-09-12T22:48:47.148Z''@eslint-react/[email protected]': '2026-09-27T20:42:15.063Z'@@ -18141,6 +18214,7 @@ time:[email protected]: '2026-08-15T03:33:20.323Z'[email protected]: '2026-04-24T22:15:18.933Z'[email protected]: '2026-09-12T19:11:21.465Z'+ [email protected]: '2024-09-17T04:37:03.810Z'[email protected]: '2026-08-17T11:52:35.217Z'[email protected]: '2025-07-06T22:50:38.844Z'[email protected]: '2026-09-23T15:29:57.247Z'diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 3db35116452..225f3f4e086 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -73,6 +73,8 @@ catalog:'@base-ui/utils': 0.4.0'@chromatic-com/storybook': 5.3.1'@cucumber/cucumber': 13.2.1+ '@date-fns/tz': 1.4.1+ '@daypicker/react': 10.0.1'@egoist/tailwindcss-icons': 1.9.2'@eslint-community/eslint-plugin-eslint-comments': 4.8.1'@eslint-react/eslint-plugin': 5.21.0@@ -160,6 +162,7 @@ catalog:concurrently: 10.0.5copy-to-clipboard: 4.0.2cron-parser: 5.10.1+ date-fns: 4.1.0dayjs: 1.11.23decimal.js: 10.6.0dompurify: 3.4.16diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/date-picker.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/date-picker.tsxdeleted file mode 100644index 476757e559c..00000000000--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/date-picker.tsx+++ /dev/null@@ -1,53 +0,0 @@-'use client'-import type { Dayjs } from 'dayjs'-import type { FC } from 'react'-import dayjs from 'dayjs'-import * as React from 'react'-import { useCallback } from 'react'-import DateRangePicker from '@/app/components/base/date-and-time-picker/date-range-picker'--type Props = Readonly<{- start: Dayjs- end: Dayjs- onStartChange: (date?: Dayjs) => void- onEndChange: (date?: Dayjs) => void-}>--const today = dayjs()-const DatePicker: FC<Props> = ({ start, end, onStartChange, onEndChange }) => {- const availableStartDate = end.subtract(30, 'day')- const startDateDisabled = useCallback(- (date: Dayjs) => {- if (date.isAfter(today, 'date')) return true- return !(- (date.isAfter(availableStartDate, 'date') || date.isSame(availableStartDate, 'date')) &&- (date.isBefore(end, 'date') || date.isSame(end, 'date'))- )- },- [availableStartDate, end],- )-- const availableEndDate = start.add(30, 'day')- const endDateDisabled = useCallback(- (date: Dayjs) => {- if (date.isAfter(today, 'date')) return true- return !(- (date.isAfter(start, 'date') || date.isSame(start, 'date')) &&- (date.isBefore(availableEndDate, 'date') || date.isSame(availableEndDate, 'date'))- )- },- [availableEndDate, start],- )-- return (- <DateRangePicker- start={start}- end={end}- onStartChange={onStartChange}- onEndChange={onEndChange}- getIsStartDateDisabled={startDateDisabled}- getIsEndDateDisabled={endDateDisabled}- />- )-}-export default React.memo(DatePicker)diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/index.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/index.tsxindex 53803270228..888721efdb9 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/index.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/time-range-picker/index.tsx@@ -10,12 +10,10 @@ import dayjs from 'dayjs'import * as React from 'react'import { useCallback, useState } from 'react'import { useLocale } from '#i18n'+import { MonitoringDateRangePicker } from '@/features/monitoring/date-range-picker'import { formatToLocalTime } from '@/utils/format'-import DatePicker from './date-picker'import RangeSelector from './range-selector'-const today = dayjs()-type TimePeriodName = I18nKeysByPrefix<'appLog', 'filter.period.'>type Props = Readonly<{@@ -28,8 +26,8 @@ const TimeRangePicker: FC<Props> = ({ ranges, onSelect, queryDateFormat }) => {const locale = useLocale()const [isCustomRange, setIsCustomRange] = useState(false)- const [start, setStart] = useState<Dayjs>(today)- const [end, setEnd] = useState<Dayjs>(today)+ const [start, setStart] = useState<Dayjs>(() => dayjs())+ const [end, setEnd] = useState<Dayjs>(() => dayjs())const handleRangeChange = useCallback((payload: PeriodParamsWithTimeRange) => {@@ -79,7 +77,7 @@ const TimeRangePicker: FC<Props> = ({ ranges, onSelect, queryDateFormat }) => {aria-hiddenclassName="i-custom-vender-other-hourglass-shape h-3.5 w-2 text-components-input-bg-normal"/>- <DatePicker+ <MonitoringDateRangePickerstart={start}end={end}onStartChange={handleDateChange('start')}diff --git a/web/app/components/base/date-and-time-picker/__tests__/hooks.spec.ts b/web/app/components/base/date-and-time-picker/__tests__/hooks.spec.tsdeleted file mode 100644index 3595cb66000..00000000000--- a/web/app/components/base/date-and-time-picker/__tests__/hooks.spec.ts+++ /dev/null@@ -1,94 +0,0 @@-import { renderHook } from '@testing-library/react'-import { useDaysOfWeek, useMonths, useTimeOptions, useYearOptions } from '../hooks'-import { Period } from '../types'-import dayjs from '../utils/dayjs'--describe('date-and-time-picker hooks', () => {- // Tests for useDaysOfWeek hook- describe('useDaysOfWeek', () => {- it('should return 7 days of the week', () => {- const { result } = renderHook(() => useDaysOfWeek())-- expect(result.current).toHaveLength(7)- })-- it('should return translated day keys with namespace prefix', () => {- const { result } = renderHook(() => useDaysOfWeek())-- // Global i18n mock returns "time.daysInWeek.<day>" format- expect(result.current[0]).toContain('daysInWeek.Sun')- expect(result.current[6]).toContain('daysInWeek.Sat')- })- })-- // Tests for useMonths hook- describe('useMonths', () => {- it('should return 12 months', () => {- const { result } = renderHook(() => useMonths())-- expect(result.current).toHaveLength(12)- })-- it('should return translated month keys with namespace prefix', () => {- const { result } = renderHook(() => useMonths())-- expect(result.current[0]).toContain('months.January')- expect(result.current[11]).toContain('months.December')- })- })-- // Tests for useYearOptions hook- describe('useYearOptions', () => {- it('should return 200 year options', () => {- const { result } = renderHook(() => useYearOptions())-- expect(result.current).toHaveLength(200)- })-- it('should center around the current year', () => {- const { result } = renderHook(() => useYearOptions())- const currentYear = dayjs().year()-- expect(result.current).toContain(currentYear)- // First year should be currentYear - 50 (YEAR_RANGE/2 = 50)- expect(result.current[0]).toBe(currentYear - 50)- // Last year should be currentYear + 149- expect(result.current[199]).toBe(currentYear + 149)- })- })-- // Tests for useTimeOptions hook- describe('useTimeOptions', () => {- it('should return 12 hour options', () => {- const { result } = renderHook(() => useTimeOptions())-- expect(result.current.hourOptions).toHaveLength(12)- })-- it('should return hours from 01 to 12 zero-padded', () => {- const { result } = renderHook(() => useTimeOptions())-- expect(result.current.hourOptions[0]).toBe('01')- expect(result.current.hourOptions[11]).toBe('12')- })-- it('should return 60 minute options', () => {- const { result } = renderHook(() => useTimeOptions())-- expect(result.current.minuteOptions).toHaveLength(60)- })-- it('should return minutes from 00 to 59 zero-padded', () => {- const { result } = renderHook(() => useTimeOptions())-- expect(result.current.minuteOptions[0]).toBe('00')- expect(result.current.minuteOptions[59]).toBe('59')- })-- it('should return AM and PM period options', () => {- const { result } = renderHook(() => useTimeOptions())-- expect(result.current.periodOptions).toEqual([Period.AM, Period.PM])- })- })-})diff --git a/web/app/components/base/date-and-time-picker/calendar/__tests__/index.spec.tsx b/web/app/components/base/date-and-time-picker/calendar/__tests__/index.spec.tsxdeleted file mode 100644index 7ef6580a27d..00000000000--- a/web/app/components/base/date-and-time-picker/calendar/__tests__/index.spec.tsx+++ /dev/null@@ -1,104 +0,0 @@-import type { CalendarProps, Day } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import dayjs from '../../utils/dayjs'-import Calendar from '../index'--// Mock scrollIntoView since the test DOM runtime doesn't implement it-beforeAll(() => {- Element.prototype.scrollIntoView = vi.fn()-})--// Factory for creating mock days-const createMockDays = (count: number = 7): Day[] => {- return Array.from({ length: count }, (_, i) => ({- date: dayjs('2024-06-01').add(i, 'day'),- isCurrentMonth: true,- }))-}--// Factory for Calendar props-const createCalendarProps = (overrides: Partial<CalendarProps> = {}): CalendarProps => ({- days: createMockDays(),- selectedDate: undefined,- onDateClick: vi.fn(),- ...overrides,-})--describe('Calendar', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render days of week header', () => {- const props = createCalendarProps()- render(<Calendar {...props} />)-- // DaysOfWeek component renders day labels- const dayLabels = screen.getAllByText(/daysInWeek/)- expect(dayLabels).toHaveLength(7)- })-- it('should render all calendar day items', () => {- const days = createMockDays(7)- const props = createCalendarProps({ days })- render(<Calendar {...props} />)-- const buttons = screen.getAllByRole('button')- expect(buttons).toHaveLength(7)- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call onDateClick when a day is clicked', () => {- const onDateClick = vi.fn()- const days = createMockDays(3)- const props = createCalendarProps({ days, onDateClick })- render(<Calendar {...props} />)-- const dayButtons = screen.getAllByRole('button')- fireEvent.click(dayButtons[1]!)-- expect(onDateClick).toHaveBeenCalledTimes(1)- expect(onDateClick).toHaveBeenCalledWith(days[1]!.date)- })- })-- // Disabled dates tests- describe('Disabled Dates', () => {- it('should not call onDateClick for disabled dates', () => {- const onDateClick = vi.fn()- const days = createMockDays(3)- // Disable all dates- const getIsDateDisabled = vi.fn().mockReturnValue(true)- const props = createCalendarProps({ days, onDateClick, getIsDateDisabled })- render(<Calendar {...props} />)-- const dayButtons = screen.getAllByRole('button')- fireEvent.click(dayButtons[0]!)-- expect(onDateClick).not.toHaveBeenCalled()- })-- it('should pass getIsDateDisabled to CalendarItem', () => {- const getIsDateDisabled = vi.fn().mockReturnValue(false)- const days = createMockDays(2)- const props = createCalendarProps({ days, getIsDateDisabled })- render(<Calendar {...props} />)-- expect(getIsDateDisabled).toHaveBeenCalled()- })- })-- // Edge cases- describe('Edge Cases', () => {- it('should render empty calendar when days array is empty', () => {- const props = createCalendarProps({ days: [] })- render(<Calendar {...props} />)-- expect(screen.queryAllByRole('button')).toHaveLength(0)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/calendar/__tests__/item.spec.tsx b/web/app/components/base/date-and-time-picker/calendar/__tests__/item.spec.tsxdeleted file mode 100644index 5a8f294b9e6..00000000000--- a/web/app/components/base/date-and-time-picker/calendar/__tests__/item.spec.tsx+++ /dev/null@@ -1,159 +0,0 @@-import type { CalendarItemProps, Day } from '../../types'-import { render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import dayjs from '../../utils/dayjs'-import Item from '../item'--const { locale, translations } = vi.hoisted(() => ({- locale: { value: 'en-US' },- translations: { 'common.calendar.selectedDate': 'Selected' },-}))--vi.mock('react-i18next', async () => {- const { createReactI18nextMock } = await import('@/test/i18n-mock')- return createReactI18nextMock(translations)-})--vi.mock('#i18n', async (importOriginal) => ({- ...(await importOriginal<typeof import('#i18n')>()),- useLocale: () => locale.value,-}))--const createMockDay = (overrides: Partial<Day> = {}): Day => ({- date: dayjs('2024-06-15'),- isCurrentMonth: true,- ...overrides,-})--const createItemProps = (overrides: Partial<CalendarItemProps> = {}): CalendarItemProps => ({- day: createMockDay(),- selectedDate: undefined,- onClick: vi.fn(),- isDisabled: false,- ...overrides,-})--describe('CalendarItem', () => {- beforeEach(() => {- vi.clearAllMocks()- locale.value = 'en-US'- translations['common.calendar.selectedDate'] = 'Selected'- })-- describe('Rendering', () => {- it('should render the day number', () => {- const props = createItemProps()-- render(<Item {...props} />)-- expect(screen.getByRole('button', { name: 'Saturday, June 15, 2024' })).toHaveTextContent(- '15',- )- })-- it('should localize the full date without changing the calendar date across time zones', () => {- locale.value = 'zh-Hans'- translations['common.calendar.selectedDate'] = '已选中'- const props = createItemProps({- day: createMockDay({ date: dayjs.tz('2024-06-15 00:00', 'Pacific/Kiritimati') }),- selectedDate: dayjs.tz('2024-06-15 00:00', 'Pacific/Kiritimati'),- })-- render(<Item {...props} />)-- expect(screen.getByRole('button', { name: '2024年6月15日星期六' })).toHaveTextContent('15')- expect(- screen.getByRole('button', { name: '2024年6月15日星期六' }),- ).toHaveAccessibleDescription('已选中')- })-- it.each([- ['fa-IR', 'شنبه ۱۵ ژوئن ۲۰۲۴'],- ['th-TH', 'วันเสาร์ที่ 15 มิถุนายน ค.ศ. 2024'],- ])('should keep the displayed Gregorian date in %s', (language, name) => {- locale.value = language- render(<Item {...createItemProps()} />)-- expect(screen.getByRole('button', { name })).toHaveTextContent('15')- })-- it('should describe selection without toggle semantics and clear it when another date is selected', () => {- const props = createItemProps({ selectedDate: dayjs('2024-06-15') })- const { rerender } = render(<Item {...props} />)-- const button = screen.getByRole('button', { name: 'Saturday, June 15, 2024' })- expect(button).toHaveAccessibleDescription('Selected')- expect(button).not.toHaveAttribute('aria-pressed')-- rerender(<Item {...props} selectedDate={dayjs('2024-06-16')} />)-- expect(button).toHaveAccessibleName('Saturday, June 15, 2024')- expect(button).not.toHaveAccessibleDescription()- expect(button).not.toHaveAttribute('aria-pressed')- })- })-- describe('Click Behavior', () => {- it('should call onClick with the date when clicked', async () => {- const user = userEvent.setup()- const onClick = vi.fn()- const day = createMockDay()- const props = createItemProps({ day, onClick })-- render(<Item {...props} />)- await user.click(screen.getByRole('button'))-- expect(onClick).toHaveBeenCalledTimes(1)- expect(onClick).toHaveBeenCalledWith(day.date)- })-- it('should expose disabled dates and prevent activation', async () => {- const user = userEvent.setup()- const onClick = vi.fn()- const props = createItemProps({ onClick, isDisabled: true })-- render(<Item {...props} />)- expect(screen.getByRole('button')).toBeDisabled()- await user.click(screen.getByRole('button'))-- expect(onClick).not.toHaveBeenCalled()- })- })-- describe('Today Indicator', () => {- it('should render today indicator when date is today', () => {- const today = dayjs()- const props = createItemProps({- day: createMockDay({ date: today }),- })-- render(<Item {...props} />)-- const button = screen.getByRole('button')- expect(button).toHaveAttribute('aria-current', 'date')- })-- it('should not render today indicator when date is not today', () => {- const notToday = dayjs('2020-01-01')- const props = createItemProps({- day: createMockDay({ date: notToday }),- })-- render(<Item {...props} />)-- const button = screen.getByRole('button')- expect(button).not.toHaveAttribute('aria-current')- })- })-- describe('Edge Cases', () => {- it('should leave an unselected date without a selection description or toggle state', () => {- const props = createItemProps({ selectedDate: undefined })-- render(<Item {...props} />)-- expect(screen.getByRole('button')).not.toHaveAccessibleDescription()- expect(screen.getByRole('button')).not.toHaveAttribute('aria-pressed')- })- })-})diff --git a/web/app/components/base/date-and-time-picker/calendar/days-of-week.tsx b/web/app/components/base/date-and-time-picker/calendar/days-of-week.tsxdeleted file mode 100644index b6e53b3024a..00000000000--- a/web/app/components/base/date-and-time-picker/calendar/days-of-week.tsx+++ /dev/null@@ -1,19 +0,0 @@-import * as React from 'react'-import { useDaysOfWeek } from '../hooks'--export const DaysOfWeek = () => {- const daysOfWeek = useDaysOfWeek()-- return (- <div className="grid grid-cols-7 gap-x-0.5 border-b-[0.5px] border-divider-regular p-2">- {daysOfWeek.map((day) => (- <div- key={day}- className="flex items-center justify-center system-2xs-medium text-text-tertiary"- >- {day}- </div>- ))}- </div>- )-}diff --git a/web/app/components/base/date-and-time-picker/calendar/index.tsx b/web/app/components/base/date-and-time-picker/calendar/index.tsxdeleted file mode 100644index 914aceed61e..00000000000--- a/web/app/components/base/date-and-time-picker/calendar/index.tsx+++ /dev/null@@ -1,31 +0,0 @@-import type { FC } from 'react'-import type { CalendarProps } from '../types'-import { DaysOfWeek } from './days-of-week'-import CalendarItem from './item'--const Calendar: FC<CalendarProps> = ({- days,- selectedDate,- onDateClick,- wrapperClassName,- getIsDateDisabled,-}) => {- return (- <div className={wrapperClassName}>- <DaysOfWeek />- <div className="grid grid-cols-7 gap-0.5 p-2">- {days.map((day) => (- <CalendarItem- key={day.date.format('YYYY-MM-DD')}- day={day}- selectedDate={selectedDate}- onClick={onDateClick}- isDisabled={getIsDateDisabled ? getIsDateDisabled(day.date) : false}- />- ))}- </div>- </div>- )-}--export default Calendardiff --git a/web/app/components/base/date-and-time-picker/calendar/item.tsx b/web/app/components/base/date-and-time-picker/calendar/item.tsxdeleted file mode 100644index 6639cea4caf..00000000000--- a/web/app/components/base/date-and-time-picker/calendar/item.tsx+++ /dev/null@@ -1,55 +0,0 @@-import type { FC } from 'react'-import type { CalendarItemProps } from '../types'-import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'-import { useTranslation } from 'react-i18next'-import { useLocale } from '#i18n'-import dayjs from '../utils/dayjs'--const Item: FC<CalendarItemProps> = ({ day, selectedDate, onClick, isDisabled }) => {- const locale = useLocale()- const { t } = useTranslation(['common'])- const selectedDescriptionId = React.useId()- const { date, isCurrentMonth } = day- const isSelected = selectedDate?.isSame(date, 'date')- const isToday = date.isSame(dayjs(), 'date')- const dateLabel = new Intl.DateTimeFormat(locale.replace('_', '-'), {- dateStyle: 'full',- calendar: 'gregory',- timeZone: 'UTC',- }).format(new Date(Date.UTC(date.year(), date.month(), date.date())))-- return (- <button- type="button"- aria-label={dateLabel}- aria-describedby={isSelected ? selectedDescriptionId : undefined}- aria-current={isToday ? 'date' : undefined}- disabled={isDisabled}- onClick={() => !isDisabled && onClick(date)}- className={cn(- 'relative flex items-center justify-center rounded-lg px-1 py-2 system-sm-medium focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',- isCurrentMonth ? 'text-text-secondary' : 'text-text-quaternary hover:text-text-secondary',- isSelected- ? 'bg-components-button-primary-bg system-sm-medium text-components-button-primary-text'- : 'hover:bg-state-base-hover',- isDisabled && 'cursor-not-allowed text-text-quaternary hover:bg-transparent',- )}- >- {date.date()}- {isSelected && (- <span id={selectedDescriptionId} className="sr-only">- {t(($) => $['calendar.selectedDate'])}- </span>- )}- {isToday && (- <div- aria-hidden- className="absolute bottom-1 mx-auto size-1 rounded-full bg-components-button-primary-bg"- />- )}- </button>- )-}--export default React.memo(Item)diff --git a/web/app/components/base/date-and-time-picker/common/__tests__/option-list-item.spec.tsx b/web/app/components/base/date-and-time-picker/common/__tests__/option-list-item.spec.tsxdeleted file mode 100644index e642edd0b8e..00000000000--- a/web/app/components/base/date-and-time-picker/common/__tests__/option-list-item.spec.tsx+++ /dev/null@@ -1,113 +0,0 @@-import { fireEvent, render, screen } from '@testing-library/react'-import OptionListItem from '../option-list-item'--describe('OptionListItem', () => {- let originalScrollIntoView: Element['scrollIntoView']- beforeEach(() => {- vi.clearAllMocks()- originalScrollIntoView = Element.prototype.scrollIntoView- Element.prototype.scrollIntoView = vi.fn()- })-- afterEach(() => {- Element.prototype.scrollIntoView = originalScrollIntoView- })-- describe('Rendering', () => {- it('should render children content', () => {- render(- <OptionListItem isSelected={false} onClick={vi.fn()}>- Test Item- </OptionListItem>,- )-- expect(screen.getByText('Test Item')).toBeInTheDocument()- })-- it('should render as a list item element', () => {- render(- <OptionListItem isSelected={false} onClick={vi.fn()}>- Item- </OptionListItem>,- )-- expect(screen.getByRole('listitem')).toBeInTheDocument()- })- })-- describe('Auto-Scroll', () => {- it('should scroll into view on mount when isSelected is true', () => {- render(- <OptionListItem isSelected={true} onClick={vi.fn()}>- Selected- </OptionListItem>,- )-- expect(Element.prototype.scrollIntoView).toHaveBeenCalledWith({ behavior: 'instant' })- })-- it('should not scroll into view on mount when isSelected is false', () => {- render(- <OptionListItem isSelected={false} onClick={vi.fn()}>- Not Selected- </OptionListItem>,- )-- expect(Element.prototype.scrollIntoView).not.toHaveBeenCalled()- })-- it('should not scroll into view on mount when noAutoScroll is true', () => {- render(- <OptionListItem isSelected={true} noAutoScroll onClick={vi.fn()}>- No Scroll- </OptionListItem>,- )-- expect(Element.prototype.scrollIntoView).not.toHaveBeenCalled()- })- })-- describe('Click Behavior', () => {- it('should call onClick when clicked', () => {- const handleClick = vi.fn()-- render(- <OptionListItem isSelected={false} onClick={handleClick}>- Clickable- </OptionListItem>,- )- fireEvent.click(screen.getByRole('button'))-- expect(handleClick).toHaveBeenCalledTimes(1)- })-- it('should scroll into view with smooth behavior on click', () => {- render(- <OptionListItem isSelected={false} onClick={vi.fn()}>- Item- </OptionListItem>,- )- fireEvent.click(screen.getByRole('button'))-- expect(Element.prototype.scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth' })- })- })-- describe('Edge Cases', () => {- it('should handle rapid clicks without errors', () => {- const handleClick = vi.fn()- render(- <OptionListItem isSelected={false} onClick={handleClick}>- Rapid Click- </OptionListItem>,- )-- const item = screen.getByRole('button')- fireEvent.click(item)- fireEvent.click(item)- fireEvent.click(item)-- expect(handleClick).toHaveBeenCalledTimes(3)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/common/option-list-item.tsx b/web/app/components/base/date-and-time-picker/common/option-list-item.tsxdeleted file mode 100644index 85d51554384..00000000000--- a/web/app/components/base/date-and-time-picker/common/option-list-item.tsx+++ /dev/null@@ -1,47 +0,0 @@-import type { FC, ReactNode } from 'react'-import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'-import { useEffect, useRef } from 'react'--type OptionListItemProps = {- isSelected: boolean- onClick: () => void- noAutoScroll?: boolean- children: ReactNode-}--const OptionListItem: FC<OptionListItemProps> = ({- isSelected,- onClick,- noAutoScroll,- children,-}) => {- const listItemRef = useRef<HTMLLIElement>(null)-- useEffect(() => {- if (isSelected && !noAutoScroll) listItemRef.current?.scrollIntoView({ behavior: 'instant' })- }, [])-- return (- <li ref={listItemRef}>- <button- type="button"- className={cn(- 'flex w-full cursor-pointer items-center justify-center rounded-md px-1.5 py-1 system-xs-medium text-components-button-ghost-text outline-hidden',- 'focus-visible:inset-ring-1 focus-visible:inset-ring-components-input-border-hover',- isSelected- ? 'bg-components-button-ghost-bg-hover'- : 'hover:bg-components-button-ghost-bg-hover',- )}- onClick={() => {- listItemRef.current?.scrollIntoView({ behavior: 'smooth' })- onClick()- }}- >- {children}- </button>- </li>- )-}--export default React.memo(OptionListItem)diff --git a/web/app/components/base/date-and-time-picker/common/option-list.tsx b/web/app/components/base/date-and-time-picker/common/option-list.tsxdeleted file mode 100644index 9419fc12493..00000000000--- a/web/app/components/base/date-and-time-picker/common/option-list.tsx+++ /dev/null@@ -1,22 +0,0 @@-import type { HTMLAttributes, ReactNode } from 'react'-import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'--type OptionListProps = {- children: ReactNode-} & HTMLAttributes<HTMLUListElement>--const optionListClassName = cn(- 'flex h-52 flex-col gap-y-0.5 overflow-y-auto pb-46',- 'scrollbar-none [&::-webkit-scrollbar]:hidden',-)--const OptionList = ({ children, className, ...props }: OptionListProps) => {- return (- <ul className={cn(optionListClassName, className)} {...props}>- {children}- </ul>- )-}--export default React.memo(OptionList)diff --git a/web/app/components/base/date-and-time-picker/date-picker/__tests__/footer.spec.tsx b/web/app/components/base/date-and-time-picker/date-picker/__tests__/footer.spec.tsxdeleted file mode 100644index 75cecb732b8..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/__tests__/footer.spec.tsx+++ /dev/null@@ -1,99 +0,0 @@-import type { DatePickerFooterProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import { ViewType } from '../../types'-import Footer from '../footer'--// Factory for Footer props-const createFooterProps = (- overrides: Partial<DatePickerFooterProps> = {},-): DatePickerFooterProps => ({- needTimePicker: true,- displayTime: '02:30 PM',- view: ViewType.date,- handleClickTimePicker: vi.fn(),- handleSelectCurrentDate: vi.fn(),- handleConfirmDate: vi.fn(),- ...overrides,-})--describe('DatePicker Footer', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render Now button and confirm button', () => {- const props = createFooterProps()- render(<Footer {...props} />)-- expect(screen.getByText(/operation\.now/)).toBeInTheDocument()- expect(screen.getByText(/operation\.ok/)).toBeInTheDocument()- })-- it('should show time picker button when needTimePicker is true', () => {- const props = createFooterProps({ needTimePicker: true, displayTime: '02:30 PM' })- render(<Footer {...props} />)-- expect(screen.getByText('02:30 PM')).toBeInTheDocument()- })-- it('should not show time picker button when needTimePicker is false', () => {- const props = createFooterProps({ needTimePicker: false })- render(<Footer {...props} />)-- expect(screen.queryByText('02:30 PM')).not.toBeInTheDocument()- })- })-- // View-dependent rendering tests- describe('View States', () => {- it('should show display time when view is date', () => {- const props = createFooterProps({ view: ViewType.date, displayTime: '10:00 AM' })- render(<Footer {...props} />)-- expect(screen.getByText('10:00 AM')).toBeInTheDocument()- })-- it('should show pickDate text when view is time', () => {- const props = createFooterProps({ view: ViewType.time })- render(<Footer {...props} />)-- expect(screen.getByText(/operation\.pickDate/)).toBeInTheDocument()- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call handleClickTimePicker when time picker button is clicked', () => {- const handleClickTimePicker = vi.fn()- const props = createFooterProps({ handleClickTimePicker })- render(<Footer {...props} />)-- // Click the time picker toggle button (has the time display)- fireEvent.click(screen.getByText('02:30 PM'))-- expect(handleClickTimePicker).toHaveBeenCalledTimes(1)- })-- it('should call handleSelectCurrentDate when Now button is clicked', () => {- const handleSelectCurrentDate = vi.fn()- const props = createFooterProps({ handleSelectCurrentDate })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.now/))-- expect(handleSelectCurrentDate).toHaveBeenCalledTimes(1)- })-- it('should call handleConfirmDate when OK button is clicked', () => {- const handleConfirmDate = vi.fn()- const props = createFooterProps({ handleConfirmDate })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.ok/))-- expect(handleConfirmDate).toHaveBeenCalledTimes(1)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/date-picker/__tests__/header.spec.tsx b/web/app/components/base/date-and-time-picker/date-picker/__tests__/header.spec.tsxdeleted file mode 100644index fc7e7a2e36b..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/__tests__/header.spec.tsx+++ /dev/null@@ -1,81 +0,0 @@-import type { DatePickerHeaderProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import dayjs from '../../utils/dayjs'-import Header from '../header'--// Factory for Header props-const createHeaderProps = (- overrides: Partial<DatePickerHeaderProps> = {},-): DatePickerHeaderProps => ({- handleOpenYearMonthPicker: vi.fn(),- currentDate: dayjs('2024-06-15'),- onClickNextMonth: vi.fn(),- onClickPrevMonth: vi.fn(),- ...overrides,-})--describe('DatePicker Header', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render month and year display', () => {- const props = createHeaderProps({ currentDate: dayjs('2024-06-15') })- render(<Header {...props} />)-- // The useMonths hook returns translated keys; check for year- // The useMonths hook returns translated keys; check for year- expect(screen.getByText(/2024/))!.toBeInTheDocument()- })-- it('should render navigation buttons', () => {- const props = createHeaderProps()- render(<Header {...props} />)-- // There are 3 buttons: month/year display, prev, next- const buttons = screen.getAllByRole('button')- expect(buttons).toHaveLength(3)- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call handleOpenYearMonthPicker when month/year button is clicked', () => {- const handleOpenYearMonthPicker = vi.fn()- const props = createHeaderProps({ handleOpenYearMonthPicker })- render(<Header {...props} />)-- // First button is the month/year display- const buttons = screen.getAllByRole('button')- fireEvent.click(buttons[0]!)-- expect(handleOpenYearMonthPicker).toHaveBeenCalledTimes(1)- })-- it('should call onClickPrevMonth when previous button is clicked', () => {- const onClickPrevMonth = vi.fn()- const props = createHeaderProps({ onClickPrevMonth })- render(<Header {...props} />)-- // Second button is prev month- const buttons = screen.getAllByRole('button')- fireEvent.click(buttons[1]!)-- expect(onClickPrevMonth).toHaveBeenCalledTimes(1)- })-- it('should call onClickNextMonth when next button is clicked', () => {- const onClickNextMonth = vi.fn()- const props = createHeaderProps({ onClickNextMonth })- render(<Header {...props} />)-- // Third button is next month- const buttons = screen.getAllByRole('button')- fireEvent.click(buttons[2]!)-- expect(onClickNextMonth).toHaveBeenCalledTimes(1)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.browser.spec.tsx b/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.browser.spec.tsxdeleted file mode 100644index 14a2c870049..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.browser.spec.tsx+++ /dev/null@@ -1,30 +0,0 @@-import { userEvent } from 'vite-plus/test/browser'-import { render } from 'vitest-browser-react'-import dayjs from '../../utils/dayjs'-import DatePicker from '../index'--describe('DatePicker browser interactions', () => {- it('closes when focus moves backward past the trigger', async () => {- // Chromium owns the native focus event order used by Base UI's focus guards.- const screen = await render(- <>- <button type="button">Before picker</button>- <DatePicker value={dayjs('2024-06-15')} onChange={() => {}} onClear={() => {}} />- </>,- )-- const trigger = screen.getByRole('button', { name: /time.defaultPlaceholder/ })- await trigger.click()- await expect.element(screen.getByRole('dialog')).toBeVisible()-- await userEvent.tab({ shift: true })-- expect(trigger.element()).toHaveFocus()- await expect.element(screen.getByRole('dialog')).toBeVisible()-- await userEvent.tab({ shift: true })-- expect(screen.getByRole('button', { name: 'Before picker' }).element()).toHaveFocus()- await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()- })-})diff --git a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx b/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsxdeleted file mode 100644index 6f014e220d0..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/__tests__/index.spec.tsx+++ /dev/null@@ -1,742 +0,0 @@-import type { DatePickerProps } from '../../types'-import { fireEvent, render, screen, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import dayjs from '../../utils/dayjs'-import DatePicker from '../index'--// Mock scrollIntoView-beforeAll(() => {- Element.prototype.scrollIntoView = vi.fn()-})--// Factory for DatePicker props-const createDatePickerProps = (overrides: Partial<DatePickerProps> = {}): DatePickerProps => ({- value: undefined,- onChange: vi.fn(),- onClear: vi.fn(),- ...overrides,-})--const getDateTrigger = () =>- screen.getByRole('button', { name: /^(time.defaultPlaceholder|Select date)/ })--// Helper to open the picker-const openPicker = () => {- const input = getDateTrigger()- fireEvent.click(input)-}--describe('DatePicker', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render with default placeholder', () => {- const props = createDatePickerProps()- render(<DatePicker {...props} />)-- expect(getDateTrigger())!.toBeInTheDocument()- })-- it('should render with custom placeholder', () => {- const props = createDatePickerProps({ placeholder: 'Select date' })- render(<DatePicker {...props} />)-- expect(getDateTrigger())!.toHaveTextContent('Select date')- })-- it('should display formatted date value when value is provided', () => {- const value = dayjs('2024-06-15T14:30:00')- const props = createDatePickerProps({ value })- render(<DatePicker {...props} />)-- expect(getDateTrigger()).not.toHaveTextContent('time.defaultPlaceholder')- })-- it('should keep the accessible name in sync with the displayed draft date', async () => {- const user = userEvent.setup()- const props = createDatePickerProps({- value: dayjs('2024-06-15'),- placeholder: 'Select date',- needTimePicker: false,- })- render(<DatePicker {...props} />)-- const trigger = getDateTrigger()- const initialText = trigger.textContent-- await user.click(trigger)- await user.click(screen.getByRole('button', { name: / 20, \d{4}$/ }))-- expect(trigger.textContent).not.toBe(initialText)- expect(trigger).toHaveAccessibleName(`Select date: ${trigger.textContent}`)- })-- it('should render with empty value when no value is provided', () => {- const props = createDatePickerProps()- render(<DatePicker {...props} />)-- expect(getDateTrigger())!.toHaveTextContent('time.defaultPlaceholder')- })-- it('should normalize value with timezone applied', () => {- const value = dayjs('2024-06-15T14:30:00')- const props = createDatePickerProps({ value, timezone: 'America/New_York' })- render(<DatePicker {...props} />)-- expect(getDateTrigger()).not.toHaveTextContent('time.defaultPlaceholder')- })-- it('should normalize non-Dayjs value input', () => {- const value = new Date('2024-06-15T14:30:00Z') as unknown as DatePickerProps['value']- const props = createDatePickerProps({ value })- render(<DatePicker {...props} />)-- expect(getDateTrigger()).not.toHaveTextContent('time.defaultPlaceholder')- })- })-- // Open/close behavior- describe('Open/Close Behavior', () => {- it('should open the picker when trigger is clicked', () => {- const props = createDatePickerProps()- render(<DatePicker {...props} />)-- openPicker()-- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should close when trigger is clicked while open', () => {- const props = createDatePickerProps()- render(<DatePicker {...props} />)-- openPicker()- openPicker() // second click closes-- expect(getDateTrigger()).toHaveAttribute('aria-expanded', 'false')- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()- })-- it('should restore selected date from value when reopening', () => {- const value = dayjs('2024-06-15')- const props = createDatePickerProps({ value })- render(<DatePicker {...props} />)-- openPicker()-- // Calendar should be showing June 2024- // Calendar should be showing June 2024- expect(screen.getByText(/2024/))!.toBeInTheDocument()- })-- it('should close when clicking outside the container', async () => {- const user = userEvent.setup()- const props = createDatePickerProps()- render(<DatePicker {...props} />)-- openPicker()- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)-- await user.click(document.body)-- expect(screen.queryAllByText(/daysInWeek/)).toHaveLength(0)- expect(getDateTrigger()).toBeInTheDocument()- })- })-- // Time Picker Integration- describe('Time Picker Integration', () => {- it('should show time display in footer when needTimePicker is true', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()-- expect(screen.getByText('--:-- --'))!.toBeInTheDocument()- })-- it('should not show time toggle when needTimePicker is false', () => {- const props = createDatePickerProps({ needTimePicker: false })- render(<DatePicker {...props} />)-- openPicker()-- expect(screen.queryByText('--:-- --')).not.toBeInTheDocument()- })-- it('should switch to time view when time picker button is clicked', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()-- // Click the time display button to switch to time view- fireEvent.click(screen.getByText('--:-- --'))-- // In time view, the "pickDate" text should appear instead of the time- // In time view, the "pickDate" text should appear instead of the time- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should switch back to date view when pickDate is clicked in time view', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view- fireEvent.click(screen.getByText('--:-- --'))- // Switch back to date view- fireEvent.click(screen.getByText(/operation\.pickDate/))-- // Days of week should be visible again- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should render time picker options in time view', () => {- const props = createDatePickerProps({- needTimePicker: true,- value: dayjs('2024-06-15T14:30:00'),- })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view- fireEvent.click(screen.getByText(/\d{2}:\d{2}\s(AM|PM)/))-- // Should show AM/PM options (TimePickerOptions renders these)- // Should show AM/PM options (TimePickerOptions renders these)- expect(screen.getByText('AM'))!.toBeInTheDocument()- expect(screen.getByText('PM'))!.toBeInTheDocument()- })-- it('should update selected time when hour is selected in time view', () => {- const props = createDatePickerProps({- needTimePicker: true,- value: dayjs('2024-06-15T14:30:00'),- })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view- fireEvent.click(screen.getByText(/\d{2}:\d{2}\s(AM|PM)/))-- // Click hour "05" from the time options- const allLists = screen.getAllByRole('list')- const hourItems = within(allLists[0]!).getAllByRole('listitem')- fireEvent.click(hourItems[4]!)-- // The picker should still be in time view- // The picker should still be in time view- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should update selected time when minute is selected in time view', () => {- const props = createDatePickerProps({- needTimePicker: true,- value: dayjs('2024-06-15T14:30:00'),- })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view- fireEvent.click(screen.getByText(/\d{2}:\d{2}\s(AM|PM)/))-- // Click minute "45" from the time options- const allLists = screen.getAllByRole('list')- const minuteItems = within(allLists[1]!).getAllByRole('listitem')- fireEvent.click(minuteItems[45]!)-- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should update selected time when period is changed in time view', () => {- const props = createDatePickerProps({- needTimePicker: true,- value: dayjs('2024-06-15T14:30:00'),- })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view- fireEvent.click(screen.getByText(/\d{2}:\d{2}\s(AM|PM)/))-- // Click AM to switch period- fireEvent.click(screen.getByText('AM'))-- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should update time when no selectedDate exists and hour is selected', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()-- // Switch to time view (click on the "--:-- --" text)- fireEvent.click(screen.getByText('--:-- --'))-- // Click hour "03" from the time options- const allLists = screen.getAllByRole('list')- const hourItems = within(allLists[0]!).getAllByRole('listitem')- fireEvent.click(hourItems[2]!)-- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should update time when no selectedDate exists and minute is selected', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText('--:-- --'))-- const allLists = screen.getAllByRole('list')- const minuteItems = within(allLists[1]!).getAllByRole('listitem')- fireEvent.click(minuteItems[15]!)-- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })-- it('should update time when no selectedDate exists and period is selected', () => {- const props = createDatePickerProps({ needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText('--:-- --'))- fireEvent.click(screen.getByText('PM'))-- expect(screen.getByText(/operation\.pickDate/))!.toBeInTheDocument()- })- })-- // Date selection- describe('Date Selection', () => {- it('should call onChange when Now button is clicked', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/operation\.now/))-- expect(onChange).toHaveBeenCalledTimes(1)- })-- it('should call onChange when OK button is clicked with a value', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange, value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/operation\.ok/))-- expect(onChange).toHaveBeenCalledTimes(1)- })-- it('should select a calendar day when clicked', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange, value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()-- // Click on a day in the calendar - day "20"- const dayButton = screen.getByRole('button', { name: / 20, \d{4}$/ })- fireEvent.click(dayButton)-- // The date should now appear in the header/display- // The date should now appear in the header/display- expect(getDateTrigger())!.toBeInTheDocument()- })-- it('should immediately confirm when noConfirm is true and a date is clicked', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange, noConfirm: true, value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()-- // Click on a day- const dayButton = screen.getByRole('button', { name: / 20, \d{4}$/ })- fireEvent.click(dayButton)-- expect(onChange).toHaveBeenCalledTimes(1)- })-- it('should clone time from timezone default when selecting a date without initial value', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange, noConfirm: true })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByRole('button', { name: / 20, \d{4}$/ }))-- expect(onChange).toHaveBeenCalledTimes(1)- })-- it('should call onChange with undefined when OK is clicked without a selected date', () => {- const onChange = vi.fn()- const props = createDatePickerProps({ onChange })- render(<DatePicker {...props} />)-- openPicker()-- // Clear selected date then confirm- fireEvent.click(screen.getByText(/operation\.ok/))-- expect(onChange).toHaveBeenCalledTimes(1)- })- })-- // Clear behavior- describe('Clear Behavior', () => {- it('should call onClear when clear is clicked while picker is closed', () => {- const onClear = vi.fn()- const renderTrigger = vi.fn((triggerProps, _state, { handleClear }) => (- <button- {...triggerProps}- data-testid="clear-trigger"- onClick={(event) => {- event.preventDefault()- handleClear(event)- triggerProps.onClick?.(event)- }}- >- Clear- </button>- ))- const props = createDatePickerProps({- value: dayjs('2024-06-15'),- onClear,- renderTrigger,- })- render(<DatePicker {...props} />)-- fireEvent.click(screen.getByTestId('clear-trigger'))-- expect(onClear).toHaveBeenCalledTimes(1)- })-- it('should clear selected date without calling onClear when picker is open', async () => {- const user = userEvent.setup()- const onClear = vi.fn()- const onChange = vi.fn()- const renderTrigger = vi.fn((triggerProps, _state, { handleClear }) => (- <div>- <button {...triggerProps} data-testid="open-trigger">- Open- </button>- <button data-testid="clear-trigger" onClick={handleClear}>- Clear- </button>- </div>- ))- const props = createDatePickerProps({- value: dayjs('2024-06-15'),- onClear,- onChange,- renderTrigger,- })- render(<DatePicker {...props} />)-- await user.click(screen.getByRole('button', { name: 'Open' }))- await user.click(screen.getByRole('button', { name: 'Clear' }))- await user.click(screen.getByRole('button', { name: /operation\.ok/ }))-- expect(onClear).not.toHaveBeenCalled()- expect(onChange).toHaveBeenCalledWith(undefined)- })- })-- // Month navigation- describe('Month Navigation', () => {- it('should navigate to next month when next arrow is clicked', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()-- // Find navigation buttons in the header- const allButtons = screen.getAllByRole('button')- // The header has: month/year button, prev button, next button- // Then calendar days are also buttons. We need the 3rd button (next month).- // Header buttons come first in DOM order.- fireEvent.click(allButtons[2]!) // next month button-- expect(screen.getAllByRole('button').length).toBeGreaterThan(0)- })-- it('should navigate to previous month when prev arrow is clicked', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()-- const allButtons = screen.getAllByRole('button')- fireEvent.click(allButtons[1]!) // prev month button-- expect(screen.getAllByRole('button').length).toBeGreaterThan(0)- })- })-- // Year/Month picker- describe('Year/Month Picker', () => {- it('should open year/month picker when month/year header is clicked', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()-- const headerButton = screen.getByText(/2024/)- fireEvent.click(headerButton)-- // Cancel button visible in year/month picker footer- // Cancel button visible in year/month picker footer- expect(screen.getByText(/operation\.cancel/))!.toBeInTheDocument()- })-- it('should close year/month picker when cancel is clicked', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/2024/))-- // Cancel- fireEvent.click(screen.getByText(/operation\.cancel/))-- // Should be back to date view with days of week- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should confirm year/month selection when OK is clicked', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/2024/))-- // Select a different year- fireEvent.click(screen.getByText('2023'))-- // Confirm - click the last OK button (year/month footer)- const okButtons = screen.getAllByText(/operation\.ok/)- fireEvent.click(okButtons[okButtons.length - 1]!)-- // Should return to date view- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should close year/month picker by clicking header button', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()- // Open year/month picker- fireEvent.click(screen.getByText(/2024/))-- fireEvent.click(screen.getByRole('button', { name: /time\.months\.June 2024/ }))-- // Should return to date view- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should update month selection in year/month picker', () => {- const props = createDatePickerProps({ value: dayjs('2024-06-15') })- render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/2024/))-- // Select a different month using RTL queries- const allLists = screen.getAllByRole('list')- const monthItems = within(allLists[0]!).getAllByRole('listitem')- fireEvent.click(monthItems[0]!)-- // Confirm the selection - click the last OK button (year/month footer)- const okButtons = screen.getAllByText(/operation\.ok/)- fireEvent.click(okButtons[okButtons.length - 1]!)-- // Should return to date view- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })- })-- // noConfirm mode- describe('noConfirm Mode', () => {- it('should not show footer when noConfirm is true', () => {- const props = createDatePickerProps({ noConfirm: true })- render(<DatePicker {...props} />)-- openPicker()-- expect(screen.queryByText(/operation\.ok/)).not.toBeInTheDocument()- })- })-- // Custom trigger- describe('Custom Trigger', () => {- it('should use renderTrigger when provided', () => {- const renderTrigger = vi.fn((triggerProps) => (- <button {...triggerProps} data-testid="custom-trigger">- Custom- </button>- ))-- const props = createDatePickerProps({ renderTrigger })- render(<DatePicker {...props} />)-- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()- })-- it('should open picker when custom trigger is clicked', () => {- const renderTrigger = vi.fn((triggerProps) => (- <button {...triggerProps} data-testid="custom-trigger">- Custom- </button>- ))-- const props = createDatePickerProps({ renderTrigger })- render(<DatePicker {...props} />)-- fireEvent.click(screen.getByTestId('custom-trigger'))-- expect(screen.getAllByText(/daysInWeek/).length).toBeGreaterThan(0)- })-- it('should expose Base UI trigger state and props to a custom trigger', () => {- const renderTrigger = vi.fn((triggerProps, state) => (- <button {...triggerProps} data-testid="state-trigger">- {state.open ? 'Open' : 'Closed'}- </button>- ))-- render(<DatePicker {...createDatePickerProps({ renderTrigger })} />)-- expect(screen.getByTestId('state-trigger')).toHaveTextContent('Closed')- expect(screen.getByTestId('state-trigger')).not.toHaveAttribute('data-popup-open')-- fireEvent.click(screen.getByTestId('state-trigger'))-- expect(screen.getByTestId('state-trigger')).toHaveTextContent('Open')- expect(screen.getByTestId('state-trigger')).toHaveAttribute('data-popup-open')- })- })-- // Disabled dates- describe('Disabled Dates', () => {- it('should pass getIsDateDisabled to calendar', () => {- const getIsDateDisabled = vi.fn().mockReturnValue(false)- const props = createDatePickerProps({- value: dayjs('2024-06-15'),- getIsDateDisabled,- })- render(<DatePicker {...props} />)-- openPicker()-- expect(getIsDateDisabled).toHaveBeenCalled()- })- })-- // Timezone- describe('Timezone', () => {- it('should render with timezone', () => {- const props = createDatePickerProps({- value: dayjs('2024-06-15'),- timezone: 'UTC',- })- render(<DatePicker {...props} />)-- expect(getDateTrigger())!.toBeInTheDocument()- })-- it('should call onChange when timezone changes with a value', () => {- const onChange = vi.fn()- const props = createDatePickerProps({- value: dayjs('2024-06-15T14:30:00'),- timezone: 'UTC',- onChange,- })- const { rerender } = render(<DatePicker {...props} />)-- // Change timezone- rerender(<DatePicker {...props} timezone="America/New_York" />)-- expect(onChange).toHaveBeenCalled()- })-- it('should update currentDate when timezone changes without a value', () => {- const onChange = vi.fn()- const props = createDatePickerProps({- timezone: 'UTC',- onChange,- })- const { rerender } = render(<DatePicker {...props} />)-- // Change timezone with no value- rerender(<DatePicker {...props} timezone="America/New_York" />)-- // onChange should NOT be called when there is no value- expect(onChange).not.toHaveBeenCalled()- })-- it('should update selectedDate when timezone changes and value is present', () => {- const onChange = vi.fn()- const value = dayjs('2024-06-15T14:30:00')- const props = createDatePickerProps({- value,- timezone: 'UTC',- onChange,- })- const { rerender } = render(<DatePicker {...props} />)-- // Change timezone- rerender(<DatePicker {...props} timezone="Asia/Tokyo" />)-- // Should have been called with the new timezone-adjusted value- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(emitted.isValid()).toBe(true)- })-- it('should preserve selected date when timezone changes after selecting now without initial value', () => {- const onChange = vi.fn()- const props = createDatePickerProps({- timezone: 'UTC',- onChange,- })- const { rerender } = render(<DatePicker {...props} />)-- openPicker()- fireEvent.click(screen.getByText(/operation\.now/))- rerender(<DatePicker {...props} timezone="Asia/Tokyo" />)-- expect(onChange).toHaveBeenCalledTimes(1)- expect(getDateTrigger())!.toBeInTheDocument()- })- })-- // Display time when selected date exists- describe('Time Display', () => {- it('should show formatted time when selectedDate exists', () => {- const value = dayjs('2024-06-15T14:30:00')- const props = createDatePickerProps({ value, needTimePicker: true })- render(<DatePicker {...props} />)-- openPicker()-- // The footer should show the time from selectedDate (02:30 PM)- // The footer should show the time from selectedDate (02:30 PM)- expect(screen.getByText(/\d{2}:\d{2}\s(AM|PM)/))!.toBeInTheDocument()- })- })-})diff --git a/web/app/components/base/date-and-time-picker/date-picker/footer.tsx b/web/app/components/base/date-and-time-picker/date-picker/footer.tsxdeleted file mode 100644index 849335d11e8..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/footer.tsx+++ /dev/null@@ -1,64 +0,0 @@-import type { FC } from 'react'-import type { DatePickerFooterProps } from '../types'-import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'-import { RiTimeLine } from '@remixicon/react'-import * as React from 'react'-import { useTranslation } from 'react-i18next'-import { ViewType } from '../types'--const Footer: FC<DatePickerFooterProps> = ({- needTimePicker,- displayTime,- view,- handleClickTimePicker,- handleSelectCurrentDate,- handleConfirmDate,-}) => {- const { t } = useTranslation(['time'])-- return (- <div- className={cn(- 'flex items-center justify-between border-t-[0.5px] border-divider-regular p-2',- !needTimePicker && 'justify-end',- )}- >- {/* Time Picker */}- {needTimePicker && (- <button- type="button"- className="flex items-center gap-x-px rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-1.5 py-1 system-xs-medium text-components-button-secondary-accent-text shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]"- onClick={handleClickTimePicker}- >- <RiTimeLine className="size-3.5" />- {view === ViewType.date && <span>{displayTime}</span>}- {view === ViewType.time && (- <span>{t(($) => $['operation.pickDate'], { ns: 'time' })}</span>- )}- </button>- )}- <div className="flex items-center gap-x-1">- {/* Now */}- <button- type="button"- className="flex items-center justify-center px-1.5 py-1 system-xs-medium text-components-button-secondary-accent-text"- onClick={handleSelectCurrentDate}- >- <span className="px-0.75">{t(($) => $['operation.now'], { ns: 'time' })}</span>- </button>- {/* Confirm Button */}- <Button- variant="primary"- size="small"- className="w-16 px-1.5 py-1"- onClick={handleConfirmDate}- >- {t(($) => $['operation.ok'], { ns: 'time' })}- </Button>- </div>- </div>- )-}--export default React.memo(Footer)diff --git a/web/app/components/base/date-and-time-picker/date-picker/header.tsx b/web/app/components/base/date-and-time-picker/date-picker/header.tsxdeleted file mode 100644index 68e1e97cec4..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/header.tsx+++ /dev/null@@ -1,45 +0,0 @@-import type { FC } from 'react'-import type { DatePickerHeaderProps } from '../types'-import { RiArrowDownSLine, RiArrowUpSLine } from '@remixicon/react'-import * as React from 'react'-import { useMonths } from '../hooks'--const Header: FC<DatePickerHeaderProps> = ({- handleOpenYearMonthPicker,- currentDate,- onClickNextMonth,- onClickPrevMonth,-}) => {- const months = useMonths()-- return (- <div className="mx-2 mt-2 flex items-center">- <div className="flex-1">- <button- type="button"- onClick={handleOpenYearMonthPicker}- className="flex items-center gap-x-0.5 rounded-lg px-2 py-1.5 system-md-semibold text-text-primary hover:bg-state-base-hover"- >- <span>{`${months[currentDate.month()]} ${currentDate.year()}`}</span>- <RiArrowDownSLine className="size-4 text-text-tertiary" />- </button>- </div>- <button- type="button"- onClick={onClickPrevMonth}- className="rounded-lg p-1.5 hover:bg-state-base-hover"- >- <RiArrowUpSLine className="h-4.5 w-4.5 text-text-secondary" />- </button>- <button- type="button"- onClick={onClickNextMonth}- className="rounded-lg p-1.5 hover:bg-state-base-hover"- >- <RiArrowDownSLine className="h-4.5 w-4.5 text-text-secondary" />- </button>- </div>- )-}--export default React.memo(Header)diff --git a/web/app/components/base/date-and-time-picker/date-picker/index.tsx b/web/app/components/base/date-and-time-picker/date-picker/index.tsxdeleted file mode 100644index dda231b7211..00000000000--- a/web/app/components/base/date-and-time-picker/date-picker/index.tsx+++ /dev/null@@ -1,392 +0,0 @@-import type { PopoverProps } from '@langgenius/dify-ui/popover'-import type { Dayjs } from 'dayjs'-import type { DatePickerProps, Period } from '../types'-import { cn } from '@langgenius/dify-ui/cn'-import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import * as React from 'react'-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { useTranslation } from 'react-i18next'-import Calendar from '../calendar'-import TimePickerHeader from '../time-picker/header'-import TimePickerOptions from '../time-picker/options'-import { ViewType } from '../types'-import dayjs, {- clearMonthMapCache,- cloneTime,- getDateWithTimezone,- getDaysInMonth,- getHourIn12Hour,-} from '../utils/dayjs'-import YearAndMonthPickerFooter from '../year-and-month-picker/footer'-import YearAndMonthPickerHeader from '../year-and-month-picker/header'-import YearAndMonthPickerOptions from '../year-and-month-picker/options'-import DatePickerFooter from './footer'-import DatePickerHeader from './header'--const DatePicker = ({- value,- timezone,- onChange,- onClear,- placeholder,- disabled = false,- needTimePicker = true,- renderTrigger,- triggerWrapClassName,- noConfirm,- getIsDateDisabled,-}: DatePickerProps) => {- const { t } = useTranslation(['common', 'time'])- const [isOpen, setIsOpen] = useState(false)- const [view, setView] = useState<ViewType>(ViewType.date)- const dateConfirmationViews: readonly ViewType[] = [ViewType.date, ViewType.time]- const isInitialRef = useRef(true)- const triggerAreaRef = useRef<HTMLDivElement>(null)-- // Normalize the value to ensure that all subsequent uses are Day.js objects.- const normalizedValue = useMemo(() => {- if (!value) return undefined- return dayjs.isDayjs(value) ? value.tz(timezone) : dayjs(value).tz(timezone)- }, [value, timezone])-- const inputValue = useRef(normalizedValue).current- const defaultValue = useRef(getDateWithTimezone({ timezone })).current-- const [currentDate, setCurrentDate] = useState(inputValue || defaultValue)- const [selectedDate, setSelectedDate] = useState(inputValue)-- const [selectedMonth, setSelectedMonth] = useState(() => (inputValue || defaultValue).month())- const [selectedYear, setSelectedYear] = useState(() => (inputValue || defaultValue).year())-- useEffect(() => {- if (isInitialRef.current) {- isInitialRef.current = false- return- }- clearMonthMapCache()- if (normalizedValue) {- const newValue = getDateWithTimezone({ date: normalizedValue, timezone })- // oxlint-disable-next-line eslint-react/set-state-in-effect -- timezone changes intentionally resync the displayed calendar state.- setCurrentDate(newValue)- // oxlint-disable-next-line eslint-react/set-state-in-effect -- timezone changes intentionally resync the selected value.- setSelectedDate(newValue)- onChange(newValue)- } else {- // oxlint-disable-next-line eslint-react/set-state-in-effect -- timezone changes intentionally resync the displayed calendar state.- setCurrentDate((prev) => getDateWithTimezone({ date: prev, timezone }))- // oxlint-disable-next-line eslint-react/set-state-in-effect -- timezone changes intentionally resync the selected value.- setSelectedDate((prev) => (prev ? getDateWithTimezone({ date: prev, timezone }) : undefined))- }- // oxlint-disable-next-line react/exhaustive-deps -- this effect intentionally runs only when timezone changes.- }, [timezone])-- const handleOpenChange = useCallback<NonNullable<PopoverProps['onOpenChange']>>(- (nextOpen, details) => {- const isFocusGuardClose =- !nextOpen && details.reason === 'focus-out' && details.event.type === 'focusin'- if (isFocusGuardClose) {- details.cancel()- // Let Base UI move focus past its guard before the controlled root closes.- queueMicrotask(() => {- setIsOpen(false)- setView(ViewType.date)- })- return- }- const outsideTarget =- details.reason === 'focus-out' && details.event instanceof FocusEvent- ? details.event.relatedTarget- : details.event.target- if (- !nextOpen &&- (details.reason === 'outside-press' || details.reason === 'focus-out') &&- outsideTarget instanceof Node &&- triggerAreaRef.current?.contains(outsideTarget)- ) {- details.cancel()- return- }- setIsOpen(nextOpen)- setView(ViewType.date)- if (nextOpen && normalizedValue) {- setCurrentDate(normalizedValue)- setSelectedDate(normalizedValue)- }- },- [normalizedValue],- )-- const handleClickTrigger = (e: React.MouseEvent) => {- e.stopPropagation()- }-- const handleClear = (e: React.MouseEvent) => {- e.stopPropagation()- setSelectedDate(undefined)- if (!isOpen) onClear()- }-- const days = useMemo(() => {- return getDaysInMonth(currentDate)- }, [currentDate])-- const handleClickNextMonth = useCallback(() => {- setCurrentDate(currentDate.clone().add(1, 'month'))- }, [currentDate])-- const handleClickPrevMonth = useCallback(() => {- setCurrentDate(currentDate.clone().subtract(1, 'month'))- }, [currentDate])-- const handleConfirmDate = useCallback(- (passedInSelectedDate?: Dayjs) => {- // passedInSelectedDate may be a click event when noConfirm is false- const nextDate = dayjs.isDayjs(passedInSelectedDate) ? passedInSelectedDate : selectedDate- onChange(nextDate ? nextDate.tz(timezone) : undefined)- setIsOpen(false)- },- [selectedDate, onChange, timezone],- )-- const handleDateSelect = useCallback(- (day: Dayjs) => {- const newDate = cloneTime(day, selectedDate || getDateWithTimezone({ timezone }))- setCurrentDate(newDate)- setSelectedDate(newDate)- if (noConfirm) handleConfirmDate(newDate)- },- [selectedDate, timezone, noConfirm, handleConfirmDate],- )-- const handleSelectCurrentDate = () => {- const newDate = getDateWithTimezone({ timezone })- setCurrentDate(newDate)- setSelectedDate(newDate)- onChange(newDate)- setIsOpen(false)- }-- const handleClickTimePicker = () => {- if (view === ViewType.date) {- setView(ViewType.time)- return- }- if (view === ViewType.time) setView(ViewType.date)- }-- const handleTimeSelect = (hour: string, minute: string, period: Period) => {- const newTime = cloneTime(dayjs(), dayjs(`1/1/2000 ${hour}:${minute} ${period}`))- setSelectedDate((prev) => {- return prev ? cloneTime(prev, newTime) : newTime- })- }-- const handleSelectHour = useCallback(- (hour: string) => {- const selectedTime = selectedDate || getDateWithTimezone({ timezone })- handleTimeSelect(- hour,- selectedTime.minute().toString().padStart(2, '0'),- selectedTime.format('A') as Period,- )- },- [selectedDate, timezone],- )-- const handleSelectMinute = useCallback(- (minute: string) => {- const selectedTime = selectedDate || getDateWithTimezone({ timezone })- handleTimeSelect(- getHourIn12Hour(selectedTime).toString().padStart(2, '0'),- minute,- selectedTime.format('A') as Period,- )- },- [selectedDate, timezone],- )-- const handleSelectPeriod = useCallback(- (period: Period) => {- const selectedTime = selectedDate || getDateWithTimezone({ timezone })- handleTimeSelect(- getHourIn12Hour(selectedTime).toString().padStart(2, '0'),- selectedTime.minute().toString().padStart(2, '0'),- period,- )- },- [selectedDate, timezone],- )-- const handleOpenYearMonthPicker = () => {- setSelectedMonth(currentDate.month())- setSelectedYear(currentDate.year())- setView(ViewType.yearMonth)- }-- const handleCloseYearMonthPicker = useCallback(() => {- setView(ViewType.date)- }, [])-- const handleMonthSelect = useCallback((month: number) => {- setSelectedMonth(month)- }, [])-- const handleYearSelect = useCallback((year: number) => {- setSelectedYear(year)- }, [])-- const handleYearMonthCancel = useCallback(() => {- setView(ViewType.date)- }, [])-- const handleYearMonthConfirm = () => {- setCurrentDate((prev) => prev.clone().month(selectedMonth).year(selectedYear))- setView(ViewType.date)- }-- const timeFormat = needTimePicker- ? t(($) => $['dateFormats.displayWithTime'], { ns: 'time' })- : t(($) => $['dateFormats.display'], { ns: 'time' })- const displayValue = normalizedValue?.format(timeFormat) || ''- const displayTime = selectedDate?.format('hh:mm A') || '--:-- --'- return (- <Popover open={isOpen} onOpenChange={handleOpenChange}>- <div ref={triggerAreaRef} className={cn('min-w-0', triggerWrapClassName)}>- <PopoverTrigger- disabled={disabled}- onClick={handleClickTrigger}- className={triggerWrapClassName}- render={(props, state) => {- if (renderTrigger) {- return renderTrigger(props, state, {- value: normalizedValue,- selectedDate,- handleClear,- })- }-- const triggerPlaceholder = placeholder || t(($) => $.defaultPlaceholder, { ns: 'time' })- const triggerDisplayValue = state.open- ? selectedDate?.format(timeFormat) || ''- : displayValue-- return (- <div- className={cn(- 'group relative flex w-63 items-center rounded-lg bg-components-input-bg-normal hover:bg-state-base-hover-alt',- disabled && 'opacity-60',- props.className,- )}- >- <button- {...props}- type="button"- aria-label={`${triggerPlaceholder}${triggerDisplayValue ? `: ${triggerDisplayValue}` : ''}`}- className="flex min-w-0 flex-1 cursor-pointer items-center gap-x-0.5 rounded-lg px-2 py-1 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden disabled:cursor-default"- data-testid="date-picker-trigger"- >- <span- className={cn(- 'min-w-0 flex-1 truncate p-1 system-xs-regular',- triggerDisplayValue- ? 'text-components-input-text-filled'- : 'text-components-input-text-placeholder',- )}- >- {triggerDisplayValue || triggerPlaceholder}- </span>- <span- aria-hidden- className={cn(- 'i-ri-calendar-line size-4 shrink-0 text-text-quaternary',- state.open ? 'text-text-secondary' : 'group-hover:text-text-secondary',- )}- />- </button>- {(displayValue || (state.open && selectedDate)) && !disabled && (- <button- type="button"- aria-label={t(($) => $['operation.clear'], { ns: 'common' })}- className="absolute right-2 flex size-4 shrink-0 items-center justify-center rounded-full border-none bg-components-input-bg-normal p-0 text-text-quaternary opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 hover:text-text-secondary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden [@media(hover:none)]:opacity-100"- onClick={handleClear}- >- <span className="i-ri-close-circle-fill size-4" aria-hidden="true" />- </button>- )}- </div>- )- }}- />- </div>- <PopoverContent- placement="bottom-end"- sideOffset={0}- className="border-none bg-transparent shadow-none"- >- <div className="mt-1 w-63 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg shadow-shadow-shadow-5">- {/* Header */}- {view === ViewType.date ? (- <DatePickerHeader- handleOpenYearMonthPicker={handleOpenYearMonthPicker}- currentDate={currentDate}- onClickNextMonth={handleClickNextMonth}- onClickPrevMonth={handleClickPrevMonth}- />- ) : view === ViewType.yearMonth ? (- <YearAndMonthPickerHeader- selectedYear={selectedYear}- selectedMonth={selectedMonth}- onClick={handleCloseYearMonthPicker}- />- ) : (- <TimePickerHeader />- )}-- {/* Content */}- {view === ViewType.date ? (- <Calendar- days={days}- selectedDate={selectedDate}- onDateClick={handleDateSelect}- getIsDateDisabled={getIsDateDisabled}- />- ) : view === ViewType.yearMonth ? (- <YearAndMonthPickerOptions- selectedMonth={selectedMonth}- selectedYear={selectedYear}- handleMonthSelect={handleMonthSelect}- handleYearSelect={handleYearSelect}- />- ) : (- <TimePickerOptions- selectedTime={selectedDate}- handleSelectHour={handleSelectHour}- handleSelectMinute={handleSelectMinute}- handleSelectPeriod={handleSelectPeriod}- />- )}-- {/* Footer */}- {dateConfirmationViews.includes(view) && !noConfirm && (- <DatePickerFooter- needTimePicker={needTimePicker}- displayTime={displayTime}- view={view}- handleClickTimePicker={handleClickTimePicker}- handleSelectCurrentDate={handleSelectCurrentDate}- handleConfirmDate={handleConfirmDate}- />- )}- {!dateConfirmationViews.includes(view) && (- <YearAndMonthPickerFooter- handleYearMonthCancel={handleYearMonthCancel}- handleYearMonthConfirm={handleYearMonthConfirm}- />- )}- </div>- </PopoverContent>- </Popover>- )-}--export default DatePickerdiff --git a/web/app/components/base/date-and-time-picker/date-range-picker/index.tsx b/web/app/components/base/date-and-time-picker/date-range-picker/index.tsxdeleted file mode 100644index 05105b825f5..00000000000--- a/web/app/components/base/date-and-time-picker/date-range-picker/index.tsx+++ /dev/null@@ -1,138 +0,0 @@-'use client'--import type { Dayjs } from 'dayjs'-import type { FC } from 'react'-import type { DatePickerProps, TriggerProps } from '../types'-import { cn } from '@langgenius/dify-ui/cn'-import { noop } from 'es-toolkit/function'-import * as React from 'react'-import { useTranslation } from 'react-i18next'-import { useLocale } from '#i18n'-import { formatToLocalTime } from '@/utils/format'-import DatePicker from '../date-picker'--type DateRangePickerProps = Readonly<{- start?: Dayjs- end?: Dayjs- timezone?: string- displayFormat?: string- startPlaceholder?: string- endPlaceholder?: string- onStartChange: (date?: Dayjs) => void- onEndChange: (date?: Dayjs) => void- clearable?: boolean- disabled?: boolean- getIsStartDateDisabled?: DatePickerProps['getIsDateDisabled']- getIsEndDateDisabled?: DatePickerProps['getIsDateDisabled']- className?: string-}>--const DateRangePicker: FC<DateRangePickerProps> = ({- start,- end,- timezone,- displayFormat = 'MMM D',- startPlaceholder,- endPlaceholder,- onStartChange,- onEndChange,- clearable = false,- disabled = false,- getIsStartDateDisabled,- getIsEndDateDisabled,- className,-}) => {- const { t } = useTranslation(['common'])- const locale = useLocale()-- const renderDate = (- placeholder: string | undefined,- onChange: (date?: Dayjs) => void,- ): NonNullable<DatePickerProps['renderTrigger']> => {- return (props, _state, { value, handleClear }: TriggerProps) => {- const displayValue = value ? formatToLocalTime(value, locale, displayFormat) : ''- const triggerLabel = placeholder- ? `${placeholder}${displayValue ? `: ${displayValue}` : ''}`- : displayValue-- return (- <div className="group/date-trigger relative min-w-0">- <button- {...props}- type="button"- aria-label={triggerLabel}- className={cn(- 'flex h-7 min-w-0 cursor-pointer items-center rounded-lg px-1 system-sm-regular text-components-input-text-filled hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover',- disabled && 'cursor-default hover:bg-transparent',- props.className,- )}- >- <span className={cn('truncate', !value && 'text-components-input-text-placeholder')}>- {displayValue || placeholder}- </span>- </button>- {clearable && value && !disabled && (- <button- type="button"- aria-label={- placeholder- ? `${placeholder}: ${t(($) => $['operation.clear'], { ns: 'common' })}`- : t(($) => $['operation.clear'], { ns: 'common' })- }- className="pointer-events-none absolute top-1/2 right-1 z-1 flex size-4 -translate-y-1/2 items-center justify-center rounded border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg text-text-tertiary opacity-0 shadow-xs group-focus-within/date-trigger:pointer-events-auto group-focus-within/date-trigger:opacity-100 group-hover/date-trigger:pointer-events-auto group-hover/date-trigger:opacity-100 hover:bg-components-button-secondary-bg-hover hover:text-text-secondary [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"- onClick={(event) => {- handleClear(event)- onChange(undefined)- }}- >- <span className="i-ri-close-circle-fill size-3.5" aria-hidden="true" />- </button>- )}- </div>- )- }- }-- return (- <div- className={cn(- 'flex h-8 min-w-0 items-center space-x-0.5 rounded-lg bg-components-input-bg-normal px-2',- disabled && 'opacity-60',- className,- )}- >- <div className="shrink-0 p-px">- <span className="i-ri-calendar-line block size-3.5 text-text-tertiary" aria-hidden="true" />- </div>- <DatePicker- disabled={disabled}- value={start}- timezone={timezone}- onChange={onStartChange}- onClear={noop}- renderTrigger={renderDate(startPlaceholder, onStartChange)}- triggerWrapClassName="min-w-0"- needTimePicker={false}- noConfirm- getIsDateDisabled={getIsStartDateDisabled}- />- <span className="shrink-0 system-sm-regular text-text-tertiary" aria-hidden="true">- -- </span>- <DatePicker- disabled={disabled}- value={end}- timezone={timezone}- onChange={onEndChange}- onClear={noop}- renderTrigger={renderDate(endPlaceholder, onEndChange)}- triggerWrapClassName="min-w-0"- needTimePicker={false}- noConfirm- getIsDateDisabled={getIsEndDateDisabled}- />- </div>- )-}--export default React.memo(DateRangePicker)diff --git a/web/app/components/base/date-and-time-picker/hooks.ts b/web/app/components/base/date-and-time-picker/hooks.tsdeleted file mode 100644index 1df105bb936..00000000000--- a/web/app/components/base/date-and-time-picker/hooks.ts+++ /dev/null@@ -1,49 +0,0 @@-import { useTranslation } from 'react-i18next'-import { Period } from './types'-import dayjs from './utils/dayjs'--const YEAR_RANGE = 100--const daysInWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const--export const useDaysOfWeek = () => {- const { t } = useTranslation(['time'])- return daysInWeek.map((day) => t(($) => $[`daysInWeek.${day}`], { ns: 'time' }))-}--const monthNames = [- 'January',- 'February',- 'March',- 'April',- 'May',- 'June',- 'July',- 'August',- 'September',- 'October',- 'November',- 'December',-] as const--export const useMonths = () => {- const { t } = useTranslation(['time'])- return monthNames.map((month) => t(($) => $[`months.${month}`], { ns: 'time' }))-}--export const useYearOptions = () => {- const yearOptions = Array.from({ length: 200 }, (_, i) => dayjs().year() - YEAR_RANGE / 2 + i)- return yearOptions-}--export const useTimeOptions = () => {- const hourOptions = Array.from({ length: 12 }, (_, i) => (i + 1).toString().padStart(2, '0'))- const minuteOptions = Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0'))- const periodOptions = [Period.AM, Period.PM]-- return {- hourOptions,- minuteOptions,- periodOptions,- }-}diff --git a/web/app/components/base/date-and-time-picker/index.stories.tsx b/web/app/components/base/date-and-time-picker/index.stories.tsxdeleted file mode 100644index 3fe8cac2f07..00000000000--- a/web/app/components/base/date-and-time-picker/index.stories.tsx+++ /dev/null@@ -1,97 +0,0 @@-import type { Meta, StoryObj } from '@storybook/nextjs-vite'-import type { DatePickerProps } from './types'-import { useState } from 'react'-import { fn } from 'storybook/test'-import DatePicker from './date-picker'-import dayjs, { getDateWithTimezone } from './utils/dayjs'--const meta = {- title: 'Base/Data Entry/DateAndTimePicker',- component: DatePicker,- parameters: {- docs: {- description: {- component:- 'Combined date and time picker with timezone support. Includes shortcuts for “now”, year-month navigation, and optional time selection.',- },- },- },- tags: ['autodocs'],- args: {- value: getDateWithTimezone({}),- timezone: dayjs.tz.guess(),- needTimePicker: true,- placeholder: 'Select schedule time',- onChange: fn(),- onClear: fn(),- },-} satisfies Meta<typeof DatePicker>--export default meta-type Story = StoryObj<typeof meta>--const DatePickerPlayground = (props: DatePickerProps) => {- const [value, setValue] = useState(props.value)-- return (- <div className="inline-flex flex-col items-start gap-3">- <DatePicker- {...props}- value={value}- onChange={setValue}- onClear={() => setValue(undefined)}- />- <div className="w-63 rounded-lg border border-divider-subtle bg-components-panel-bg p-3 text-xs text-text-secondary">- Selected datetime:{' '}- <span className="font-mono text-text-primary">{value ? value.format() : 'undefined'}</span>- </div>- </div>- )-}--export const Playground: Story = {- render: (args) => <DatePickerPlayground {...args} />,- args: {- ...meta.args,- needTimePicker: false,- placeholder: 'Select due date',- },- parameters: {- docs: {- source: {- language: 'tsx',- code: `-const [value, setValue] = useState(getDateWithTimezone({}))--<DatePicker- value={value}- timezone={dayjs.tz.guess()}- onChange={setValue}- onClear={() => setValue(undefined)}-/>- `.trim(),- },- },- },-}--export const DateOnly: Story = {- render: (args) => (- <DatePickerPlayground {...args} needTimePicker={false} placeholder="Select due date" />- ),- args: {- ...meta.args,- needTimePicker: false,- placeholder: 'Select due date',- },- parameters: {- docs: {- source: {- language: 'tsx',- code: `-<DatePicker needTimePicker={false} placeholder="Select due date" />- `.trim(),- },- },- },-}diff --git a/web/app/components/base/date-and-time-picker/time-picker/__tests__/footer.spec.tsx b/web/app/components/base/date-and-time-picker/time-picker/__tests__/footer.spec.tsxdeleted file mode 100644index 46965df2364..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/__tests__/footer.spec.tsx+++ /dev/null@@ -1,52 +0,0 @@-import type { TimePickerFooterProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import Footer from '../footer'--// Factory for TimePickerFooter props-const createFooterProps = (- overrides: Partial<TimePickerFooterProps> = {},-): TimePickerFooterProps => ({- handleSelectCurrentTime: vi.fn(),- handleConfirm: vi.fn(),- ...overrides,-})--describe('TimePicker Footer', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render Now and OK buttons', () => {- const props = createFooterProps()- render(<Footer {...props} />)-- expect(screen.getByText(/operation\.now/)).toBeInTheDocument()- expect(screen.getByText(/operation\.ok/)).toBeInTheDocument()- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call handleSelectCurrentTime when Now button is clicked', () => {- const handleSelectCurrentTime = vi.fn()- const props = createFooterProps({ handleSelectCurrentTime })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.now/))-- expect(handleSelectCurrentTime).toHaveBeenCalledTimes(1)- })-- it('should call handleConfirm when OK button is clicked', () => {- const handleConfirm = vi.fn()- const props = createFooterProps({ handleConfirm })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.ok/))-- expect(handleConfirm).toHaveBeenCalledTimes(1)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx b/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsxdeleted file mode 100644index 61af8702376..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/__tests__/index.spec.tsx+++ /dev/null@@ -1,728 +0,0 @@-import type { TimePickerProps } from '../../types'-import { fireEvent, render, screen, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import dayjs, { isDayjsObject } from '../../utils/dayjs'-import TimePicker from '../index'--// Mock scrollIntoView since the test DOM runtime doesn't implement it-beforeAll(() => {- Element.prototype.scrollIntoView = vi.fn()-})--describe('TimePicker', () => {- const baseProps: Pick<TimePickerProps, 'onChange' | 'onClear' | 'value'> = {- onChange: vi.fn(),- onClear: vi.fn(),- value: undefined,- }-- beforeEach(() => {- vi.clearAllMocks()- })-- it('renders formatted value for string input (Issue #26692 regression)', () => {- render(<TimePicker {...baseProps} value="18:45" timezone="UTC" />)-- expect(screen.getByDisplayValue('06:45 PM'))!.toBeInTheDocument()- })-- it('confirms cleared value when confirming without selection', () => {- render(<TimePicker {...baseProps} value={dayjs('2024-01-01T03:30:00Z')} timezone="UTC" />)-- const input = screen.getByRole('textbox')- fireEvent.click(input)-- const clearButton = screen.getByRole('button', { name: /operation\.clear/i })- fireEvent.click(clearButton)-- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(baseProps.onChange).toHaveBeenCalledTimes(1)- expect(baseProps.onChange).toHaveBeenCalledWith(undefined)- expect(baseProps.onClear).not.toHaveBeenCalled()- })-- it('selecting current time emits timezone-aware value', () => {- const onChange = vi.fn()- render(<TimePicker {...baseProps} onChange={onChange} timezone="America/New_York" />)-- // Open the picker first to access content- fireEvent.click(screen.getByRole('textbox'))-- const nowButton = screen.getByRole('button', { name: /operation\.now/i })- fireEvent.click(nowButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted?.utcOffset()).toBe(dayjs().tz('America/New_York').utcOffset())- })-- // Opening and closing behavior tests- describe('Open/Close Behavior', () => {- it('should show placeholder when no value is provided', () => {- render(<TimePicker {...baseProps} />)-- const input = screen.getByRole('textbox')- expect(input)!.toHaveAttribute('placeholder', expect.stringMatching(/defaultPlaceholder/i))- })-- it('should toggle open state when trigger is clicked', () => {- render(<TimePicker {...baseProps} value="10:00 AM" timezone="UTC" />)-- const input = screen.getByRole('textbox')- // Open- fireEvent.click(input)- expect(input)!.toHaveValue('')-- // Close by clicking again- fireEvent.click(input)- expect(input)!.toHaveValue('10:00 AM')- })-- it('should close when clicking outside while the picker is open', async () => {- const user = userEvent.setup()- render(<TimePicker {...baseProps} value="10:00 AM" timezone="UTC" />)-- const input = screen.getByRole('textbox')- fireEvent.click(input)- expect(input)!.toHaveValue('')-- await user.click(document.body)- expect(input).toHaveValue('10:00 AM')- })-- it('should call onClear when clear is clicked while picker is closed', () => {- const onClear = vi.fn()- render(<TimePicker {...baseProps} onClear={onClear} value="10:00 AM" timezone="UTC" />)-- const clearButton = screen.getByRole('button', { name: /operation\.clear/i })- fireEvent.click(clearButton)-- expect(onClear).toHaveBeenCalledTimes(1)- })-- it('should not call onClear when clear is clicked while picker is open', () => {- const onClear = vi.fn()- render(<TimePicker {...baseProps} onClear={onClear} value="10:00 AM" timezone="UTC" />)-- // Open picker first- fireEvent.click(screen.getByRole('textbox'))- // Then clear- const clearButton = screen.getByRole('button', { name: /operation\.clear/i })- fireEvent.click(clearButton)-- expect(onClear).not.toHaveBeenCalled()- })-- it('should sync selectedTime from value when opening with stale state', () => {- const onChange = vi.fn()- render(<TimePicker {...baseProps} onChange={onChange} value="10:00 AM" timezone="UTC" />)-- const input = screen.getByRole('textbox')- // Open - this triggers handleClickTrigger which syncs selectedTime from value- fireEvent.click(input)-- // Confirm to verify selectedTime was synced from value prop ("10:00 AM")- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)- expect(onChange).toHaveBeenCalledTimes(1)-- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted.hour()).toBe(10)- expect(emitted.minute()).toBe(0)- })-- it('should resync selectedTime when opening after internal clear', () => {- const onChange = vi.fn()- render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- const input = screen.getByRole('textbox')- // Open- fireEvent.click(input)-- // Clear selected time internally- const clearButton = screen.getByRole('button', { name: /operation\.clear/i })- fireEvent.click(clearButton)-- // Close- fireEvent.click(input)-- // Open again - should resync selectedTime from value prop- fireEvent.click(input)-- // Confirm to verify the value was resynced- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- // Resynced from value prop: dayjs('2024-01-01T10:30:00Z') in UTC = 10:30 AM- expect(emitted.hour()).toBe(10)- expect(emitted.minute()).toBe(30)- })- })-- // Props tests- describe('Props', () => {- it('should show custom placeholder when provided', () => {- render(<TimePicker {...baseProps} placeholder="Select time" />)-- const input = screen.getByRole('textbox')- expect(input)!.toHaveAttribute('placeholder', 'Select time')- })-- it('should render with triggerFullWidth prop without errors', () => {- render(<TimePicker {...baseProps} triggerFullWidth={true} />)-- // Verify the component renders successfully with triggerFullWidth- // Verify the component renders successfully with triggerFullWidth- expect(screen.getByRole('textbox'))!.toBeInTheDocument()- })-- it('should use renderTrigger when provided', () => {- const renderTrigger = vi.fn((triggerProps, _state, { inputElem }) => (- <div {...triggerProps} data-testid="custom-trigger">- {inputElem}- </div>- ))-- render(<TimePicker {...baseProps} renderTrigger={renderTrigger} />)-- expect(screen.getByTestId('custom-trigger'))!.toBeInTheDocument()- expect(renderTrigger).toHaveBeenCalled()- })-- it('should expose Base UI trigger state and props to a custom trigger', () => {- const renderTrigger = vi.fn((triggerProps, state, { inputElem }) => (- <button {...triggerProps} data-testid="state-trigger">- {state.open ? 'Open' : 'Closed'}- {inputElem}- </button>- ))-- render(<TimePicker {...baseProps} renderTrigger={renderTrigger} />)-- expect(screen.getByTestId('state-trigger')).toHaveTextContent('Closed')- expect(screen.getByTestId('state-trigger')).not.toHaveAttribute('data-popup-open')-- fireEvent.click(screen.getByTestId('state-trigger'))-- expect(screen.getByTestId('state-trigger')).toHaveTextContent('Open')- expect(screen.getByTestId('state-trigger')).toHaveAttribute('data-popup-open')- })-- it('supports one named native button without an inner text field for a custom trigger', async () => {- const user = userEvent.setup()- render(- <TimePicker- {...baseProps}- value="10:45 AM"- timezone="UTC"- triggerNativeButton- renderTrigger={(props, _state, { displayText }) => (- <button {...props} type="button">- <span className="sr-only">Update Time</span>- <span>{displayText}</span>- <span>UTC</span>- </button>- )}- />,- )-- const trigger = screen.getByRole('button', { name: 'Update Time 10:45 AM UTC' })- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()-- trigger.focus()- await user.keyboard('{Enter}')- expect(trigger).toHaveAttribute('data-popup-open')- })-- it('should render with notClearable prop without errors', () => {- render(<TimePicker {...baseProps} notClearable={true} value="10:00 AM" timezone="UTC" />)-- // In test env the icon stays in DOM, but must remain hidden when notClearable is set- // In test env the icon stays in DOM, but must remain hidden when notClearable is set- expect(screen.getByRole('button', { name: /clear/i }))!.toHaveClass('hidden')- })- })-- // Confirm behavior tests- describe('Confirm Behavior', () => {- it('should emit selected time when confirm is clicked with a value', () => {- const onChange = vi.fn()- render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- // Open the picker first to access content- fireEvent.click(screen.getByRole('textbox'))-- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted.hour()).toBe(10)- expect(emitted.minute()).toBe(30)- })- })-- // Time selection handler tests- describe('Time Selection', () => {- const openPicker = () => {- fireEvent.click(screen.getByRole('textbox'))- }-- const getHourAndMinuteLists = () => {- const allLists = screen.getAllByRole('list')- const hourList = allLists.find(- (list) =>- within(list).queryByText('01') &&- within(list).queryByText('12') &&- !within(list).queryByText('59'),- )- const minuteList = allLists.find(- (list) => within(list).queryByText('00') && within(list).queryByText('59'),- )-- expect(hourList).toBeTruthy()- expect(minuteList).toBeTruthy()-- return {- hourList: hourList!,- minuteList: minuteList!,- }- }-- it('should update selectedTime when hour is selected', () => {- const onChange = vi.fn()- render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- openPicker()-- // Click hour "05" from the time options- const { hourList } = getHourAndMinuteLists()- fireEvent.click(within(hourList).getByText('05'))-- // Now confirm to verify the selectedTime was updated- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- // Hour 05 in AM (since original was 10:30 AM) = 5- expect(emitted.hour()).toBe(5)- })-- it('should update selectedTime when minute is selected', () => {- const onChange = vi.fn()- render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- openPicker()-- // Click minute "45" from the time options- const { minuteList } = getHourAndMinuteLists()- fireEvent.click(within(minuteList).getByText('45'))-- // Confirm- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(emitted.minute()).toBe(45)- })-- it('should update selectedTime when period is changed', () => {- const onChange = vi.fn()- render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- openPicker()-- // Click PM to switch period- fireEvent.click(screen.getByText('PM'))-- // Confirm- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- // Original was 10:30 AM, switching to PM makes it 22:30- expect(emitted.hour()).toBe(22)- })-- it('should create new time when selecting hour without prior selectedTime', () => {- const onChange = vi.fn()- render(<TimePicker {...baseProps} onChange={onChange} timezone="UTC" />)-- openPicker()-- // Click hour "03" with no existing selectedTime- const { hourList } = getHourAndMinuteLists()- fireEvent.click(within(hourList).getByText('03'))-- // Confirm- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted.hour()).toBe(3)- })-- it('should handle minute selection without prior selectedTime', () => {- const onChange = vi.fn()- render(<TimePicker {...baseProps} onChange={onChange} timezone="UTC" />)-- openPicker()-- // Click minute "15" with no existing selectedTime- const { minuteList } = getHourAndMinuteLists()- fireEvent.click(within(minuteList).getByText('15'))-- // Confirm- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(emitted.minute()).toBe(15)- })-- it('should handle period selection without prior selectedTime', () => {- const onChange = vi.fn()- render(<TimePicker {...baseProps} onChange={onChange} timezone="UTC" />)-- openPicker()-- // Click PM with no existing selectedTime- fireEvent.click(screen.getByText('PM'))-- // Confirm- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted.hour()).toBeGreaterThanOrEqual(12)- })-- it('should handle selection when timezone is undefined', () => {- const onChange = vi.fn()- // Render without timezone prop- render(<TimePicker {...baseProps} onChange={onChange} />)- openPicker()-- // Click hour "03"- const { hourList } = getHourAndMinuteLists()- fireEvent.click(within(hourList).getByText('03'))-- const confirmButton = screen.getByRole('button', { name: /operation\.ok/i })- fireEvent.click(confirmButton)-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(emitted.hour()).toBe(3)- })- })-- // Timezone change effect tests- describe('Timezone Changes', () => {- it('should return early when only onChange reference changes', () => {- const value = dayjs('2024-01-01T10:30:00Z')- const onChangeA = vi.fn()- const onChangeB = vi.fn()-- const { rerender } = render(- <TimePicker {...baseProps} onChange={onChangeA} value={value} timezone="UTC" />,- )-- rerender(<TimePicker {...baseProps} onChange={onChangeB} value={value} timezone="UTC" />)-- expect(onChangeA).not.toHaveBeenCalled()- expect(onChangeB).not.toHaveBeenCalled()- expect(screen.getByDisplayValue('10:30 AM'))!.toBeInTheDocument()- })-- it('should safely return when value changes to an unparsable time string', () => {- const onChange = vi.fn()- const invalidValue = 123 as unknown as TimePickerProps['value']- const { rerender } = render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- rerender(- <TimePicker {...baseProps} onChange={onChange} value={invalidValue} timezone="UTC" />,- )-- expect(onChange).not.toHaveBeenCalled()- expect(screen.getByRole('textbox'))!.toHaveValue('')- })-- it('should call onChange when timezone changes with an existing value', () => {- const onChange = vi.fn()- const value = dayjs('2024-01-01T10:30:00Z')- const { rerender } = render(- <TimePicker {...baseProps} onChange={onChange} value={value} timezone="UTC" />,- )-- // Change timezone without changing value (same reference)- rerender(- <TimePicker {...baseProps} onChange={onChange} value={value} timezone="America/New_York" />,- )-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- // 10:30 UTC converted to America/New_York (UTC-5 in Jan) = 05:30- expect(emitted.utcOffset()).toBe(dayjs.tz('2024-01-01', 'America/New_York').utcOffset())- expect(emitted.hour()).toBe(5)- expect(emitted.minute()).toBe(30)- })-- it('should update selectedTime when value changes', () => {- const onChange = vi.fn()- const { rerender } = render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- // Change value- rerender(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T14:00:00Z')}- timezone="UTC"- />,- )-- // onChange should not be called when only value changes (no timezone change)- expect(onChange).not.toHaveBeenCalled()-- // But the display should update- // But the display should update- expect(screen.getByDisplayValue('02:00 PM'))!.toBeInTheDocument()- })-- it('should handle timezone change when value is undefined', () => {- const onChange = vi.fn()- const { rerender } = render(<TimePicker {...baseProps} onChange={onChange} timezone="UTC" />)-- // Change timezone without a value- rerender(<TimePicker {...baseProps} onChange={onChange} timezone="America/New_York" />)-- // onChange should not be called when value is undefined- expect(onChange).not.toHaveBeenCalled()- })-- it('should handle timezone change when selectedTime exists but value becomes undefined', () => {- const onChange = vi.fn()- const { rerender } = render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )- // Remove value and change timezone- rerender(- <TimePicker- {...baseProps}- onChange={onChange}- value={undefined}- timezone="America/New_York"- />,- )- // Input should be empty now- // Input should be empty now- expect(screen.getByRole('textbox'))!.toHaveValue('')- // onChange should not fire when value is undefined, even if selectedTime was set- expect(onChange).not.toHaveBeenCalled()- })-- it('should preserve selected time when value is removed and timezone is undefined', () => {- const onChange = vi.fn()- const { rerender } = render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- rerender(- <TimePicker {...baseProps} onChange={onChange} value={undefined} timezone={undefined} />,- )-- fireEvent.click(screen.getByRole('textbox'))- fireEvent.click(screen.getByRole('button', { name: /operation\.ok/i }))-- expect(onChange).toHaveBeenCalledTimes(1)- const emitted = onChange.mock.calls[0]![0]- expect(isDayjsObject(emitted)).toBe(true)- expect(emitted.hour()).toBe(10)- expect(emitted.minute()).toBe(30)- })-- it('should not update when neither timezone nor value changes', () => {- const onChange = vi.fn()- const value = dayjs('2024-01-01T10:30:00Z')- const { rerender } = render(- <TimePicker {...baseProps} onChange={onChange} value={value} timezone="UTC" />,- )-- // Rerender with same props- rerender(<TimePicker {...baseProps} onChange={onChange} value={value} timezone="UTC" />)-- expect(onChange).not.toHaveBeenCalled()- })-- it('should update display when both value and timezone change', () => {- const onChange = vi.fn()- const { rerender } = render(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T10:30:00Z')}- timezone="UTC"- />,- )-- // Change both value and timezone simultaneously- rerender(- <TimePicker- {...baseProps}- onChange={onChange}- value={dayjs('2024-01-01T15:00:00Z')}- timezone="America/New_York"- />,- )-- // onChange should not be called since both changed (timezoneChanged && !valueChanged is false)- expect(onChange).not.toHaveBeenCalled()-- // 15:00 UTC in America/New_York (UTC-5) = 10:00 AM- // 15:00 UTC in America/New_York (UTC-5) = 10:00 AM- expect(screen.getByDisplayValue('10:00 AM'))!.toBeInTheDocument()- })- })-- // Format time value tests- describe('Format Time Value', () => {- it('should return empty string when value is undefined', () => {- render(<TimePicker {...baseProps} />)-- expect(screen.getByRole('textbox'))!.toHaveValue('')- })-- it('should format dayjs value correctly', () => {- render(<TimePicker {...baseProps} value={dayjs('2024-01-01T14:30:00Z')} timezone="UTC" />)-- expect(screen.getByDisplayValue('02:30 PM'))!.toBeInTheDocument()- })-- it('should format string value correctly', () => {- render(<TimePicker {...baseProps} value="09:15" timezone="UTC" />)-- expect(screen.getByDisplayValue('09:15 AM'))!.toBeInTheDocument()- })-- it('should return empty display value for an unparsable truthy string', () => {- const invalidValue = 123 as unknown as TimePickerProps['value']- render(<TimePicker {...baseProps} value={invalidValue} timezone="UTC" />)-- expect(screen.getByRole('textbox'))!.toHaveValue('')- })- })-- describe('Timezone Label Integration', () => {- it('should not display timezone label by default', () => {- render(<TimePicker {...baseProps} value="12:00 AM" timezone="Asia/Shanghai" />)-- expect(screen.queryByTitle(/Timezone: Asia\/Shanghai/)).not.toBeInTheDocument()- })-- it('should not display timezone label when showTimezone is false', () => {- render(- <TimePicker- {...baseProps}- value="12:00 AM"- timezone="Asia/Shanghai"- showTimezone={false}- />,- )-- expect(screen.queryByTitle(/Timezone: Asia\/Shanghai/)).not.toBeInTheDocument()- })-- it('should display timezone label when showTimezone is true', () => {- render(- <TimePicker {...baseProps} value="12:00 AM" timezone="Asia/Shanghai" showTimezone={true} />,- )-- const timezoneLabel = screen.getByTitle(/Timezone: Asia\/Shanghai/)- expect(timezoneLabel)!.toBeInTheDocument()- expect(timezoneLabel.textContent).toMatch(/UTC[+-]\d+/)- })-- it('should not display timezone label when showTimezone is true but timezone is not provided', () => {- render(<TimePicker {...baseProps} value="12:00 AM" showTimezone={true} />)-- expect(screen.queryByTitle(/Timezone:/)).not.toBeInTheDocument()- })- })-})diff --git a/web/app/components/base/date-and-time-picker/time-picker/__tests__/options.spec.tsx b/web/app/components/base/date-and-time-picker/time-picker/__tests__/options.spec.tsxdeleted file mode 100644index 7127a8a0eaf..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/__tests__/options.spec.tsx+++ /dev/null@@ -1,97 +0,0 @@-import type { TimeOptionsProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import dayjs from '../../utils/dayjs'-import Options from '../options'--beforeAll(() => {- Element.prototype.scrollIntoView = vi.fn()-})--const createOptionsProps = (overrides: Partial<TimeOptionsProps> = {}): TimeOptionsProps => ({- selectedTime: undefined,- handleSelectHour: vi.fn(),- handleSelectMinute: vi.fn(),- handleSelectPeriod: vi.fn(),- ...overrides,-})--describe('TimePickerOptions', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- describe('Rendering', () => {- it('should render hour options', () => {- const props = createOptionsProps()-- render(<Options {...props} />)-- const allItems = screen.getAllByRole('listitem')- expect(allItems.length).toBeGreaterThan(12)- })-- it('should render all hour, minute, and period options by default', () => {- const props = createOptionsProps()- render(<Options {...props} />)- const allItems = screen.getAllByRole('listitem')- // 12 hours + 60 minutes + 2 periods- expect(allItems).toHaveLength(74)- })-- it('should render AM and PM period options', () => {- const props = createOptionsProps()-- render(<Options {...props} />)-- expect(screen.getByText('AM'))!.toBeInTheDocument()- expect(screen.getByText('PM'))!.toBeInTheDocument()- })- })-- describe('Minute Filter', () => {- it('should apply minuteFilter when provided', () => {- const minuteFilter = (minutes: string[]) => minutes.filter((m) => Number(m) % 15 === 0)- const props = createOptionsProps({ minuteFilter })-- render(<Options {...props} />)-- const allItems = screen.getAllByRole('listitem')- expect(allItems).toHaveLength(18)- })- })-- describe('Interactions', () => {- it('should render selected hour in the list', () => {- const props = createOptionsProps({ selectedTime: dayjs('2024-01-01 05:30:00') })- render(<Options {...props} />)- const selectedHour = screen.getAllByRole('button').find((item) => item.textContent === '05')- expect(selectedHour)!.toHaveClass('bg-components-button-ghost-bg-hover')- })- it('should render selected minute in the list', () => {- const props = createOptionsProps({ selectedTime: dayjs('2024-01-01 05:30:00') })- render(<Options {...props} />)- const selectedMinute = screen.getAllByRole('button').find((item) => item.textContent === '30')- expect(selectedMinute)!.toHaveClass('bg-components-button-ghost-bg-hover')- })-- it('should call handleSelectPeriod when AM is clicked', () => {- const handleSelectPeriod = vi.fn()- const props = createOptionsProps({ handleSelectPeriod })-- render(<Options {...props} />)- fireEvent.click(screen.getAllByText('AM')[0]!)-- expect(handleSelectPeriod).toHaveBeenCalledWith('AM')- })-- it('should call handleSelectPeriod when PM is clicked', () => {- const handleSelectPeriod = vi.fn()- const props = createOptionsProps({ handleSelectPeriod })-- render(<Options {...props} />)- fireEvent.click(screen.getAllByText('PM')[0]!)-- expect(handleSelectPeriod).toHaveBeenCalledWith('PM')- })- })-})diff --git a/web/app/components/base/date-and-time-picker/time-picker/footer.tsx b/web/app/components/base/date-and-time-picker/time-picker/footer.tsxdeleted file mode 100644index 4637371ea06..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/footer.tsx+++ /dev/null@@ -1,34 +0,0 @@-import type { FC } from 'react'-import type { TimePickerFooterProps } from '../types'-import { Button } from '@langgenius/dify-ui/button'-import * as React from 'react'-import { useTranslation } from 'react-i18next'--const Footer: FC<TimePickerFooterProps> = ({ handleSelectCurrentTime, handleConfirm }) => {- const { t } = useTranslation(['time'])-- return (- <div className="flex items-center justify-between border-t-[0.5px] border-divider-regular p-2">- {/* Now Button */}- <Button- variant="secondary-accent"- size="small"- className="mr-1 flex-1"- onClick={handleSelectCurrentTime}- >- {t(($) => $['operation.now'], { ns: 'time' })}- </Button>- {/* Confirm Button */}- <Button- variant="primary"- size="small"- className="ml-1 flex-1"- onClick={handleConfirm.bind(null)}- >- {t(($) => $['operation.ok'], { ns: 'time' })}- </Button>- </div>- )-}--export default React.memo(Footer)diff --git a/web/app/components/base/date-and-time-picker/time-picker/header.tsx b/web/app/components/base/date-and-time-picker/time-picker/header.tsxdeleted file mode 100644index 0204ff293da..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/header.tsx+++ /dev/null@@ -1,19 +0,0 @@-import * as React from 'react'-import { useTranslation } from 'react-i18next'--type Props = Readonly<{- title?: string-}>-const Header = ({ title }: Props) => {- const { t } = useTranslation(['time'])-- return (- <div className="flex flex-col border-b-[0.5px] border-divider-regular">- <div className="flex items-center px-2 py-1.5 system-md-semibold text-text-primary">- {title || t(($) => $['title.pickTime'], { ns: 'time' })}- </div>- </div>- )-}--export default React.memo(Header)diff --git a/web/app/components/base/date-and-time-picker/time-picker/index.tsx b/web/app/components/base/date-and-time-picker/time-picker/index.tsxdeleted file mode 100644index 551e9f112ab..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/index.tsx+++ /dev/null@@ -1,304 +0,0 @@-import type { Dayjs } from 'dayjs'-import type { TimePickerProps } from '../types'-import { cn } from '@langgenius/dify-ui/cn'-import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import * as React from 'react'-import { useCallback, useEffect, useRef, useState } from 'react'-import { useTranslation } from 'react-i18next'-import TimezoneLabel from '@/app/components/base/timezone-label'-import { Period } from '../types'-import dayjs, { getDateWithTimezone, getHourIn12Hour, isDayjsObject, toDayjs } from '../utils/dayjs'-import Footer from './footer'-import Header from './header'-import Options from './options'--const to24Hour = (hour12: string, period: Period) => {- const normalized = Number.parseInt(hour12, 10) % 12- return period === Period.PM ? normalized + 12 : normalized-}--const TimePicker = ({- id,- value,- timezone,- placeholder,- onChange,- onClear,- renderTrigger,- triggerNativeButton = false,- title,- minuteFilter,- notClearable = false,- triggerFullWidth = false,- showTimezone = false,-}: TimePickerProps) => {- const { t } = useTranslation(['common', 'time'])- const [isOpen, setIsOpen] = useState(false)- const isInitialRef = useRef(true)-- // Initialize selectedTime- const [selectedTime, setSelectedTime] = useState(() => {- return toDayjs(value, { timezone })- })-- // Track previous values to avoid unnecessary updates- const prevValueRef = useRef(value)- const prevTimezoneRef = useRef(timezone)-- useEffect(() => {- if (isInitialRef.current) {- isInitialRef.current = false- // Save initial values on first render- prevValueRef.current = value- prevTimezoneRef.current = timezone- return- }-- // Only update when timezone changes but value doesn't- const valueChanged = prevValueRef.current !== value- const timezoneChanged = prevTimezoneRef.current !== timezone-- // Update reference values- prevValueRef.current = value- prevTimezoneRef.current = timezone-- // Skip if neither timezone changed nor value changed- if (!timezoneChanged && !valueChanged) return-- if (value !== undefined && value !== null) {- const dayjsValue = toDayjs(value, { timezone })- if (!dayjsValue) return-- // oxlint-disable-next-line eslint-react/set-state-in-effect -- value/timezone changes intentionally resync the internal selected time.- setSelectedTime(dayjsValue)-- if (timezoneChanged && !valueChanged) onChange(dayjsValue)- return- }-- // oxlint-disable-next-line eslint-react/set-state-in-effect -- value/timezone changes intentionally resync the internal selected time.- setSelectedTime((prev) => {- if (!isDayjsObject(prev)) return undefined- return timezone ? getDateWithTimezone({ date: prev, timezone }) : prev- })- }, [timezone, value, onChange])-- const syncSelectedTimeFromValue = useCallback(() => {- if (!value) return-- const dayjsValue = toDayjs(value, { timezone })- const needsUpdate =- dayjsValue &&- (!selectedTime || !isDayjsObject(selectedTime) || !dayjsValue.isSame(selectedTime, 'minute'))- if (needsUpdate) setSelectedTime(dayjsValue)- }, [selectedTime, timezone, value])-- const handleOpenChange = useCallback(- (nextOpen: boolean) => {- setIsOpen(nextOpen)- if (nextOpen) syncSelectedTimeFromValue()- },- [syncSelectedTimeFromValue],- )-- const handleClickTrigger = (e: React.MouseEvent) => {- e.preventDefault()- e.stopPropagation()- handleOpenChange(!isOpen)- }-- const handleClear = (e: React.MouseEvent) => {- e.stopPropagation()- setSelectedTime(undefined)- if (!isOpen) onClear()- }-- const handleTimeSelect = useCallback(- (hour: string, minute: string, period: Period) => {- const periodAdjustedHour = to24Hour(hour, period)- const nextMinute = Number.parseInt(minute, 10)- setSelectedTime((prev) => {- const reference = isDayjsObject(prev)- ? prev- : (timezone ? getDateWithTimezone({ timezone }) : dayjs()).startOf('minute')- return reference- .set('hour', periodAdjustedHour)- .set('minute', nextMinute)- .set('second', 0)- .set('millisecond', 0)- })- },- [timezone],- )-- const getSafeTimeObject = useCallback(() => {- if (isDayjsObject(selectedTime)) return selectedTime- return (timezone ? getDateWithTimezone({ timezone }) : dayjs()).startOf('day')- }, [selectedTime, timezone])-- const handleSelectHour = useCallback(- (hour: string) => {- const time = getSafeTimeObject()- handleTimeSelect(hour, time.minute().toString().padStart(2, '0'), time.format('A') as Period)- },- [getSafeTimeObject, handleTimeSelect],- )-- const handleSelectMinute = useCallback(- (minute: string) => {- const time = getSafeTimeObject()- handleTimeSelect(- getHourIn12Hour(time).toString().padStart(2, '0'),- minute,- time.format('A') as Period,- )- },- [getSafeTimeObject, handleTimeSelect],- )-- const handleSelectPeriod = useCallback(- (period: Period) => {- const time = getSafeTimeObject()- handleTimeSelect(- getHourIn12Hour(time).toString().padStart(2, '0'),- time.minute().toString().padStart(2, '0'),- period,- )- },- [getSafeTimeObject, handleTimeSelect],- )-- const handleSelectCurrentTime = useCallback(() => {- const newDate = getDateWithTimezone({ timezone })- setSelectedTime(newDate)- onChange(newDate)- setIsOpen(false)- }, [timezone, onChange])-- const handleConfirm = useCallback(() => {- const valueToEmit = isDayjsObject(selectedTime) ? selectedTime : undefined- onChange(valueToEmit)- setIsOpen(false)- }, [selectedTime, onChange])-- const timeFormat = 'hh:mm A'-- const formatTimeValue = useCallback(- (timeValue: string | Dayjs | undefined): string => {- if (!timeValue) return ''-- const dayjsValue = toDayjs(timeValue, { timezone })- return dayjsValue?.format(timeFormat) || ''- },- [timezone],- )-- const displayValue = formatTimeValue(value)- const placeholderText = placeholder || t(($) => $.defaultPlaceholder, { ns: 'time' })- const getDisplayText = (open: boolean) =>- open && isDayjsObject(selectedTime)- ? selectedTime.format(timeFormat)- : displayValue || placeholderText- const renderInput = (open: boolean) => {- const placeholderDate =- open && isDayjsObject(selectedTime) ? selectedTime.format(timeFormat) : placeholderText-- return (- <input- id={id}- className="flex-1 cursor-pointer appearance-none truncate bg-transparent p-1 system-xs-regular text-components-input-text-filled outline-hidden select-none placeholder:text-components-input-text-placeholder"- readOnly- value={open ? '' : displayValue}- placeholder={placeholderDate}- />- )- }- return (- <Popover open={isOpen} onOpenChange={handleOpenChange}>- <PopoverTrigger- nativeButton={triggerNativeButton}- className={triggerFullWidth ? 'flex! w-full' : undefined}- render={(props, state) => {- const inputElem = renderInput(state.open)- if (renderTrigger)- return renderTrigger(props, state, {- inputElem,- displayText: getDisplayText(state.open),- onClick: handleClickTrigger,- })-- return (- <div- {...props}- className={cn(- 'group flex cursor-pointer items-center gap-x-0.5 rounded-lg bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt',- triggerFullWidth ? 'w-full min-w-0' : 'w-63',- props.className,- )}- onClick={(event) => {- handleClickTrigger(event)- props.onClick?.(event)- }}- data-testid="time-picker-trigger"- >- {inputElem}- {showTimezone && timezone && (- <TimezoneLabel- timezone={timezone}- inline- className="shrink-0 text-xs select-none"- />- )}- <span- className={cn(- 'i-ri-time-line size-4 shrink-0 text-text-quaternary',- state.open ? 'text-text-secondary' : 'group-hover:text-text-secondary',- (displayValue || (state.open && selectedTime)) &&- !notClearable &&- 'group-hover:hidden',- )}- />- <button- type="button"- className={cn(- 'hidden size-4 shrink-0 border-none bg-transparent p-0 text-text-quaternary hover:text-text-secondary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden',- (displayValue || (state.open && selectedTime)) &&- !notClearable &&- 'group-hover:inline-block',- )}- aria-label={t(($) => $['operation.clear'], { ns: 'common' })}- onClick={handleClear}- >- <span className="i-ri-close-circle-fill size-4" aria-hidden="true" />- </button>- </div>- )- }}- />- <PopoverContent- placement="bottom-start"- sideOffset={0}- className="border-none bg-transparent shadow-none"- >- <div className="mt-1 w-63 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg shadow-shadow-shadow-5">- {/* Header */}- <Header title={title} />-- {/* Time Options */}- <Options- selectedTime={selectedTime}- minuteFilter={minuteFilter}- handleSelectHour={handleSelectHour}- handleSelectMinute={handleSelectMinute}- handleSelectPeriod={handleSelectPeriod}- />-- {/* Footer */}- <Footer handleSelectCurrentTime={handleSelectCurrentTime} handleConfirm={handleConfirm} />- </div>- </PopoverContent>- </Popover>- )-}--export default TimePickerdiff --git a/web/app/components/base/date-and-time-picker/time-picker/options.tsx b/web/app/components/base/date-and-time-picker/time-picker/options.tsxdeleted file mode 100644index c89fdb803cc..00000000000--- a/web/app/components/base/date-and-time-picker/time-picker/options.tsx+++ /dev/null@@ -1,69 +0,0 @@-import type { FC } from 'react'-import type { TimeOptionsProps } from '../types'-import * as React from 'react'-import OptionList from '../common/option-list'-import OptionListItem from '../common/option-list-item'-import { useTimeOptions } from '../hooks'--const Options: FC<TimeOptionsProps> = ({- selectedTime,- minuteFilter,- handleSelectHour,- handleSelectMinute,- handleSelectPeriod,-}) => {- const { hourOptions, minuteOptions, periodOptions } = useTimeOptions()-- return (- <div className="grid grid-cols-3 gap-x-1 p-2">- {/* Hour */}- <OptionList>- {hourOptions.map((hour) => {- const isSelected = selectedTime?.format('hh') === hour- return (- <OptionListItem- key={hour}- isSelected={isSelected}- onClick={handleSelectHour.bind(null, hour)}- >- {hour}- </OptionListItem>- )- })}- </OptionList>- {/* Minute */}- <OptionList>- {(minuteFilter ? minuteFilter(minuteOptions) : minuteOptions).map((minute) => {- const isSelected = selectedTime?.format('mm') === minute- return (- <OptionListItem- key={minute}- isSelected={isSelected}- onClick={handleSelectMinute.bind(null, minute)}- >- {minute}- </OptionListItem>- )- })}- </OptionList>- {/* Period */}- <OptionList>- {periodOptions.map((period) => {- const isSelected = selectedTime?.format('A') === period- return (- <OptionListItem- key={period}- isSelected={isSelected}- onClick={handleSelectPeriod.bind(null, period)}- noAutoScroll // if choose PM which would hide(scrolled) AM that may make user confused that there's no am.- >- {period}- </OptionListItem>- )- })}- </OptionList>- </div>- )-}--export default React.memo(Options)diff --git a/web/app/components/base/date-and-time-picker/types.ts b/web/app/components/base/date-and-time-picker/types.tsdeleted file mode 100644index 6cdef9656d1..00000000000--- a/web/app/components/base/date-and-time-picker/types.ts+++ /dev/null@@ -1,138 +0,0 @@-import type { PopoverTriggerProps } from '@langgenius/dify-ui/popover'-import type { Dayjs } from 'dayjs'--export const ViewType = {- date: 'date',- yearMonth: 'yearMonth',- time: 'time',-} as const--export type ViewType = (typeof ViewType)[keyof typeof ViewType]--export const Period = {- AM: 'AM',- PM: 'PM',-} as const--export type Period = (typeof Period)[keyof typeof Period]--type PopoverTriggerRender = Exclude<NonNullable<PopoverTriggerProps['render']>, React.ReactElement>-type TriggerRenderProps = Parameters<PopoverTriggerRender>[0]-type TriggerState = Parameters<PopoverTriggerRender>[1]--export type TriggerProps = {- value: Dayjs | undefined- selectedDate: Dayjs | undefined- handleClear: (e: React.MouseEvent) => void-}--export type DatePickerProps = {- value: Dayjs | undefined- timezone?: string- placeholder?: string- disabled?: boolean- needTimePicker?: boolean- onChange: (date: Dayjs | undefined) => void- onClear: () => void- triggerWrapClassName?: string- renderTrigger?: (- props: TriggerRenderProps,- state: TriggerState,- params: TriggerProps,- ) => React.ReactElement- minuteFilter?: (minutes: string[]) => string[]- noConfirm?: boolean- getIsDateDisabled?: (date: Dayjs) => boolean-}--export type DatePickerHeaderProps = {- handleOpenYearMonthPicker: () => void- currentDate: Dayjs- onClickNextMonth: () => void- onClickPrevMonth: () => void-}--export type DatePickerFooterProps = {- needTimePicker: boolean- displayTime: string- view: ViewType- handleClickTimePicker: () => void- handleSelectCurrentDate: () => void- handleConfirmDate: () => void-}--export type TriggerParams = {- inputElem: React.ReactNode- displayText: string- onClick: (e: React.MouseEvent) => void-}-export type TimePickerProps = {- id?: string- value: Dayjs | string | undefined- timezone?: string- placeholder?: string- onChange: (date: Dayjs | undefined) => void- onClear: () => void- renderTrigger?: (- props: TriggerRenderProps,- state: TriggerState,- params: TriggerParams,- ) => React.ReactElement- triggerNativeButton?: boolean- title?: string- minuteFilter?: (minutes: string[]) => string[]- notClearable?: boolean- triggerFullWidth?: boolean- showTimezone?: boolean-}--export type TimePickerFooterProps = {- handleSelectCurrentTime: () => void- handleConfirm: () => void-}--export type Day = {- date: Dayjs- isCurrentMonth: boolean-}--export type CalendarProps = {- days: Day[]- selectedDate: Dayjs | undefined- onDateClick: (date: Dayjs) => void- wrapperClassName?: string- getIsDateDisabled?: (date: Dayjs) => boolean-}--export type CalendarItemProps = {- day: Day- selectedDate: Dayjs | undefined- onClick: (date: Dayjs) => void- isDisabled: boolean-}--export type TimeOptionsProps = {- selectedTime: Dayjs | undefined- minuteFilter?: (minutes: string[]) => string[]- handleSelectHour: (hour: string) => void- handleSelectMinute: (minute: string) => void- handleSelectPeriod: (period: Period) => void-}--export type YearAndMonthPickerHeaderProps = {- selectedYear: number- selectedMonth: number- onClick: () => void-}--export type YearAndMonthPickerOptionsProps = {- selectedYear: number- selectedMonth: number- handleYearSelect: (year: number) => void- handleMonthSelect: (month: number) => void-}--export type YearAndMonthPickerFooterProps = {- handleYearMonthCancel: () => void- handleYearMonthConfirm: () => void-}diff --git a/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs-extended.spec.ts b/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs-extended.spec.tsdeleted file mode 100644index 230c246cdb8..00000000000--- a/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs-extended.spec.ts+++ /dev/null@@ -1,325 +0,0 @@-import dayjs, {- clearMonthMapCache,- cloneTime,- formatDateForOutput,- getDateWithTimezone,- getDaysInMonth,- getHourIn12Hour,- toDayjs,-} from '../dayjs'--describe('dayjs extended utilities', () => {- // Tests for cloneTime- describe('cloneTime', () => {- it('should copy hour and minute from source to target', () => {- const target = dayjs('2024-01-15')- const source = dayjs('2024-06-20 14:30')-- const result = cloneTime(target, source)-- expect(result.hour()).toBe(14)- expect(result.minute()).toBe(30)- expect(result.date()).toBe(15)- expect(result.month()).toBe(0) // January- })-- it('should not mutate the original target date', () => {- const target = dayjs('2024-01-15 08:00')- const source = dayjs('2024-06-20 14:30')-- cloneTime(target, source)-- expect(target.hour()).toBe(8)- expect(target.minute()).toBe(0)- })- })-- // Tests for getDaysInMonth- describe('getDaysInMonth', () => {- beforeEach(() => {- clearMonthMapCache()- })-- it('should return an array of Day objects', () => {- const date = dayjs('2024-06-15')- const days = getDaysInMonth(date)-- expect(days.length).toBeGreaterThan(0)- days.forEach((day) => {- expect(day).toHaveProperty('date')- expect(day).toHaveProperty('isCurrentMonth')- })- })-- it('should include days from previous and next month to fill the grid', () => {- const date = dayjs('2024-06-15') // June 2024 starts on Saturday- const days = getDaysInMonth(date)-- const prevMonthDays = days.filter((d) => !d.isCurrentMonth && d.date.month() < date.month())- const nextMonthDays = days.filter((d) => !d.isCurrentMonth && d.date.month() > date.month())-- // June 2024 starts on Saturday (6), so there are 6 days from previous month- expect(prevMonthDays.length).toBeGreaterThan(0)- expect(nextMonthDays.length).toBeGreaterThan(0)- })-- it('should mark current month days correctly', () => {- const date = dayjs('2024-06-15')- const days = getDaysInMonth(date)-- const currentMonthDays = days.filter((d) => d.isCurrentMonth)- // June has 30 days- expect(currentMonthDays).toHaveLength(30)- })-- it('should cache results for the same month', () => {- const date1 = dayjs('2024-06-15')- const date2 = dayjs('2024-06-20')-- const days1 = getDaysInMonth(date1)- const days2 = getDaysInMonth(date2)-- // Same reference since it's cached- expect(days1).toBe(days2)- })-- it('should return different results for different months', () => {- const june = dayjs('2024-06-15')- const july = dayjs('2024-07-15')-- const juneDays = getDaysInMonth(june)- const julyDays = getDaysInMonth(july)-- expect(juneDays).not.toBe(julyDays)- })- })-- // Tests for clearMonthMapCache- describe('clearMonthMapCache', () => {- it('should clear the cache so new days are generated', () => {- const date = dayjs('2024-06-15')-- const days1 = getDaysInMonth(date)- clearMonthMapCache()- const days2 = getDaysInMonth(date)-- // After clearing cache, a new array should be created- expect(days1).not.toBe(days2)- // But should have the same length- expect(days1.length).toBe(days2.length)- })- })-- // Tests for getHourIn12Hour- describe('getHourIn12Hour', () => {- it('should return 12 for midnight (hour 0)', () => {- const date = dayjs('2024-01-01 00:00')- expect(getHourIn12Hour(date)).toBe(12)- })-- it('should return hour as-is for 1-11 AM', () => {- expect(getHourIn12Hour(dayjs('2024-01-01 01:00'))).toBe(1)- expect(getHourIn12Hour(dayjs('2024-01-01 11:00'))).toBe(11)- })-- it('should return 0 for noon (hour 12)', () => {- const date = dayjs('2024-01-01 12:00')- expect(getHourIn12Hour(date)).toBe(0)- })-- it('should return hour - 12 for PM hours (13-23)', () => {- expect(getHourIn12Hour(dayjs('2024-01-01 13:00'))).toBe(1)- expect(getHourIn12Hour(dayjs('2024-01-01 23:00'))).toBe(11)- })- })-- // Tests for getDateWithTimezone- describe('getDateWithTimezone', () => {- it('should return a cloned date when no timezone is provided', () => {- const date = dayjs('2024-06-15')- const result = getDateWithTimezone({ date })-- expect(result.format('YYYY-MM-DD')).toBe('2024-06-15')- })-- it('should return current date clone when neither date nor timezone is provided', () => {- const result = getDateWithTimezone({})- const now = dayjs()-- expect(result.format('YYYY-MM-DD')).toBe(now.format('YYYY-MM-DD'))- })-- it('should apply timezone to provided date', () => {- const date = dayjs('2024-06-15T12:00:00')- const result = getDateWithTimezone({ date, timezone: 'America/New_York' })-- // dayjs.tz converts the date to the given timezone- expect(result).toBeDefined()- expect(result.isValid()).toBe(true)- })-- it('should return current time in timezone when only timezone is provided', () => {- const result = getDateWithTimezone({ timezone: 'Asia/Tokyo' })-- expect(result.utcOffset()).toBe(dayjs().tz('Asia/Tokyo').utcOffset())- })- })-- // Tests for toDayjs additional edge cases- describe('toDayjs edge cases', () => {- it('should return undefined for empty string', () => {- expect(toDayjs('')).toBeUndefined()- })-- it('should return undefined for undefined', () => {- expect(toDayjs(undefined)).toBeUndefined()- })-- it('should handle Dayjs object input', () => {- const date = dayjs('2024-06-15')- const result = toDayjs(date)-- expect(result).toBeDefined()- expect(result?.format('YYYY-MM-DD')).toBe('2024-06-15')- })-- it('should handle Dayjs object with timezone', () => {- const date = dayjs('2024-06-15T12:00:00')- const result = toDayjs(date, { timezone: 'UTC' })-- expect(result).toBeDefined()- })-- it('should parse with custom format when format matches common formats', () => {- // Uses a format from COMMON_PARSE_FORMATS- const result = toDayjs('2024-06-15', { format: 'YYYY-MM-DD' })-- expect(result).toBeDefined()- expect(result?.format('YYYY-MM-DD')).toBe('2024-06-15')- })-- it('should fall back when custom format does not match', () => {- // dayjs strict mode with format requires customParseFormat plugin- // which is not loaded, so invalid format falls through to other parsing- const result = toDayjs('2024-06-15', { format: 'INVALID', timezone: 'UTC' })-- // It will still be parsed by fallback mechanisms- expect(result).toBeDefined()- })-- it('should parse time with seconds', () => {- const result = toDayjs('14:30:45', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.hour()).toBe(14)- expect(result?.minute()).toBe(30)- expect(result?.second()).toBe(45)- })-- it('should parse time with milliseconds', () => {- const result = toDayjs('14:30:45.123', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.millisecond()).toBe(123)- })-- it('should normalize short milliseconds by padding', () => {- const result = toDayjs('14:30:45.1', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.millisecond()).toBe(100)- })-- it('should truncate long milliseconds to 3 digits', () => {- // The time regex only captures up to 3 digits for ms, so 4+ digit values- // don't match the regex and fall through to common format parsing- const result = toDayjs('14:30:45.12', { timezone: 'UTC' })-- expect(result).toBeDefined()- // 2-digit ms "12" gets padded to "120"- expect(result?.millisecond()).toBe(120)- })-- it('should parse 12-hour AM time', () => {- const result = toDayjs('07:15 AM', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.hour()).toBe(7)- expect(result?.minute()).toBe(15)- })-- it('should parse 12-hour time with seconds', () => {- const result = toDayjs('07:15:30 PM', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.hour()).toBe(19)- expect(result?.second()).toBe(30)- })-- it('should handle 12 PM correctly', () => {- const result = toDayjs('12:00 PM', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.hour()).toBe(12)- })-- it('should handle 12 AM correctly', () => {- const result = toDayjs('12:00 AM', { timezone: 'UTC' })-- expect(result).toBeDefined()- expect(result?.hour()).toBe(0)- })-- it('should use custom formats array when provided', () => {- const result = toDayjs('2024.06.15', { formats: ['YYYY.MM.DD'] })-- expect(result).toBeDefined()- expect(result?.format('YYYY-MM-DD')).toBe('2024-06-15')- })-- it('should fall back to native parsing for ISO strings', () => {- const result = toDayjs('2024-06-15T12:00:00.000Z')-- expect(result).toBeDefined()- })-- it('should return undefined for completely unparseable value', () => {- const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})- const result = toDayjs('not-a-date')-- expect(result).toBeUndefined()- consoleSpy.mockRestore()- })- })-- // Tests for formatDateForOutput- describe('formatDateForOutput', () => {- it('should return empty string for invalid date', () => {- const invalidDate = dayjs('invalid')- expect(formatDateForOutput(invalidDate)).toBe('')- })-- it('should format date-only output without time', () => {- const date = dayjs('2024-06-15T12:00:00')- const result = formatDateForOutput(date)-- expect(result).toBe('2024-06-15')- })-- it('should format with time when includeTime is true', () => {- const date = dayjs('2024-06-15T12:00:00')- const result = formatDateForOutput(date, true)-- expect(result).toContain('2024-06-15')- expect(result).toContain('12:00:00')- })-- it('should default to date-only format', () => {- const date = dayjs('2024-06-15T14:30:00')- const result = formatDateForOutput(date)-- expect(result).toBe('2024-06-15')- expect(result).not.toContain('14:30')- })- })-})diff --git a/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs.spec.ts b/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs.spec.tsdeleted file mode 100644index 02bd91b5243..00000000000--- a/web/app/components/base/date-and-time-picker/utils/__tests__/dayjs.spec.ts+++ /dev/null@@ -1,318 +0,0 @@-import dayjs from 'dayjs'-import timezone from 'dayjs/plugin/timezone'-import utc from 'dayjs/plugin/utc'-import {- clearMonthMapCache,- cloneTime,- convertTimezoneToOffsetStr,- formatDateForOutput,- getDateWithTimezone,- getDaysInMonth,- getHourIn12Hour,- isDayjsObject,- toDayjs,-} from '../dayjs'--dayjs.extend(utc)-dayjs.extend(timezone)--// ── cloneTime ──────────────────────────────────────────────────────────────-describe('cloneTime', () => {- it('copies hour and minute from source to target, preserving target date', () => {- const target = dayjs('2024-03-15')- const source = dayjs('2020-01-01T09:30:00')- const result = cloneTime(target, source)- expect(result.format('YYYY-MM-DD')).toBe('2024-03-15')- expect(result.hour()).toBe(9)- expect(result.minute()).toBe(30)- })-})--// ── getDaysInMonth ─────────────────────────────────────────────────────────-describe('getDaysInMonth', () => {- beforeEach(() => clearMonthMapCache())-- it('returns cells for a typical month view', () => {- const date = dayjs('2024-01-01')- const days = getDaysInMonth(date)- expect(days.length).toBeGreaterThanOrEqual(28)- expect(days.some((d) => d.isCurrentMonth)).toBe(true)- expect(days.some((d) => !d.isCurrentMonth)).toBe(true)- })-- it('returns cached result on second call', () => {- const date = dayjs('2024-02-01')- const first = getDaysInMonth(date)- const second = getDaysInMonth(date)- expect(first).toBe(second) // same reference- })-- it('clears cache properly', () => {- const date = dayjs('2024-03-01')- const first = getDaysInMonth(date)- clearMonthMapCache()- const second = getDaysInMonth(date)- expect(first).not.toBe(second) // different reference after clearing- })-})--// ── getHourIn12Hour ─────────────────────────────────────────────────────────-describe('getHourIn12Hour', () => {- it('returns 12 for midnight (hour=0)', () => {- expect(getHourIn12Hour(dayjs().set('hour', 0))).toBe(12)- })-- it('returns hour-12 for hours >= 12', () => {- expect(getHourIn12Hour(dayjs().set('hour', 12))).toBe(0)- expect(getHourIn12Hour(dayjs().set('hour', 15))).toBe(3)- expect(getHourIn12Hour(dayjs().set('hour', 23))).toBe(11)- })-- it('returns hour as-is for AM hours (1-11)', () => {- expect(getHourIn12Hour(dayjs().set('hour', 1))).toBe(1)- expect(getHourIn12Hour(dayjs().set('hour', 11))).toBe(11)- })-})--// ── getDateWithTimezone ─────────────────────────────────────────────────────-describe('getDateWithTimezone', () => {- it('returns a clone of now when neither date nor timezone given', () => {- const result = getDateWithTimezone({})- expect(dayjs.isDayjs(result)).toBe(true)- })-- it('returns current tz date when only timezone given', () => {- const result = getDateWithTimezone({ timezone: 'UTC' })- expect(dayjs.isDayjs(result)).toBe(true)- expect(result.utcOffset()).toBe(0)- })-- it('returns date in given timezone when both date and timezone given', () => {- const date = dayjs.utc('2024-06-01T12:00:00Z')- const result = getDateWithTimezone({ date, timezone: 'UTC' })- expect(result.hour()).toBe(12)- })-- it('returns clone of given date when no timezone given', () => {- const date = dayjs('2024-01-15T08:30:00')- const result = getDateWithTimezone({ date })- expect(result.isSame(date)).toBe(true)- })-})--// ── isDayjsObject ───────────────────────────────────────────────────────────-describe('isDayjsObject', () => {- it('detects dayjs instances', () => {- expect(isDayjsObject(dayjs())).toBe(true)- expect(isDayjsObject(getDateWithTimezone({ timezone: 'UTC' }))).toBe(true)- expect(isDayjsObject('2024-01-01')).toBe(false)- expect(isDayjsObject({})).toBe(false)- expect(isDayjsObject(null)).toBe(false)- expect(isDayjsObject(undefined)).toBe(false)- })-})--// ── toDayjs ────────────────────────────────────────────────────────────────-describe('toDayjs', () => {- const tz = 'UTC'-- it('returns undefined for undefined value', () => {- expect(toDayjs(undefined)).toBeUndefined()- })-- it('returns undefined for empty string', () => {- expect(toDayjs('')).toBeUndefined()- })-- it('applies timezone to an existing Dayjs object', () => {- const date = dayjs('2024-06-01T12:00:00')- const result = toDayjs(date, { timezone: 'UTC' })- expect(dayjs.isDayjs(result)).toBe(true)- })-- it('returns the Dayjs object as-is when no timezone given', () => {- const date = dayjs('2024-06-01')- const result = toDayjs(date)- expect(dayjs.isDayjs(result)).toBe(true)- })-- it('returns undefined for non-string non-Dayjs value', () => {- // @ts-expect-error testing invalid input- expect(toDayjs(12345)).toBeUndefined()- })-- it('parses 24h time-only strings', () => {- const result = toDayjs('18:45', { timezone: tz })- expect(result?.format('HH:mm')).toBe('18:45')- })-- it('parses time-only strings with seconds', () => {- const result = toDayjs('09:30:45', { timezone: tz })- expect(result?.hour()).toBe(9)- expect(result?.minute()).toBe(30)- expect(result?.second()).toBe(45)- })-- it('parses time-only strings with 3-digit milliseconds', () => {- const result = toDayjs('08:00:00.500', { timezone: tz })- expect(result?.millisecond()).toBe(500)- })-- it('parses time-only strings with 3-digit ms - normalizeMillisecond exact branch', () => {- // normalizeMillisecond: length === 3 → Number('567') = 567- const result = toDayjs('08:00:00.567', { timezone: tz })- expect(result).toBeDefined()- expect(result?.hour()).toBe(8)- expect(result?.second()).toBe(0)- })-- it('parses time-only strings with <3-digit milliseconds (pads)', () => {- const result = toDayjs('08:00:00.5', { timezone: tz })- expect(result?.millisecond()).toBe(500)- })-- it('parses 12-hour time strings (PM)', () => {- const result = toDayjs('07:15 PM', { timezone: 'America/New_York' })- expect(result?.format('HH:mm')).toBe('19:15')- })-- it('parses 12-hour time strings (AM)', () => {- const result = toDayjs('12:00 AM', { timezone: tz })- expect(result?.hour()).toBe(0)- })-- it('parses 12-hour time strings with seconds', () => {- const result = toDayjs('03:30:15 PM', { timezone: tz })- expect(result?.hour()).toBe(15)- expect(result?.second()).toBe(15)- })-- it('parses datetime strings via common formats', () => {- const result = toDayjs('2024-05-01 12:00:00', { timezone: tz })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- })-- it('parses ISO datetime strings', () => {- const result = toDayjs('2024-05-01T14:30:00', { timezone: 'Europe/London' })- expect(result?.hour()).toBe(14)- })-- it('parses dates with an explicit format option', () => {- // Use unambiguous format: YYYY/MM/DD + value 2024/05/01- const result = toDayjs('2024/05/01', { format: 'YYYY/MM/DD', timezone: tz })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- })-- it('falls through to other formats when explicit format fails', () => {- // '2024-05-01' doesn't match 'DD/MM/YYYY' but will match common formats- const result = toDayjs('2024-05-01', { format: 'DD/MM/YYYY', timezone: tz })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- })-- it('falls through to common formats when explicit format fails without timezone', () => {- const result = toDayjs('2024-05-01', { format: 'DD/MM/YYYY' })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- })-- it('returns undefined when explicit format parsing fails and no fallback matches', () => {- const result = toDayjs('not-a-date-value', { format: 'YYYY/MM/DD' })- expect(result).toBeUndefined()- })-- it('uses custom formats array', () => {- const result = toDayjs('2024/05/01', { formats: ['YYYY/MM/DD'] })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- })-- it('returns undefined for completely invalid string', () => {- const result = toDayjs('not-a-valid-date-at-all!!!')- expect(result).toBeUndefined()- })-- it('parses date-only strings without time', () => {- const result = toDayjs('2024-05-01', { timezone: 'America/Los_Angeles' })- expect(result?.format('YYYY-MM-DD')).toBe('2024-05-01')- expect(result?.hour()).toBe(0)- expect(result?.minute()).toBe(0)- })-- it('uses timezone fallback parser for non-standard datetime strings', () => {- const result = toDayjs('May 1, 2024 2:30 PM', { timezone: 'America/New_York' })- expect(result?.isValid()).toBe(true)- expect(result?.year()).toBe(2024)- expect(result?.month()).toBe(4)- expect(result?.date()).toBe(1)- expect(result?.utcOffset()).toBe(dayjs.tz('2024-05-01', 'America/New_York').utcOffset())- })-- it('uses timezone fallback parser when custom formats are empty', () => {- const result = toDayjs('2024-05-01T14:30:00Z', {- timezone: 'America/New_York',- formats: [],- })- expect(result?.isValid()).toBe(true)- expect(result?.utcOffset()).toBe(dayjs.tz('2024-05-01', 'America/New_York').utcOffset())- })-})--// ── formatDateForOutput ────────────────────────────────────────────────────-describe('formatDateForOutput', () => {- it('returns empty string for invalid date', () => {- expect(formatDateForOutput(dayjs('invalid'))).toBe('')- })-- it('returns date-only format by default (includeTime=false)', () => {- const date = dayjs('2024-05-01T12:30:00')- expect(formatDateForOutput(date)).toBe('2024-05-01')- })-- it('returns ISO datetime string when includeTime=true', () => {- const date = dayjs('2024-05-01T12:30:00')- const result = formatDateForOutput(date, true)- expect(result).toMatch(/^2024-05-01T12:30:00/)- })-})--// ── convertTimezoneToOffsetStr ─────────────────────────────────────────────-describe('convertTimezoneToOffsetStr', () => {- it('returns default UTC+0 for undefined timezone', () => {- expect(convertTimezoneToOffsetStr(undefined)).toBe('UTC+0')- })-- it('returns default UTC+0 for invalid timezone', () => {- expect(convertTimezoneToOffsetStr('Invalid/Timezone')).toBe('UTC+0')- })-- it('handles positive whole-hour offsets', () => {- expect(convertTimezoneToOffsetStr('Asia/Shanghai')).toBe('UTC+8')- expect(convertTimezoneToOffsetStr('Pacific/Auckland')).toBe('UTC+12')- expect(convertTimezoneToOffsetStr('Pacific/Apia')).toBe('UTC+13')- })-- it('handles negative whole-hour offsets', () => {- expect(convertTimezoneToOffsetStr('Pacific/Niue')).toBe('UTC-11')- expect(convertTimezoneToOffsetStr('Pacific/Honolulu')).toBe('UTC-10')- expect(convertTimezoneToOffsetStr('America/New_York')).toBe('UTC-5')- })-- it('handles zero offset', () => {- expect(convertTimezoneToOffsetStr('Europe/London')).toBe('UTC+0')- expect(convertTimezoneToOffsetStr('UTC')).toBe('UTC+0')- })-- it('handles half-hour offsets', () => {- expect(convertTimezoneToOffsetStr('Asia/Kolkata')).toBe('UTC+5:30')- expect(convertTimezoneToOffsetStr('Australia/Adelaide')).toBe('UTC+9:30')- expect(convertTimezoneToOffsetStr('Australia/Darwin')).toBe('UTC+9:30')- })-- it('handles 45-minute offsets', () => {- expect(convertTimezoneToOffsetStr('Pacific/Chatham')).toBe('UTC+12:45')- })-- it('preserves leading zeros in minute part', () => {- const result = convertTimezoneToOffsetStr('Asia/Kolkata')- expect(result).toMatch(/UTC[+-]\d+:30/)- expect(result).not.toMatch(/UTC[+-]\d+:3[^0]/)- })-})diff --git a/web/app/components/base/date-and-time-picker/utils/dayjs.ts b/web/app/components/base/date-and-time-picker/utils/dayjs.tsdeleted file mode 100644index 16df8289da6..00000000000--- a/web/app/components/base/date-and-time-picker/utils/dayjs.ts+++ /dev/null@@ -1,223 +0,0 @@-import type { Dayjs } from 'dayjs'-import type { Day } from '../types'-import dayjs from 'dayjs'-import timezone from 'dayjs/plugin/timezone'-import utc from 'dayjs/plugin/utc'-import { IS_PROD } from '@/config'-import tz from '@/utils/timezone.json'--dayjs.extend(utc)-dayjs.extend(timezone)--export default dayjs--const monthMaps: Record<string, Day[]> = {}-const DEFAULT_OFFSET_STR = 'UTC+0'-const TIME_ONLY_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/-const TIME_ONLY_12H_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2}))?\s?(AM|PM)$/i--const COMMON_PARSE_FORMATS = [- 'YYYY-MM-DD',- 'YYYY/MM/DD',- 'DD-MM-YYYY',- 'DD/MM/YYYY',- 'MM-DD-YYYY',- 'MM/DD/YYYY',- 'YYYY-MM-DDTHH:mm:ss.SSSZ',- 'YYYY-MM-DDTHH:mm:ssZ',- 'YYYY-MM-DD HH:mm:ss',- 'YYYY-MM-DDTHH:mm',- 'YYYY-MM-DDTHH:mmZ',- 'YYYY-MM-DDTHH:mm:ss',- 'YYYY-MM-DDTHH:mm:ss.SSS',-]--export const cloneTime = (targetDate: Dayjs, sourceDate: Dayjs) => {- return targetDate.clone().set('hour', sourceDate.hour()).set('minute', sourceDate.minute())-}--export const getDaysInMonth = (currentDate: Dayjs) => {- const key = currentDate.format('YYYY-MM')- // return the cached days- if (monthMaps[key]) return monthMaps[key]-- const daysInCurrentMonth = currentDate.daysInMonth()- const firstDay = currentDate.startOf('month').day()- const lastDay = currentDate.endOf('month').day()- const lastDayInLastMonth = currentDate.clone().subtract(1, 'month').endOf('month')- const firstDayInNextMonth = currentDate.clone().add(1, 'month').startOf('month')- const days: Day[] = []- const daysInOneWeek = 7- const totalLines = 6-- // Add cells for days before the first day of the month- for (let i = firstDay - 1; i >= 0; i--) {- const date = cloneTime(lastDayInLastMonth.subtract(i, 'day'), currentDate)- days.push({- date,- isCurrentMonth: false,- })- }-- // Add days of the month- for (let i = 1; i <= daysInCurrentMonth; i++) {- const date = cloneTime(currentDate.startOf('month').add(i - 1, 'day'), currentDate)- days.push({- date,- isCurrentMonth: true,- })- }-- // Add cells for days after the last day of the month- const totalLinesOfCurrentMonth =- Math.ceil((daysInCurrentMonth - (daysInOneWeek - firstDay + lastDay + 1)) / 7) + 2- const needAdditionalLine = totalLinesOfCurrentMonth < totalLines- for (- let i = 0;- lastDay + i < (needAdditionalLine ? 2 * daysInOneWeek - 1 : daysInOneWeek - 1);- i++- ) {- const date = cloneTime(firstDayInNextMonth.add(i, 'day'), currentDate)- days.push({- date,- isCurrentMonth: false,- })- }-- // cache the days- monthMaps[key] = days- return days-}--export const clearMonthMapCache = () => {- for (const key in monthMaps) delete monthMaps[key]-}--export const getHourIn12Hour = (date: Dayjs) => {- const hour = date.hour()- return hour === 0 ? 12 : hour >= 12 ? hour - 12 : hour-}--export const getDateWithTimezone = ({ date, timezone }: { date?: Dayjs; timezone?: string }) => {- if (!timezone) return (date ?? dayjs()).clone()- return date ? dayjs.tz(date, timezone) : dayjs().tz(timezone)-}--export const convertTimezoneToOffsetStr = (timezone?: string) => {- if (!timezone) return DEFAULT_OFFSET_STR- const tzItem = tz.find((item) => item.value === timezone)- if (!tzItem) return DEFAULT_OFFSET_STR- // Extract offset from name format like "-11:00 Niue Time" or "+05:30 India Time"- // Name format is always "{offset}:{minutes} {timezone name}"- const offsetMatch = /^([+-]?\d{1,2}):(\d{2})/.exec(tzItem.name)- /* v8 ignore next 2 -- timezone.json entries are normalized to "{offset} {name}"; this protects against malformed data only. */- if (!offsetMatch) return DEFAULT_OFFSET_STR- // Parse hours and minutes separately- const hours = Number.parseInt(offsetMatch[1]!, 10)- const minutes = Number.parseInt(offsetMatch[2]!, 10)- const sign = hours >= 0 ? '+' : ''- // If minutes are non-zero, include them in the output (e.g., "UTC+5:30")- // Otherwise, only show hours (e.g., "UTC+8")- return minutes !== 0 ? `UTC${sign}${hours}:${offsetMatch[2]}` : `UTC${sign}${hours}`-}--export const isDayjsObject = (value: unknown): value is Dayjs => dayjs.isDayjs(value)--type ToDayjsOptions = {- timezone?: string- format?: string- formats?: string[]-}--const warnParseFailure = (value: string) => {- if (!IS_PROD) console.warn('[TimePicker] Failed to parse time value', value)-}--const normalizeMillisecond = (value: string | undefined) => {- if (!value) return 0- if (value.length === 3) return Number(value)- /* v8 ignore next 2 -- TIME_ONLY_REGEX allows at most 3 fractional digits, so >3 can only occur after future regex changes. */- if (value.length > 3) return Number(value.slice(0, 3))- return Number(value.padEnd(3, '0'))-}--const applyTimezone = (date: Dayjs, timezone?: string) => {- return timezone ? getDateWithTimezone({ date, timezone }) : date-}--export const toDayjs = (- value: string | Dayjs | undefined,- options: ToDayjsOptions = {},-): Dayjs | undefined => {- if (!value) return undefined-- const { timezone: tzName, format, formats } = options-- if (isDayjsObject(value)) return applyTimezone(value, tzName)-- if (typeof value !== 'string') return undefined-- const trimmed = value.trim()-- if (format) {- const parsedWithFormat = tzName- ? dayjs(trimmed, format, true).tz(tzName, true)- : dayjs(trimmed, format, true)- if (parsedWithFormat.isValid()) return parsedWithFormat- }-- const timeMatch = TIME_ONLY_REGEX.exec(trimmed)- if (timeMatch) {- const base = applyTimezone(dayjs(), tzName).startOf('day')- const rawHour = Number(timeMatch[1])- const minute = Number(timeMatch[2])- const second = timeMatch[3] ? Number(timeMatch[3]) : 0- const millisecond = normalizeMillisecond(timeMatch[4])-- return base- .set('hour', rawHour)- .set('minute', minute)- .set('second', second)- .set('millisecond', millisecond)- }-- const timeMatch12h = TIME_ONLY_12H_REGEX.exec(trimmed)- if (timeMatch12h) {- const base = applyTimezone(dayjs(), tzName).startOf('day')- let hour = Number(timeMatch12h[1]) % 12- const isPM = timeMatch12h[4]?.toUpperCase() === 'PM'- if (isPM) hour += 12- const minute = Number(timeMatch12h[2])- const second = timeMatch12h[3] ? Number(timeMatch12h[3]) : 0-- return base.set('hour', hour).set('minute', minute).set('second', second).set('millisecond', 0)- }-- const candidateFormats = formats ?? COMMON_PARSE_FORMATS- for (const fmt of candidateFormats) {- const parsed = tzName ? dayjs(trimmed, fmt, true).tz(tzName, true) : dayjs(trimmed, fmt, true)- if (parsed.isValid()) return parsed- }-- const fallbackParsed = tzName ? dayjs.tz(trimmed, tzName) : dayjs(trimmed)- if (fallbackParsed.isValid()) return fallbackParsed-- warnParseFailure(value)- return undefined-}-// Format date output with localization support-export const formatDateForOutput = (- date: Dayjs,- includeTime: boolean = false,- _locale: string = 'en-US',-): string => {- if (!date || !date.isValid()) return ''-- if (includeTime) {- // Output format with time- return date.format('YYYY-MM-DDTHH:mm:ss.SSSZ')- } else {- // Date-only output format without timezone- return date.format('YYYY-MM-DD')- }-}diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/footer.spec.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/footer.spec.tsxdeleted file mode 100644index 185c94d769a..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/footer.spec.tsx+++ /dev/null@@ -1,52 +0,0 @@-import type { YearAndMonthPickerFooterProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import Footer from '../footer'--// Factory for Footer props-const createFooterProps = (- overrides: Partial<YearAndMonthPickerFooterProps> = {},-): YearAndMonthPickerFooterProps => ({- handleYearMonthCancel: vi.fn(),- handleYearMonthConfirm: vi.fn(),- ...overrides,-})--describe('YearAndMonthPicker Footer', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should render Cancel and OK buttons', () => {- const props = createFooterProps()- render(<Footer {...props} />)-- expect(screen.getByText(/operation\.cancel/)).toBeInTheDocument()- expect(screen.getByText(/operation\.ok/)).toBeInTheDocument()- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call handleYearMonthCancel when Cancel button is clicked', () => {- const handleYearMonthCancel = vi.fn()- const props = createFooterProps({ handleYearMonthCancel })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.cancel/))-- expect(handleYearMonthCancel).toHaveBeenCalledTimes(1)- })-- it('should call handleYearMonthConfirm when OK button is clicked', () => {- const handleYearMonthConfirm = vi.fn()- const props = createFooterProps({ handleYearMonthConfirm })- render(<Footer {...props} />)-- fireEvent.click(screen.getByText(/operation\.ok/))-- expect(handleYearMonthConfirm).toHaveBeenCalledTimes(1)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/header.spec.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/header.spec.tsxdeleted file mode 100644index 8b2d95b1dcb..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/header.spec.tsx+++ /dev/null@@ -1,49 +0,0 @@-import type { YearAndMonthPickerHeaderProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import Header from '../header'--// Factory for Header props-const createHeaderProps = (- overrides: Partial<YearAndMonthPickerHeaderProps> = {},-): YearAndMonthPickerHeaderProps => ({- selectedYear: 2024,- selectedMonth: 5, // June (0-indexed)- onClick: vi.fn(),- ...overrides,-})--describe('YearAndMonthPicker Header', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Rendering tests- describe('Rendering', () => {- it('should display the selected year', () => {- const props = createHeaderProps({ selectedYear: 2024 })- render(<Header {...props} />)-- expect(screen.getByText(/2024/)).toBeInTheDocument()- })-- it('should render a clickable button', () => {- const props = createHeaderProps()- render(<Header {...props} />)-- expect(screen.getByRole('button')).toBeInTheDocument()- })- })-- // Interaction tests- describe('Interactions', () => {- it('should call onClick when the header button is clicked', () => {- const onClick = vi.fn()- const props = createHeaderProps({ onClick })- render(<Header {...props} />)-- fireEvent.click(screen.getByRole('button'))-- expect(onClick).toHaveBeenCalledTimes(1)- })- })-})diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/options.spec.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/options.spec.tsxdeleted file mode 100644index 5eb1e80fcac..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/__tests__/options.spec.tsx+++ /dev/null@@ -1,83 +0,0 @@-import type { YearAndMonthPickerOptionsProps } from '../../types'-import { fireEvent, render, screen } from '@testing-library/react'-import Options from '../options'--beforeAll(() => {- Element.prototype.scrollIntoView = vi.fn()-})--const createOptionsProps = (- overrides: Partial<YearAndMonthPickerOptionsProps> = {},-): YearAndMonthPickerOptionsProps => ({- selectedMonth: 5,- selectedYear: 2024,- handleMonthSelect: vi.fn(),- handleYearSelect: vi.fn(),- ...overrides,-})--describe('YearAndMonthPicker Options', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- describe('Rendering', () => {- it('should render month options', () => {- const props = createOptionsProps()-- render(<Options {...props} />)-- const monthItems = screen.getAllByText(/months\./)- expect(monthItems).toHaveLength(12)- })-- it('should render year options', () => {- const props = createOptionsProps()-- const { container } = render(<Options {...props} />)-- const yearList = container.querySelectorAll('ul')[1]- expect(yearList?.children).toHaveLength(200)- })- })-- describe('Interactions', () => {- it('should call handleMonthSelect when a month is clicked', () => {- const handleMonthSelect = vi.fn()- const props = createOptionsProps({ handleMonthSelect })- render(<Options {...props} />)- // The mock returns 'time.months.January' for the first month- fireEvent.click(screen.getByText(/months\.January/))- expect(handleMonthSelect).toHaveBeenCalledWith(0)- })-- it('should call handleYearSelect when a year is clicked', () => {- const handleYearSelect = vi.fn()- const props = createOptionsProps({ handleYearSelect })-- render(<Options {...props} />)- fireEvent.click(screen.getByText('2024'))-- expect(handleYearSelect).toHaveBeenCalledWith(2024)- })- })-- describe('Selection', () => {- it('should render selected month in the list', () => {- const props = createOptionsProps({ selectedMonth: 0 })-- render(<Options {...props} />)-- const monthItems = screen.getAllByText(/months\./)- expect(monthItems.length).toBeGreaterThan(0)- })-- it('should render selected year in the list', () => {- const props = createOptionsProps({ selectedYear: 2024 })-- render(<Options {...props} />)-- expect(screen.getByText('2024')).toBeInTheDocument()- })- })-})diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/footer.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/footer.tsxdeleted file mode 100644index 5d20011d5ba..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/footer.tsx+++ /dev/null@@ -1,25 +0,0 @@-import type { FC } from 'react'-import type { YearAndMonthPickerFooterProps } from '../types'-import { Button } from '@langgenius/dify-ui/button'-import * as React from 'react'-import { useTranslation } from 'react-i18next'--const Footer: FC<YearAndMonthPickerFooterProps> = ({- handleYearMonthCancel,- handleYearMonthConfirm,-}) => {- const { t } = useTranslation(['time'])-- return (- <div className="grid grid-cols-2 gap-x-1 p-2">- <Button size="small" onClick={handleYearMonthCancel}>- {t(($) => $['operation.cancel'], { ns: 'time' })}- </Button>- <Button variant="primary" size="small" onClick={handleYearMonthConfirm}>- {t(($) => $['operation.ok'], { ns: 'time' })}- </Button>- </div>- )-}--export default React.memo(Footer)diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/header.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/header.tsxdeleted file mode 100644index e27bf46d90d..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/header.tsx+++ /dev/null@@ -1,25 +0,0 @@-import type { FC } from 'react'-import type { YearAndMonthPickerHeaderProps } from '../types'-import { RiArrowUpSLine } from '@remixicon/react'-import * as React from 'react'-import { useMonths } from '../hooks'--const Header: FC<YearAndMonthPickerHeaderProps> = ({ selectedYear, selectedMonth, onClick }) => {- const months = useMonths()-- return (- <div className="flex border-b-[0.5px] border-divider-regular p-2 pb-1">- {/* Year and Month */}- <button- type="button"- onClick={onClick}- className="flex items-center gap-x-0.5 rounded-lg px-2 py-1.5 system-md-semibold text-text-primary hover:bg-state-base-hover"- >- <span>{`${months[selectedMonth]} ${selectedYear}`}</span>- <RiArrowUpSLine className="size-4 text-text-tertiary" />- </button>- </div>- )-}--export default React.memo(Header)diff --git a/web/app/components/base/date-and-time-picker/year-and-month-picker/options.tsx b/web/app/components/base/date-and-time-picker/year-and-month-picker/options.tsxdeleted file mode 100644index f4efb267364..00000000000--- a/web/app/components/base/date-and-time-picker/year-and-month-picker/options.tsx+++ /dev/null@@ -1,53 +0,0 @@-import type { FC } from 'react'-import type { YearAndMonthPickerOptionsProps } from '../types'-import * as React from 'react'-import OptionList from '../common/option-list'-import OptionListItem from '../common/option-list-item'-import { useMonths, useYearOptions } from '../hooks'--const Options: FC<YearAndMonthPickerOptionsProps> = ({- selectedMonth,- selectedYear,- handleMonthSelect,- handleYearSelect,-}) => {- const months = useMonths()- const yearOptions = useYearOptions()-- return (- <div className="grid grid-cols-2 gap-x-1 p-2">- {/* Month Picker */}- <OptionList>- {months.map((month, index) => {- const isSelected = selectedMonth === index- return (- <OptionListItem- key={month}- isSelected={isSelected}- onClick={handleMonthSelect.bind(null, index)}- >- {month}- </OptionListItem>- )- })}- </OptionList>- {/* Year Picker */}- <OptionList>- {yearOptions.map((year) => {- const isSelected = selectedYear === year- return (- <OptionListItem- key={year}- isSelected={isSelected}- onClick={handleYearSelect.bind(null, year)}- >- {year}- </OptionListItem>- )- })}- </OptionList>- </div>- )-}--export default React.memo(Options)diff --git a/web/app/components/base/date-time-picker/README.md b/web/app/components/base/date-time-picker/README.mdnew file mode 100644index 00000000000..bd5615cccec--- /dev/null+++ b/web/app/components/base/date-time-picker/README.md@@ -0,0 +1,60 @@+# Web date and time pickers++Use the local `date-picker`, `time-picker`, or `date-time-picker` entry in Web. Each exports+the localized Root plus the matching Dify UI Label, Trigger, Value, Clear, Content and prop types.++These roots own application language, calendar-locale mapping, direction, translated actions,+validation messages and default placeholders. They preserve the library props and caller overrides.+They do not own values, time zones, popup state, selection logic or business serialization.+Parts and types are re-exported unchanged; only Root integrates application defaults. Import the+whole composition from its matching Web entry, without a shared barrel for all three pickers.+Do not pass a repeated locale bundle at each call site.++```tsx+import {+ DatePicker,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@/app/components/base/date-time-picker/date-picker'++;<DatePicker value={date} onValueChange={setDate}>+ <DatePickerLabel>{fieldTitle}</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+</DatePicker>+```++Use the picker Label for clickable visible text. Do not point a native label or FieldLabel at+the trigger: that can activate its button and open the popup. Existing external text can supply+`aria-labelledby` on Trigger and Content; its owner is responsible for focus forwarding.+Without a Label, provide an accessible name on each part; Root has no naming props. Keep help actions beside Label.+Clear uses `aria-label` or `aria-labelledby` and may share a visual container with Trigger; do not nest+it inside the trigger button. Values and submission behavior follow the [Dify UI picker contract].++## Business owners++| Owner | Responsibility |+| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| [Monitoring date range] | Two dates with the shared 30-day/past-date restriction and compact presentation; overview and Agent monitoring retain their query state and payload formatting. |+| [Tool date parameters] | Tool field names, unknown-value validation, empty-string clearing and range serialization. Workflow and plugin configuration use the same components. |+| Dataset metadata date field | Profile time zone, Unix seconds, metadata display format and read-only state. |+| Knowledge-retrieval date condition | Profile time zone, Unix seconds, optional-value clearing and disabled state. |+| Auto-update settings | Quarter-hour choices, update configuration conversion and the time-zone settings action. |+| Schedule trigger | Schedule clock-string conversion, configured time zone and workflow read-only state. |+| Markdown form | Declared input types and labels, source-value parsing and form submission. |++Add a business wrapper only for one of these stable domain contracts. Compose the localized root+directly for one-off forms; do not introduce another general picker API with display-mode flags.++Tool date ranges read the parameter contract's object or JSON object string and emit a JSON string+with optional `start`/`end` civil dates; clearing both emits `''`. A bare date is not a date range.+There are no legacy picker imports, forwarding entrypoints or old-prop adapters.++`date-value.ts` validates civil strings at Web input boundaries. Day.js remains in monitoring and+existing business storage/display calculations; it is not passed into Dify UI, whose values are+civil strings, wall-time strings or Date instants. Do not add a second conversion inside the roots.++[Dify UI picker contract]: ../../../../../packages/dify-ui/src/date-time/README.md+[Monitoring date range]: ../../../../features/monitoring/date-range-picker.tsx+[Tool date parameters]: ../../tools/parameters/tool-date-picker.tsxdiff --git a/web/app/components/base/date-time-picker/__tests__/localization.spec.tsx b/web/app/components/base/date-time-picker/__tests__/localization.spec.tsxnew file mode 100644index 00000000000..48ad0df2116--- /dev/null+++ b/web/app/components/base/date-time-picker/__tests__/localization.spec.tsx@@ -0,0 +1,161 @@+import { act, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createInstance } from 'i18next'+import { I18nextProvider } from 'react-i18next'+import {+ DatePicker,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@/app/components/base/date-time-picker/date-picker'+import {+ DateTimePicker,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '@/app/components/base/date-time-picker/date-time-picker'+import {+ TimePicker,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+} from '@/app/components/base/date-time-picker/time-picker'+import en from '@/i18n/locales/en-US/time.json'+import fa from '@/i18n/locales/fa-IR/time.json'+import lo from '@/i18n/locales/lo-LA/time.json'+import zh from '@/i18n/locales/zh-Hans/time.json'++vi.unmock('react-i18next')++async function createI18n(language = 'en-US') {+ const i18n = createInstance()+ await i18n.init({+ lng: language,+ fallbackLng: 'en-US',+ defaultNS: 'time',+ keySeparator: false,+ resources: {+ 'en-US': { time: en },+ 'zh-Hans': { time: zh },+ 'fa-IR': { time: fa },+ 'lo-LA': { time: lo },+ },+ interpolation: { escapeValue: false },+ react: { useSuspense: false },+ })+ return i18n+}++it('localizes empty picker placeholders and preserves a caller override', async () => {+ const i18n = await createI18n('zh-Hans')+ render(+ <I18nextProvider i18n={i18n}>+ <DatePicker>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ </DatePicker>+ <TimePicker>+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ </TimePicker>+ <DateTimePicker timeZone="UTC">+ <DateTimePickerLabel className="sr-only">Meeting</DateTimePickerLabel>+ <DateTimePickerTrigger />+ </DateTimePicker>+ <DatePicker placeholder="Choose billing day">+ <DatePickerLabel className="sr-only">Billing</DatePickerLabel>+ <DatePickerTrigger />+ </DatePicker>+ </I18nextProvider>,+ )+ expect(screen.getByRole('button', { name: 'Date' })).toHaveTextContent(zh['operation.pickDate'])+ expect(screen.getByRole('button', { name: 'Meeting' })).toHaveTextContent(+ zh['operation.pickDate'],+ )+ expect(screen.getByRole('button', { name: 'Time' })).toHaveTextContent(zh['title.pickTime'])+ expect(screen.getByRole('button', { name: 'Billing' })).toHaveTextContent('Choose billing day')+})++it('updates time formatting and popup labels from the application language without locale props', async () => {+ const user = userEvent.setup()+ const i18n = await createI18n()+ render(+ <I18nextProvider i18n={i18n}>+ <TimePicker defaultValue="13:30">+ <TimePickerLabel className="sr-only">Time</TimePickerLabel>+ <TimePickerTrigger />+ <TimePickerContent />+ </TimePicker>+ </I18nextProvider>,+ )+ expect(screen.getByRole('button', { name: 'Time 1:30 PM' })).toBeInTheDocument()+ await act(() => i18n.changeLanguage('zh-Hans'))+ await user.click(screen.getByRole('button', { name: 'Time 下午1:30' }))+ expect(screen.getByRole('listbox', { name: zh['picker.hour'] })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: zh['operation.ok'] })).toBeInTheDocument()+ await act(() => i18n.changeLanguage('fa-IR'))+ expect(screen.getByRole('button', { name: /Time ۱:۳۰/ })).toBeInTheDocument()+ expect(screen.getByRole('listbox', { name: fa['picker.hour'] })).toHaveAttribute(+ 'aria-orientation',+ 'vertical',+ )+ expect(screen.getByRole('option', { name: '۱' })).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByRole('option', { name: '۳۰' })).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByRole('dialog')).toHaveAttribute('dir', 'rtl')+})++it('owns the application calendar locale and RTL while preserving caller label overrides', async () => {+ const user = userEvent.setup()+ const i18n = await createI18n('fa-IR')+ render(+ <I18nextProvider i18n={i18n}>+ <DatePicker defaultValue="2025-01-15" labels={{ nextMonth: 'Next billing month' }}>+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </I18nextProvider>,+ )+ const trigger = screen.getByRole('button', { name: /^Date / })+ expect(trigger).toHaveAttribute('dir', 'rtl')+ await user.click(trigger)+ expect(screen.getByRole('dialog', { name: 'Date' })).toHaveAttribute('dir', 'rtl')+ expect(screen.getByRole('button', { name: 'Next billing month' })).toBeInTheDocument()+ await user.click(+ screen.getByRole('button', { name: new RegExp(fa['picker.chooseMonthAndYear']) }),+ )+ expect(screen.getByRole('option', { name: 'ژانویه' })).toHaveAttribute('aria-selected', 'true')+})++it.each([+ ['zh-Hans', '今天,2026年9月28日 星期一,已选择'],+ [+ 'lo-LA',+ new Intl.DateTimeFormat('lo-LA', { dateStyle: 'full', timeZone: 'UTC' }).format(+ new Date('2026-09-28T12:00:00Z'),+ ),+ ],+])('preserves localized calendar names and today semantics for %s', async (language, dayLabel) => {+ vi.setSystemTime(new Date('2026-09-28T12:00:00Z'))+ try {+ const user = userEvent.setup()+ const i18n = await createI18n(language)+ render(+ <I18nextProvider i18n={i18n}>+ <DatePicker+ defaultValue="2026-09-28"+ locale={{ labels: { labelNav: 'Calendar navigation' } }}+ >+ <DatePickerLabel className="sr-only">Date</DatePickerLabel>+ <DatePickerTrigger />+ <DatePickerContent />+ </DatePicker>+ </I18nextProvider>,+ )+ await user.click(screen.getByRole('button', { name: /^Date / }))+ expect(screen.getByRole('button', { name: dayLabel })).toHaveAttribute('aria-current', 'date')+ expect(screen.getByRole('gridcell', { selected: true })).toBeInTheDocument()+ expect(screen.getByRole('navigation', { name: 'Calendar navigation' })).toBeInTheDocument()+ } finally {+ vi.useRealTimers()+ }+})diff --git a/web/app/components/base/date-time-picker/calendar-locales.ts b/web/app/components/base/date-time-picker/calendar-locales.tsnew file mode 100644index 00000000000..7132087614b--- /dev/null+++ b/web/app/components/base/date-time-picker/calendar-locales.ts@@ -0,0 +1,87 @@+import type { Locale } from '@daypicker/react'+import { arTN } from '@daypicker/react/locale/ar-TN'+import { az } from '@daypicker/react/locale/az'+import { de } from '@daypicker/react/locale/de'+import { enUS } from '@daypicker/react/locale/en-US'+import { es } from '@daypicker/react/locale/es'+import { faIR } from '@daypicker/react/locale/fa-IR'+import { fr } from '@daypicker/react/locale/fr'+import { hi } from '@daypicker/react/locale/hi'+import { id } from '@daypicker/react/locale/id'+import { it } from '@daypicker/react/locale/it'+import { ja } from '@daypicker/react/locale/ja'+import { ko } from '@daypicker/react/locale/ko'+import { nl } from '@daypicker/react/locale/nl'+import { pl } from '@daypicker/react/locale/pl'+import { ptBR } from '@daypicker/react/locale/pt-BR'+import { ro } from '@daypicker/react/locale/ro'+import { ru } from '@daypicker/react/locale/ru'+import { sl } from '@daypicker/react/locale/sl'+import { th } from '@daypicker/react/locale/th'+import { tr } from '@daypicker/react/locale/tr'+import { uk } from '@daypicker/react/locale/uk'+import { vi } from '@daypicker/react/locale/vi'+import { zhCN } from '@daypicker/react/locale/zh-CN'+import { zhTW } from '@daypicker/react/locale/zh-TW'++// DayPicker has no Lao locale. Keep the application fallback here.+const lo: Locale = {+ ...enUS,+ code: 'lo-LA',+ labels: {+ labelDayButton: (date) =>+ new Intl.DateTimeFormat('lo-LA', { dateStyle: 'full', timeZone: 'UTC' }).format(date),+ labelGrid: (date) =>+ new Intl.DateTimeFormat('lo-LA', { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(+ date,+ ),+ labelWeekday: (date) =>+ new Intl.DateTimeFormat('lo-LA', { weekday: 'long', timeZone: 'UTC' }).format(date),+ },+ localize: {+ ...enUS.localize,+ month: (month) =>+ new Intl.DateTimeFormat('lo-LA', { month: 'long', timeZone: 'UTC' }).format(+ new Date(Date.UTC(2025, month, 1)),+ ),+ day: (day) =>+ new Intl.DateTimeFormat('lo-LA', { weekday: 'short', timeZone: 'UTC' }).format(+ new Date(Date.UTC(2025, 0, 5 + day)),+ ),+ },+}++const calendarLocales: Record<string, Locale> = {+ 'en-US': enUS,+ 'zh-Hans': zhCN,+ 'zh-Hant': zhTW,+ 'ja-JP': ja,+ 'ko-KR': ko,+ 'de-DE': de,+ 'fr-FR': fr,+ 'es-ES': es,+ 'it-IT': it,+ 'pt-BR': ptBR,+ 'ru-RU': ru,+ 'uk-UA': uk,+ 'pl-PL': pl,+ 'nl-NL': nl,+ 'tr-TR': tr,+ 'vi-VN': vi,+ 'id-ID': id,+ 'th-TH': th,+ 'hi-IN': hi,+ 'ar-TN': arTN,+ 'fa-IR': faIR,+ 'ro-RO': ro,+ 'sl-SI': sl,+ 'az-AZ': az,+ 'lo-LA': lo,+}++export function getCalendarLocale(language: string, overrides?: Partial<Locale>): Locale {+ const locale = calendarLocales[language] ?? enUS+ return overrides+ ? { ...locale, ...overrides, labels: { ...locale.labels, ...overrides.labels } }+ : locale+}diff --git a/web/app/components/base/date-time-picker/date-picker.tsx b/web/app/components/base/date-time-picker/date-picker.tsxnew file mode 100644index 00000000000..44331454be1--- /dev/null+++ b/web/app/components/base/date-time-picker/date-picker.tsx@@ -0,0 +1,38 @@+'use client'++import type { DatePickerProps } from '@langgenius/dify-ui/date-picker'+import { DatePicker as BaseDatePicker } from '@langgenius/dify-ui/date-picker'+import { getCalendarLocale } from './calendar-locales'+import { usePickerLabels } from './use-picker-labels'++export function DatePicker(props: DatePickerProps) {+ const defaults = usePickerLabels()+ return (+ <BaseDatePicker+ {...defaults}+ {...props}+ placeholder={props.placeholder ?? defaults.labels.backToDate}+ locale={getCalendarLocale(defaults.locale, props.locale)}+ labels={{ ...defaults.labels, ...props.labels }}+ />+ )+}++/* oxlint-disable no-barrel-files/no-barrel-files -- Keep this localized picker and its unchanged parts/types in one component entry. */+export {+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+ DatePickerValue,+} from '@langgenius/dify-ui/date-picker'+/** @public Prop types for the complete localized picker composition. */+export type {+ DatePickerClearProps,+ DatePickerContentProps,+ DatePickerLabelProps,+ DatePickerProps,+ DatePickerTriggerProps,+ DatePickerValueProps,+} from '@langgenius/dify-ui/date-picker'+/* oxlint-enable no-barrel-files/no-barrel-files */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.tsxnew file mode 100644index 00000000000..c02fd2b3c86--- /dev/null+++ b/web/app/components/base/date-time-picker/date-time-picker.tsx@@ -0,0 +1,38 @@+'use client'++import type { DateTimePickerProps } from '@langgenius/dify-ui/date-time-picker'+import { DateTimePicker as BaseDateTimePicker } from '@langgenius/dify-ui/date-time-picker'+import { getCalendarLocale } from './calendar-locales'+import { usePickerLabels } from './use-picker-labels'++export function DateTimePicker(props: DateTimePickerProps) {+ const defaults = usePickerLabels()+ return (+ <BaseDateTimePicker+ {...defaults}+ {...props}+ placeholder={props.placeholder ?? defaults.labels.backToDate}+ locale={getCalendarLocale(defaults.locale, props.locale)}+ labels={{ ...defaults.labels, ...props.labels }}+ />+ )+}++/* oxlint-disable no-barrel-files/no-barrel-files -- Keep this localized picker and its unchanged parts/types in one component entry. */+export {+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+ DateTimePickerValue,+} from '@langgenius/dify-ui/date-time-picker'+/** @public Prop types for the complete localized picker composition. */+export type {+ DateTimePickerClearProps,+ DateTimePickerContentProps,+ DateTimePickerLabelProps,+ DateTimePickerProps,+ DateTimePickerTriggerProps,+ DateTimePickerValueProps,+} from '@langgenius/dify-ui/date-time-picker'+/* oxlint-enable no-barrel-files/no-barrel-files */diff --git a/web/app/components/base/date-time-picker/date-value.ts b/web/app/components/base/date-time-picker/date-value.tsnew file mode 100644index 00000000000..f4c77054e33--- /dev/null+++ b/web/app/components/base/date-time-picker/date-value.ts@@ -0,0 +1,8 @@+import { isValid, parseISO } from 'date-fns'++export function parseDateValue(value: unknown): string | undefined {+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || value.startsWith('0000'))+ return undefined+ // UTC keeps civil-date validation independent of local daylight-saving transitions.+ return isValid(parseISO(`${value}T00:00:00Z`)) ? value : undefined+}diff --git a/web/app/components/base/date-time-picker/time-picker.tsx b/web/app/components/base/date-time-picker/time-picker.tsxnew file mode 100644index 00000000000..b3dc2cc7051--- /dev/null+++ b/web/app/components/base/date-time-picker/time-picker.tsx@@ -0,0 +1,37 @@+'use client'++import type { TimePickerProps } from '@langgenius/dify-ui/time-picker'+import { TimePicker as BaseTimePicker } from '@langgenius/dify-ui/time-picker'+import { usePickerLabels } from './use-picker-labels'++export function TimePicker(props: TimePickerProps) {+ const defaults = usePickerLabels()+ return (+ <BaseTimePicker+ {...defaults}+ {...props}+ placeholder={props.placeholder ?? defaults.labels.title}+ locale={props.locale ?? defaults.locale}+ labels={{ ...defaults.labels, ...props.labels }}+ />+ )+}++/* oxlint-disable no-barrel-files/no-barrel-files -- Keep this localized picker and its unchanged parts/types in one component entry. */+export {+ TimePickerClear,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+} from '@langgenius/dify-ui/time-picker'+/** @public Prop types for the complete localized picker composition. */+export type {+ TimePickerClearProps,+ TimePickerContentProps,+ TimePickerLabelProps,+ TimePickerProps,+ TimePickerTriggerProps,+ TimePickerValueProps,+} from '@langgenius/dify-ui/time-picker'+/* oxlint-enable no-barrel-files/no-barrel-files */diff --git a/web/app/components/base/date-time-picker/use-picker-labels.ts b/web/app/components/base/date-time-picker/use-picker-labels.tsnew file mode 100644index 00000000000..09c3e08151a--- /dev/null+++ b/web/app/components/base/date-time-picker/use-picker-labels.ts@@ -0,0 +1,41 @@+'use client'++import type { DirectionProviderProps } from '@langgenius/dify-ui/direction-provider'+import { useTranslation } from 'react-i18next'+import { useLocale } from '#i18n'++export function usePickerLabels() {+ const locale = useLocale()+ const { t } = useTranslation(['time'])+ const period = (hour: number) =>+ new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' })+ .formatToParts(new Date(Date.UTC(2025, 0, 1, hour)))+ .find((part) => part.type === 'dayPeriod')?.value ?? (hour < 12 ? 'AM' : 'PM')+ const direction: DirectionProviderProps['direction'] =+ locale === 'ar-TN' || locale === 'fa-IR' ? 'rtl' : 'ltr'+ return {+ direction,+ locale,+ requiredLabel: t(($) => $['picker.requiredLabel']),+ validationMessage: t(($) => $['picker.required']),+ labels: {+ previousMonth: t(($) => $['picker.previousMonth']),+ nextMonth: t(($) => $['picker.nextMonth']),+ chooseMonthAndYear: t(($) => $['picker.chooseMonthAndYear']),+ month: t(($) => $['picker.month']),+ year: t(($) => $['picker.year']),+ hour: t(($) => $['picker.hour']),+ minute: t(($) => $['picker.minute']),+ period: t(($) => $['picker.period']),+ unavailable: t(($) => $['picker.unavailable']),+ backToDate: t(($) => $['operation.pickDate']),+ cancel: t(($) => $['operation.cancel']),+ apply: t(($) => $['operation.ok']),+ now: t(($) => $['operation.now']),+ title: t(($) => $['title.pickTime']),+ pickTime: t(($) => $['title.pickTime']),+ am: period(0),+ pm: period(12),+ },+ }+}diff --git a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsxindex 9eeecf99ae2..c10dc1f1621 100644--- a/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/form.spec.tsx@@ -1,6 +1,5 @@import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import dayjs from '@/app/components/base/date-and-time-picker/utils/dayjs'import MarkdownForm from '../form'const UNSUPPORTED_TAG_ARTICLE_RE = /Unsupported tag:\s*article/@@ -25,11 +24,8 @@ type RootNode = {children: Array<ElementNode | TextNode>}-const { mockOnSend, mockFormatDateForOutput } = vi.hoisted(() => ({+const { mockOnSend } = vi.hoisted(() => ({mockOnSend: vi.fn(),- mockFormatDateForOutput: vi.fn((_date: unknown, includeTime?: boolean) => {- return includeTime ? 'formatted-datetime' : 'formatted-date'- }),}))vi.mock('@/app/components/base/chat/chat/context', () => ({@@ -38,16 +34,6 @@ vi.mock('@/app/components/base/chat/chat/context', () => ({}),}))-vi.mock('@/app/components/base/date-and-time-picker/utils/dayjs', async () => {- const actual = await vi.importActual<- typeof import('@/app/components/base/date-and-time-picker/utils/dayjs')- >('@/app/components/base/date-and-time-picker/utils/dayjs')- return {- ...actual,- formatDateForOutput: mockFormatDateForOutput,- }-})-vi.mock('@/config', async () => {const actual = await vi.importActual<typeof import('@/config')>('@/config')return {@@ -267,7 +253,7 @@ describe('MarkdownForm', () => {})})- // Date and datetime values should be formatted through shared utility before submission.+ // Date-only values stay civil; datetime values serialize as instants.describe('Date formatting', () => {it('should format date and datetime values before sending', async () => {const user = userEvent.setup()@@ -276,12 +262,12 @@ describe('MarkdownForm', () => {createElementNode('input', {type: 'date',name: 'startDate',- value: dayjs('2026-01-10'),+ value: '2026-01-10',}),createElementNode('input', {type: 'datetime',name: 'runAt',- value: dayjs('2026-01-10T08:30:00'),+ value: '2026-01-10T08:30:00.000Z',}),createElementNode('button', {}, [createTextNode('Submit')]),],@@ -293,11 +279,8 @@ describe('MarkdownForm', () => {await user.click(screen.getByRole('button', { name: 'Submit' }))await waitFor(() => {- expect(mockFormatDateForOutput).toHaveBeenCalledTimes(2)- expect(mockFormatDateForOutput).toHaveBeenNthCalledWith(1, expect.anything(), false)- expect(mockFormatDateForOutput).toHaveBeenNthCalledWith(2, expect.anything(), true)expect(mockOnSend).toHaveBeenCalledWith(- '{"startDate":"formatted-date","runAt":"formatted-datetime"}',+ '{"startDate":"2026-01-10","runAt":"2026-01-10T08:30:00.000Z"}',)})})@@ -389,13 +372,35 @@ describe('MarkdownForm', () => {})})+ it.each(['date', 'time', 'datetime'])(+ 'focuses a %s picker from its visible label without opening it',+ async (type) => {+ const user = userEvent.setup()+ render(+ <MarkdownForm+ node={createRootNode([+ createElementNode('label', { htmlFor: 'departure' }, [createTextNode('Departure')]),+ createElementNode('input', { id: 'departure', name: 'departure', type }),+ ])}+ />,+ )+ await user.click(screen.getByText('Departure', { exact: true }))+ const trigger = screen.getByRole('button', { name: 'Departure' })+ expect(trigger).toHaveFocus()+ expect(trigger).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.keyboard('{Enter}')+ expect(await screen.findByRole('dialog', { name: 'Departure' })).toBeInTheDocument()+ },+ )+// DatePicker onChange and onClear callbacks should update form state.describe('DatePicker interaction', () => {it('should update form value when date is picked via onChange', async () => {const user = userEvent.setup()const node = createRootNode([- createElementNode('input', { type: 'date', name: 'startDate', value: '' }),+ createElementNode('input', { type: 'date', name: 'startDate', value: '2026-01-10' }),createElementNode('button', {}, [createTextNode('Submit')]),],{ dataFormat: 'json' },@@ -404,19 +409,17 @@ describe('MarkdownForm', () => {render(<MarkdownForm node={node} />)// Click the DatePicker trigger to open the popup- const trigger = screen.getByTestId('date-picker-trigger')+ const trigger = screen.getByRole('button', { name: /^startDate/ })await user.click(trigger)- // Click the "Now" button in the footer to select current date (calls onChange)- const nowButton = await screen.findByText('time.operation.now')+ // Select a different calendar day.+ const nowButton = await screen.findByRole('button', { name: /January 11/ })await user.click(nowButton)// Submit the formawait user.click(screen.getByRole('button', { name: 'Submit' }))await waitFor(() => {- // onChange was called with a Dayjs object that has .format, so formatDateForOutput is called- expect(mockFormatDateForOutput).toHaveBeenCalledWith(expect.anything(), false)expect(mockOnSend).toHaveBeenCalled()})})@@ -428,7 +431,7 @@ describe('MarkdownForm', () => {createElementNode('input', {type: 'date',name: 'startDate',- value: dayjs('2026-01-10'),+ value: '2026-01-10',}),createElementNode('button', {}, [createTextNode('Submit')]),],@@ -458,12 +461,7 @@ describe('MarkdownForm', () => {render(<MarkdownForm node={node} />)- // The real TimePicker renders a trigger with a readonly input showing the formatted time- const timeInput = screen- .getByTestId('time-picker-trigger')- .querySelector('input[readonly]') as HTMLInputElement- expect(timeInput).not.toBeNull()- expect(timeInput.value).toBe('09:00 AM')+ expect(screen.getByRole('button', { name: 'meetingTime 9:00 AM' })).toBeInTheDocument()})it('should update form value when time is picked via onChange', async () => {@@ -476,12 +474,13 @@ describe('MarkdownForm', () => {render(<MarkdownForm node={node} />)// Click the TimePicker trigger to open the popup- const trigger = screen.getByTestId('time-picker-trigger')+ const trigger = screen.getByRole('button', { name: /^meetingTime/ })await user.click(trigger)// Click the "Now" button in the footer to select current time (calls onChange)const nowButtons = await screen.findAllByText('time.operation.now')await user.click(nowButtons[0]!)+ await user.click(screen.getByRole('button', { name: 'time.operation.ok' }))// Submit the formawait user.click(screen.getByRole('button', { name: 'Submit' }))@@ -663,14 +662,14 @@ describe('MarkdownForm', () => {createElementNode('label', { for: '内容' }, [createTextNode('Content:')]),createElementNode('textarea', { name: '内容', value: 'Hello' }),createElementNode('label', { for: '日期' }, [createTextNode('Date:')]),- createElementNode('input', { type: 'date', name: '日期', value: dayjs('2026-01-10') }),+ createElementNode('input', { type: 'date', name: '日期', value: '2026-01-10' }),createElementNode('label', { for: '时间' }, [createTextNode('Time:')]),createElementNode('input', { type: 'time', name: '时间', value: '09:00' }),createElementNode('label', { for: '日期时间' }, [createTextNode('Datetime:')]),createElementNode('input', {type: 'datetime',name: '日期时间',- value: dayjs('2026-01-10T08:30:00'),+ value: '2026-01-10T08:30:00.000Z',}),createElementNode('label', { for: 'café' }, [createTextNode('Select:')]),createElementNode('input', {@@ -705,8 +704,8 @@ describe('MarkdownForm', () => {用户名: 'Alice',密码: 'secret',内容: 'Hello',- 日期: 'formatted-date',- 日期时间: 'formatted-datetime',+ 日期: '2026-01-10',+ 日期时间: '2026-01-10T08:30:00.000Z',café: 'hello',同意条款: true,})diff --git a/web/app/components/base/markdown-blocks/date-values.ts b/web/app/components/base/markdown-blocks/date-values.tsnew file mode 100644index 00000000000..1989be1a168--- /dev/null+++ b/web/app/components/base/markdown-blocks/date-values.ts@@ -0,0 +1,17 @@+import { parseDateValue } from '../date-time-picker/date-value'++export function parseFormTime(value: unknown): string | undefined {+ if (typeof value !== 'string') return undefined+ const match = /^(\d{1,2}):(\d{2})(?::\d{2}(?:\.\d{1,3})?)?\s*(AM|PM)?$/i.exec(value.trim())+ if (!match) return undefined+ let hour = Number(match[1])+ const minute = Number(match[2])+ if (minute > 59 || (match[3] ? hour < 1 || hour > 12 : hour > 23)) return undefined+ if (match[3]) hour = (hour % 12) + (match[3].toUpperCase() === 'PM' ? 12 : 0)+ return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`+}+export function parseFormInstant(value: unknown): Date | undefined {+ if (typeof value !== 'string' || !parseDateValue(value.slice(0, 10))) return undefined+ const instant = new Date(value)+ return Number.isNaN(instant.getTime()) ? undefined : instant+}diff --git a/web/app/components/base/markdown-blocks/form.tsx b/web/app/components/base/markdown-blocks/form.tsxindex 563e69df372..3e0118c47ef 100644--- a/web/app/components/base/markdown-blocks/form.tsx+++ b/web/app/components/base/markdown-blocks/form.tsx@@ -1,4 +1,3 @@-import type { Dayjs } from 'dayjs'import { Button } from '@langgenius/dify-ui/button'import { Checkbox } from '@langgenius/dify-ui/checkbox'import { Input } from '@langgenius/dify-ui/input'@@ -15,15 +14,33 @@ import {import { Textarea } from '@langgenius/dify-ui/textarea'import * as React from 'react'import { useCallback, useId, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'import { useChatContext } from '@/app/components/base/chat/chat/context'-import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'-import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'import {- formatDateForOutput,- toDayjs,-} from '@/app/components/base/date-and-time-picker/utils/dayjs'+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+} from '@/app/components/base/date-time-picker/date-picker'+import {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '@/app/components/base/date-time-picker/date-time-picker'+import {+ TimePicker,+ TimePickerClear,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+} from '@/app/components/base/date-time-picker/time-picker'import { MARKDOWN_FORM_FIELD_NAME_EXTRA_CHARS, MARKDOWN_FORM_FIELD_NAME_MAX_LENGTH } from '@/config'+import { parseDateValue } from '../date-time-picker/date-value'import { getMarkdownButtonAppearance } from './button-appearance'+import { parseFormInstant, parseFormTime } from './date-values'const DATA_FORMAT = {TEXT: 'text',@@ -53,6 +70,11 @@ const SUPPORTED_TYPES = {type SupportedType = (typeof SUPPORTED_TYPES)[keyof typeof SUPPORTED_TYPES]const SUPPORTED_TYPES_SET = new Set<string>(Object.values(SUPPORTED_TYPES))+const PICKER_TYPES = new Set<string>([+ SUPPORTED_TYPES.DATE,+ SUPPORTED_TYPES.TIME,+ SUPPORTED_TYPES.DATETIME,+])const SAFE_NAME_RE = /^\p{L}[\p{L}\p{M}\p{N}_-]*$/u// Treat operator-provided characters literally instead of interpolating them into a regular expression.@@ -90,7 +112,7 @@ type HastElement = {children: Array<HastElement | HastText>}-type FormValue = string | number | boolean | Dayjs | undefined+type FormValue = string | number | boolean | Date | undefinedtype FormValues = Record<string, FormValue>type EditState = {source: HastElement[]@@ -129,7 +151,12 @@ function computeInitialFormValues(children: HastElement[]): FormValues {type === SUPPORTED_TYPES.TIME) {const raw = child.properties.value- init[name] = raw != null ? toDayjs(String(raw)) : undefined+ init[name] =+ type === SUPPORTED_TYPES.DATE+ ? parseDateValue(raw)+ : type === SUPPORTED_TYPES.TIME+ ? parseFormTime(raw)+ : parseFormInstant(raw)} else if (type === SUPPORTED_TYPES.CHECKBOX) {const { checked, value } = child.propertiesconst hasInitialValue = checked != null || value != null@@ -156,6 +183,8 @@ function getElementKey(child: HastElement, index: number): string {const MarkdownForm = ({ node }: { node: HastElement }) => {const formId = useId()+ const { t } = useTranslation(['common'])+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZoneconst typedNode = nodeconst { onSend } = useChatContext()const [isSubmitting, setIsSubmitting] = useState(false)@@ -199,17 +228,7 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {const name = child.properties.nameif (!isSafeName(name)) continuelet value: FormValue = formValues[name]- if (- child.tagName === SUPPORTED_TAGS.INPUT &&- (child.properties.type === SUPPORTED_TYPES.DATE ||- child.properties.type === SUPPORTED_TYPES.DATETIME) &&- value != null &&- typeof value === 'object' &&- 'format' in value- ) {- const includeTime = child.properties.type === SUPPORTED_TYPES.DATETIME- value = formatDateForOutput(value as Dayjs, includeTime)- }+ if (value instanceof Date) value = value.toISOString()if (value === undefined) continueif (typeof value === 'boolean') out[name] = valueelse out[name] = String(value)@@ -246,6 +265,13 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {{elementChildren.map((child, index) => {const key = getElementKey(child, index)if (child.tagName === SUPPORTED_TAGS.LABEL) {+ const target = elementChildren.find(+ (node) =>+ node.tagName === SUPPORTED_TAGS.INPUT &&+ isSafeName(str(node.properties.name)) &&+ getLabelTarget(child) === (str(node.properties.id) || str(node.properties.name)),+ )+ if (target && PICKER_TYPES.has(str(target.properties.type))) return nullreturn (<labelkey={key}@@ -266,31 +292,83 @@ const MarkdownForm = ({ node }: { node: HastElement }) => {const type = str(child.properties.type) as SupportedTypeconst controlId = `${formId}-${str(child.properties.id) || name}`- const hasExternalLabel = elementChildren.some(+ const fieldLabel = elementChildren.find((node) =>node.tagName === SUPPORTED_TAGS.LABEL &&getLabelTarget(node) === (str(child.properties.id) || name),)-- if (type === SUPPORTED_TYPES.DATE || type === SUPPORTED_TYPES.DATETIME) {+ const hasExternalLabel = Boolean(fieldLabel)+ const pickerLabel = fieldLabel ? getTextContent(fieldLabel) : name+ const pickerProps = {+ name,+ required: Boolean(child.properties.required),+ disabled: Boolean(child.properties.disabled),+ readOnly: Boolean(child.properties.readOnly),+ placeholder: str(child.properties.placeholder) || undefined,+ }+ const clearLabel = t(($) => $['operation.clear'])+ if (type === SUPPORTED_TYPES.DATE) {return (<DatePickerkey={key}- value={formValues[name] as Dayjs | undefined}- needTimePicker={type === SUPPORTED_TYPES.DATETIME}- onChange={(date) => updateValue(name, date)}- onClear={() => updateValue(name, undefined)}- />+ {...pickerProps}+ value={(formValues[name] as string | undefined) ?? null}+ onValueChange={(date) => updateValue(name, date ?? undefined)}+ >+ <DatePickerLabel+ className={fieldLabel ? 'my-2 system-md-semibold text-text-secondary' : 'sr-only'}+ >+ {pickerLabel}+ </DatePickerLabel>+ <div className="flex">+ <DatePickerTrigger id={controlId} />+ <DatePickerClear aria-label={clearLabel} />+ </div>+ <DatePickerContent />+ </DatePicker>+ )+ }+ if (type === SUPPORTED_TYPES.DATETIME) {+ return (+ <DateTimePicker+ key={key}+ {...pickerProps}+ timeZone={timeZone}+ value={(formValues[name] as Date | undefined) ?? null}+ onValueChange={(date) => updateValue(name, date ?? undefined)}+ >+ <DateTimePickerLabel+ className={fieldLabel ? 'my-2 system-md-semibold text-text-secondary' : 'sr-only'}+ >+ {pickerLabel}+ </DateTimePickerLabel>+ <div className="flex">+ <DateTimePickerTrigger id={controlId} />+ <DateTimePickerClear aria-label={clearLabel} />+ </div>+ <DateTimePickerContent />+ </DateTimePicker>)}if (type === SUPPORTED_TYPES.TIME) {return (<TimePickerkey={key}- value={formValues[name] as Dayjs | string | undefined}- onChange={(time) => updateValue(name, time)}- onClear={() => updateValue(name, undefined)}- />+ {...pickerProps}+ value={(formValues[name] as string | undefined) ?? null}+ onValueChange={(time) => updateValue(name, time ?? undefined)}+ >+ <TimePickerLabel+ className={fieldLabel ? 'my-2 system-md-semibold text-text-secondary' : 'sr-only'}+ >+ {pickerLabel}+ </TimePickerLabel>+ <div className="flex">+ <TimePickerTrigger id={controlId} />+ <TimePickerClear aria-label={clearLabel} />+ </div>+ <TimePickerContent />+ </TimePicker>)}if (type === SUPPORTED_TYPES.CHECKBOX) {diff --git a/web/app/components/base/markdown-blocks/index.ts b/web/app/components/base/markdown-blocks/index.tsindex 10e98c9ad97..dc126414cfa 100644--- a/web/app/components/base/markdown-blocks/index.ts+++ b/web/app/components/base/markdown-blocks/index.ts@@ -7,7 +7,6 @@ export { default as AudioBlock } from './audio-block'// Assuming these are also standalone components in this directory intended for Markdown renderingexport { default as MarkdownButton } from './button'-export { default as MarkdownForm } from './form'export { default as Img } from './img'export { default as Link } from './link'export { default as Paragraph } from './paragraph'diff --git a/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx b/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsxindex b04cbe2c023..a5d19d861c6 100644--- a/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx+++ b/web/app/components/base/markdown/__tests__/streamdown-wrapper-form.spec.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from '@testing-library/react'+import { act, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'const { mockOnSend } = vi.hoisted(() => ({@@ -36,6 +36,7 @@ describe('StreamdownWrapper Markdown form field names', () => {`render(<StreamdownWrapper latexContent={content} mode="static" />)+ await act(() => vi.dynamicImportSettled())expect(screen.getByPlaceholderText('mixed-width')).toBeInTheDocument()expect(screen.getByPlaceholderText('full-width')).toBeInTheDocument()@@ -71,6 +72,7 @@ describe('StreamdownWrapper Markdown form field names', () => {</form>`render(<StreamdownWrapper latexContent={content} />)+ await act(() => vi.dynamicImportSettled())expect(await screen.findByRole('button', { name: '提交' })).toBeInTheDocument()expect(screen.queryByText('*')).not.toBeInTheDocument()diff --git a/web/app/components/base/markdown/__tests__/streamdown-wrapper.spec.tsx b/web/app/components/base/markdown/__tests__/streamdown-wrapper.spec.tsxindex ca0ba503187..4f4a3f70887 100644--- a/web/app/components/base/markdown/__tests__/streamdown-wrapper.spec.tsx+++ b/web/app/components/base/markdown/__tests__/streamdown-wrapper.spec.tsx@@ -11,7 +11,6 @@ vi.mock('@/app/components/base/markdown-blocks', () => ({<a href={href}>{children}</a>),MarkdownButton: ({ children }: PropsWithChildren) => <button>{children}</button>,- MarkdownForm: ({ children }: PropsWithChildren) => <form>{children}</form>,Paragraph: ({ children }: PropsWithChildren) => <p data-testid="paragraph">{children}</p>,PluginImg: ({ alt }: { alt?: string }) => <span data-testid="plugin-img">{alt}</span>,PluginParagraph: ({ children }: PropsWithChildren) => (diff --git a/web/app/components/base/markdown/streamdown-wrapper.tsx b/web/app/components/base/markdown/streamdown-wrapper.tsxindex ae6df546add..dbb2e19a9c7 100644--- a/web/app/components/base/markdown/streamdown-wrapper.tsx+++ b/web/app/components/base/markdown/streamdown-wrapper.tsx@@ -10,7 +10,6 @@ import {Img,Link,MarkdownButton,- MarkdownForm,Paragraph,PluginImg,PluginParagraph,@@ -37,6 +36,10 @@ type SanitizeSchema = {const MARKDOWN_FORM_TAG_RE = /<form(?:\s|>)/i+const MarkdownForm = dynamic(() => import('@/app/components/base/markdown-blocks/form'), {+ ssr: false,+})+const CodeBlock = dynamic(() =>import('@/app/components/base/markdown-blocks/code-block').then((module) => module.CodeBlock),diff --git a/web/app/components/base/timezone-label/__tests__/index.spec.tsx b/web/app/components/base/timezone-label/__tests__/index.spec.tsxdeleted file mode 100644index 4b43183eab1..00000000000--- a/web/app/components/base/timezone-label/__tests__/index.spec.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { render, screen } from '@testing-library/react'-import TimezoneLabel from '../index'--describe('TimezoneLabel', () => {- it('shows the timezone offset and source timezone', () => {- const { rerender } = render(<TimezoneLabel timezone="UTC" />)-- expect(screen.getByText('UTC+0')).toHaveAttribute('title', 'Timezone: UTC (UTC+0)')-- rerender(<TimezoneLabel timezone="Asia/Shanghai" />)- expect(screen.getByText('UTC+8')).toHaveAttribute('title', 'Timezone: Asia/Shanghai (UTC+8)')- })-})diff --git a/web/app/components/base/timezone-label/index.tsx b/web/app/components/base/timezone-label/index.tsxdeleted file mode 100644index 1b7f7be0c07..00000000000--- a/web/app/components/base/timezone-label/index.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { cn } from '@langgenius/dify-ui/cn'-import * as React from 'react'-import { useMemo } from 'react'-import { convertTimezoneToOffsetStr } from '@/app/components/base/date-and-time-picker/utils/dayjs'--type TimezoneLabelProps = {- /** IANA timezone identifier (e.g., 'Asia/Shanghai', 'America/New_York') */- timezone: string- /** Additional CSS classes to apply */- className?: string- /** Use inline mode with lighter text color for secondary display */- inline?: boolean-}--/**- * TimezoneLabel component displays timezone information in UTC offset format.- *- * @example- * // Standard display- * <TimezoneLabel timezone="Asia/Shanghai" />- * // Output: UTC+8- *- * @example- * // Inline mode with lighter color- * <TimezoneLabel timezone="America/New_York" inline />- * // Output: UTC-5- *- * @example- * // Custom styling- * <TimezoneLabel timezone="Europe/London" className="text-xs font-bold" />- */-const TimezoneLabel: React.FC<TimezoneLabelProps> = ({ timezone, className, inline = false }) => {- // Memoize offset calculation to avoid redundant computations- const offsetStr = useMemo(() => convertTimezoneToOffsetStr(timezone), [timezone])-- return (- <span- className={cn(- 'system-sm-regular text-text-tertiary',- inline && 'text-text-quaternary',- className,- )}- title={`Timezone: ${timezone} (${offsetStr})`}- >- {offsetStr}- </span>- )-}--export default React.memo(TimezoneLabel)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 5f0ba0e400e..54f193b4934 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,276 +1,65 @@import type { ReactElement } from 'react'-import type { DatePickerProps } from '@/app/components/base/date-and-time-picker/types'-import { fireEvent, render as rtlRender, screen } from '@testing-library/react'-import { describe, expect, it, vi } from 'vite-plus/test'+import { render as rtlRender, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'+import InputCombined from '../../edit-metadata-batch/input-combined'+import { DataType } from '../../types'import WrappedDatePicker from '../date-picker'-// Mock the base date picker component-vi.mock('@/app/components/base/date-and-time-picker/date-picker', () => ({- default: ({ onChange, onClear, renderTrigger, value }: DatePickerProps) => {- const trigger = renderTrigger?.(- {},- { open: false, disabled: false },- {- value,- selectedDate: value,- handleClear: onClear,- },- )- return (- <div role="group" aria-label="Date picker">- {trigger}- <button onClick={() => onChange(value)}>Select Date</button>- <button onClick={() => onClear()}>Clear Date</button>- </div>- )- },-}))--// Mock useTimestamp hookvi.mock('@/hooks/use-timestamp', () => ({- default: () => ({- formatTime: (timestamp: number) => {- if (!timestamp) return ''- return new Date(timestamp * 1000).toLocaleDateString()- },- }),+ default: () => ({ formatTime: (timestamp: number) => new Date(timestamp * 1000).toISOString() }),}))--const render = (ui: ReactElement) => {- const Wrapper = createAccountProfileQueryWrapper()- return rtlRender(ui, { wrapper: Wrapper })-}--describe('WrappedDatePicker', () => {- describe('Rendering', () => {- it('should render placeholder text when no value', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker onChange={handleChange} />)- expect(- screen.getByRole('button', { name: 'dataset.metadata.chooseTime' }),- ).toBeInTheDocument()- })-- it('should render formatted date when value is provided', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })-- it('should render calendar icon', () => {- const handleChange = vi.fn()- const { container } = render(<WrappedDatePicker onChange={handleChange} />)- const svg = container.querySelector('svg')- expect(svg).toBeInTheDocument()- })-- it('should render select date button', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker onChange={handleChange} />)- expect(screen.getByRole('button', { name: 'Select Date' })).toBeInTheDocument()- })-- it('should render clear date button', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker onChange={handleChange} />)- expect(screen.getByRole('button', { name: 'Clear Date' })).toBeInTheDocument()- })-- it('should render close icon for clearing', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)- expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeInTheDocument()- })-- it('should include the field label in the trigger accessible name', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker label="Metadata field" onChange={handleChange} />)-- expect(- screen.getByRole('button', { name: 'Metadata field: dataset.metadata.chooseTime' }),- ).toBeInTheDocument()- })-- it('should include the field label in the clear button accessible name', () => {- const handleChange = vi.fn()- const timestamp = 1609459200- render(<WrappedDatePicker label="Metadata field" value={timestamp} onChange={handleChange} />)-- expect(- screen.getByRole('button', { name: 'Metadata field: common.operation.clear' }),- ).toBeInTheDocument()- })+const render = (ui: ReactElement) => rtlRender(ui, { wrapper: createAccountProfileQueryWrapper() })++describe('Metadata date field', () => {+ it('keeps a read-only metadata date focusable without editing or clearing it', async () => {+ const user = userEvent.setup()+ const changed = vi.fn()+ render(+ <InputCombined+ label="Published"+ type={DataType.time}+ value={1736947800}+ onChange={changed}+ readOnly+ />,+ )+ const trigger = screen.getByRole('button', { name: /^Published/ })+ await user.tab()+ expect(trigger).toHaveFocus()+ await user.keyboard('{Enter}')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'common.operation.clear' })).not.toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()})-- describe('Props', () => {- it('should apply custom className', () => {- const handleChange = vi.fn()- const { container } = render(- <WrappedDatePicker className="custom-class" onChange={handleChange} />,- )- const triggerElement = container.querySelector('.custom-class')- expect(triggerElement).toBeInTheDocument()- })-- it('should accept undefined value', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker value={undefined} onChange={handleChange} />)- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })-- it('should accept number value', () => {- const handleChange = vi.fn()- const timestamp = 1609459200 // 2021-01-01- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })+ it('keeps an empty field empty when opening and dismissing the calendar', async () => {+ const onChange = vi.fn()+ const user = userEvent.setup()+ render(<WrappedDatePicker label="Published" onChange={onChange} />)+ const trigger = screen.getByRole('button', { name: /^Published/ })+ await user.click(trigger)+ expect(await screen.findByRole('dialog', { name: 'Published' })).toBeInTheDocument()+ await user.keyboard('{Escape}')+ expect(onChange).not.toHaveBeenCalled()+ await waitFor(() => expect(trigger).toHaveFocus())})-- describe('User Interactions', () => {- it('should call onChange with timestamp when date is selected', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'Select Date' }))-- expect(handleChange).toHaveBeenCalled()- })-- it('should call onChange with null when date is cleared via onClear', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'Clear Date' }))-- expect(handleChange).toHaveBeenCalledWith(null)- })-- it('should call onChange with null when close icon is clicked directly', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'common.operation.clear' }))-- expect(handleChange).toHaveBeenCalledWith(null)- })-- it('should show close button on hover when value exists', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- const { container } = render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- // The close icon should be present but hidden initially- const triggerGroup = container.querySelector('.group')- expect(triggerGroup).toBeInTheDocument()- })-- it('should handle clicking on trigger element', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- const { container } = render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- const trigger = container.querySelector('.group.flex')- if (trigger) fireEvent.click(trigger)-- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })+ it('treats Unix epoch zero as a value and returns focus after clearing it', async () => {+ const onChange = vi.fn()+ const user = userEvent.setup()+ render(<WrappedDatePicker label="Published" value={0} onChange={onChange} />)+ const trigger = screen.getByRole('button', { name: /Published 1970-01-01/ })+ await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith(null)+ expect(trigger).toHaveFocus()})-- describe('Styling', () => {- it('should have tertiary text color when no value', () => {- const handleChange = vi.fn()- const { container } = render(<WrappedDatePicker onChange={handleChange} />)- const textElement = container.querySelector('.text-text-tertiary')- expect(textElement).toBeInTheDocument()- })-- it('should have secondary text color when value exists', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- const { container } = render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)- const textElement = container.querySelector('.text-text-secondary')- expect(textElement).toBeInTheDocument()- })-- it('should have input background styling', () => {- const handleChange = vi.fn()- const { container } = render(<WrappedDatePicker onChange={handleChange} />)- const bgElement = container.querySelector('.bg-components-input-bg-normal')- expect(bgElement).toBeInTheDocument()- })-- it('should have quaternary text color for close icon when value exists', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- const { container } = render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)- const closeIcon = container.querySelector('.text-text-quaternary')- expect(closeIcon).toBeInTheDocument()- })- })-- describe('Edge Cases', () => {- it('should handle timestamp of 0', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker value={0} onChange={handleChange} />)- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })-- it('should handle very large timestamp', () => {- const handleChange = vi.fn()- const farFuture = 4102444800 // 2100-01-01- render(<WrappedDatePicker value={farFuture} onChange={handleChange} />)- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })-- it('should handle switching between no value and value', () => {- const handleChange = vi.fn()- const { rerender } = render(<WrappedDatePicker onChange={handleChange} />)-- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()-- const timestamp = Math.floor(Date.now() / 1000)- rerender(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- expect(screen.getByRole('group', { name: 'Date picker' })).toBeInTheDocument()- })-- it('should handle clearing date multiple times', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'Clear Date' }))- fireEvent.click(screen.getByRole('button', { name: 'Clear Date' }))- fireEvent.click(screen.getByRole('button', { name: 'Clear Date' }))-- expect(handleChange).toHaveBeenCalledTimes(3)- })-- it('should handle rapid date selections', () => {- const handleChange = vi.fn()- const timestamp = Math.floor(Date.now() / 1000)- render(<WrappedDatePicker value={timestamp} onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'Select Date' }))- fireEvent.click(screen.getByRole('button', { name: 'Select Date' }))- fireEvent.click(screen.getByRole('button', { name: 'Select Date' }))-- expect(handleChange).toHaveBeenCalledTimes(3)- })-- it('should handle onChange with date object that has unix method', () => {- const handleChange = vi.fn()- render(<WrappedDatePicker onChange={handleChange} />)-- fireEvent.click(screen.getByRole('button', { name: 'Select Date' }))-- expect(handleChange).toHaveBeenCalled()- })+ it('commits the selected date as Unix seconds only after confirmation', async () => {+ const onChange = vi.fn()+ const user = userEvent.setup()+ render(<WrappedDatePicker label="Published" value={1736947800} onChange={onChange} />)+ await user.click(screen.getByRole('button', { name: /^Published/ }))+ await user.click(await screen.findByRole('button', { name: /January 16/ }))+ expect(onChange).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'time.operation.ok' }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith(1737034200)})})diff --git a/web/app/components/datasets/metadata/base/date-picker.tsx b/web/app/components/datasets/metadata/base/date-picker.tsxindex 5cd3af075eb..30fa58efc08 100644--- a/web/app/components/datasets/metadata/base/date-picker.tsx+++ b/web/app/components/datasets/metadata/base/date-picker.tsx@@ -1,11 +1,14 @@-import type { DatePickerProps } from '@/app/components/base/date-and-time-picker/types'import { cn } from '@langgenius/dify-ui/cn'-import { RiCalendarLine, RiCloseCircleFill } from '@remixicon/react'import { useQuery } from '@tanstack/react-query'-import dayjs from 'dayjs'-import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'+import {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+ DateTimePickerValue,+} from '@/app/components/base/date-time-picker/date-time-picker'import { userProfileQueryOptions } from '@/features/account-profile/client'import useTimestamp from '@/hooks/use-timestamp'@@ -13,91 +16,53 @@ type Props = Readonly<{className?: stringlabel?: stringvalue?: number+ readOnly?: booleanonChange: (date: number | null) => void}>-const WrappedDatePicker = ({ className, label, value, onChange }: Props) => {+function WrappedDatePicker({ className, label, value, readOnly, onChange }: Props) {const { t } = useTranslation(['common', 'dataset', 'datasetDocuments'])- const { data: timezone } = useQuery({+ const { data: timezone = 'UTC' } = useQuery({...userProfileQueryOptions(),- select: (data) => data.profile.timezone ?? undefined,+ select: (data) => data.profile.timezone || 'UTC',})- const { formatTime: formatTimestamp } = useTimestamp()-- const handleDateChange = useCallback(- (date?: dayjs.Dayjs) => {- if (date) onChange(date.unix())- else onChange(null)- },- [onChange],- )-- const renderTrigger = useCallback<NonNullable<DatePickerProps['renderTrigger']>>(- (props) => {- const hasValue = Boolean(value)- const triggerText = value- ? formatTimestamp(- value,- t(($) => $['metadata.dateTimeFormat'], { ns: 'datasetDocuments' }),- )- : t(($) => $['metadata.chooseTime'], { ns: 'dataset' })- const clearLabel = t(($) => $['operation.clear'], { ns: 'common' })-- return (- <div- className={cn(- 'group flex items-center rounded-md bg-components-input-bg-normal',- className,- props.className,- )}- >- <button- {...props}- type="button"- aria-label={label ? `${label}: ${triggerText}` : undefined}- className="flex min-w-0 grow items-center border-none bg-transparent p-0 text-left focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"- >- <span className={cn('grow', hasValue ? 'text-text-secondary' : 'text-text-tertiary')}>- {triggerText}- </span>- <RiCalendarLine- aria-hidden="true"- className={cn(- 'block size-4 shrink-0',- hasValue ? 'text-text-quaternary' : 'text-text-tertiary',- )}- />- </button>- {hasValue ? (- <button- type="button"- aria-label={label ? `${label}: ${clearLabel}` : clearLabel}- className={cn(- 'size-4 shrink-0 cursor-pointer rounded-full border-none bg-transparent p-0 text-text-quaternary opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 hover:text-components-input-text-filled focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden [@media(hover:none)]:opacity-100',- )}- onClick={(event) => {- event.stopPropagation()- handleDateChange()- }}- >- <RiCloseCircleFill className="size-4" aria-hidden="true" />- </button>- ) : null}- </div>- )- },- [className, label, value, formatTimestamp, t, handleDateChange],- )-+ const { formatTime } = useTimestamp()+ const placeholder = t(($) => $['metadata.chooseTime'], { ns: 'dataset' })return (- <DatePicker- value={dayjs(value ? value * 1000 : Date.now())}- timezone={timezone}- onChange={handleDateChange}- onClear={handleDateChange}- renderTrigger={renderTrigger}- triggerWrapClassName="w-full"- />+ <DateTimePicker+ readOnly={readOnly}+ placeholder={placeholder}+ value={value === undefined ? null : new Date(value * 1000)}+ timeZone={timezone}+ onValueChange={(next) => onChange(next ? Math.floor(next.getTime() / 1000) : null)}+ >+ <DateTimePickerLabel className="sr-only">{label || placeholder}</DateTimePickerLabel>+ <div+ className={cn(+ 'flex h-8 w-full items-center rounded-md bg-components-input-bg-normal',+ className,+ )}+ >+ <DateTimePickerTrigger className="h-full min-w-0 flex-1 bg-transparent px-1 text-xs">+ <DateTimePickerValue>+ {value === undefined+ ? placeholder+ : formatTime(+ value,+ t(($) => $['metadata.dateTimeFormat'], { ns: 'datasetDocuments' }),+ )}+ </DateTimePickerValue>+ <span+ className="i-ri-calendar-line size-4 shrink-0 text-text-tertiary"+ aria-hidden="true"+ />+ </DateTimePickerTrigger>+ <DateTimePickerClear+ className="size-4"+ aria-label={t(($) => $['operation.clear'], { ns: 'common' })}+ />+ </div>+ <DateTimePickerContent />+ </DateTimePicker>)}-export default WrappedDatePickerdiff --git a/web/app/components/datasets/metadata/edit-metadata-batch/input-combined.tsx b/web/app/components/datasets/metadata/edit-metadata-batch/input-combined.tsxindex 5409e1c6946..c7eec1285fb 100644--- a/web/app/components/datasets/metadata/edit-metadata-batch/input-combined.tsx+++ b/web/app/components/datasets/metadata/edit-metadata-batch/input-combined.tsx@@ -33,7 +33,15 @@ const InputCombined: FC<Props> = ({}) => {const className = cn('h-6 grow p-0.5 text-xs')if (type === DataType.time) {- return <Datepicker label={label} className={className} value={value} onChange={onChange} />+ return (+ <Datepicker+ label={label}+ className={className}+ value={value}+ onChange={onChange}+ readOnly={readOnly}+ />+ )}if (type === DataType.number) {diff --git a/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx b/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsxindex 374f2f37973..8d486af6454 100644--- a/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/update-setting-dialog-form.spec.tsx@@ -1,5 +1,6 @@import type { SettingsDestination } from '@/app/components/header/account-setting/query-params'import { fireEvent, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import * as React from 'react'import {AUTO_UPDATE_MODE,@@ -61,7 +62,8 @@ describe('UpdateSettingDialogForm', () => {mockSettingsDestination = null})- it('should open preferences after closing the update setting dialog when timezone link is clicked', () => {+ it('should focus update time from its label and keep the timezone action separate', async () => {+ const user = userEvent.setup()const onRequestClose = vi.fn()render(@@ -79,16 +81,22 @@ describe('UpdateSettingDialogForm', () => {strategyOptions={[{ value: AUTO_UPDATE_STRATEGY.fixOnly, label: 'Fix only' }]}timezone="UTC"updateTimeValue="00:00"- minuteFilter={(minutes) => minutes}onAutoUpgradeChange={vi.fn()}onPluginsChange={vi.fn()}onRequestClose={onRequestClose}onUpdateTimeChange={vi.fn()}- renderTimePickerTrigger={() => <button type="button">Pick time</button>}/>,)- fireEvent.click(screen.getByText('autoUpdate.changeTimezone'))+ expect(+ screen.getByRole('button', { name: /autoUpdate.updateTime.*12:00 AM.*UTC/ }),+ ).toBeInTheDocument()+ await user.click(screen.getByText('plugin.autoUpdate.updateTime', { exact: true }))+ expect(+ screen.getByRole('button', { name: /autoUpdate.updateTime.*12:00 AM.*UTC/ }),+ ).toHaveFocus()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.click(screen.getByText('autoUpdate.changeTimezone'))expect(onRequestClose).toHaveBeenCalledTimes(1)expect(mockSetSettingsDestination).toHaveBeenCalledWith('preferences')@@ -112,12 +120,10 @@ describe('UpdateSettingDialogForm', () => {strategyOptions={[{ value: AUTO_UPDATE_STRATEGY.fixOnly, label: 'Fix only' }]}timezone="UTC"updateTimeValue="00:00"- minuteFilter={(minutes) => minutes}onAutoUpgradeChange={vi.fn()}onPluginsChange={vi.fn()}onRequestClose={vi.fn()}onUpdateTimeChange={vi.fn()}- renderTimePickerTrigger={() => <button type="button">Pick time</button>}/>,)diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsxindex d0a11801742..5b935d0a31a 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'import type { PluginDeclaration, PluginDetail } from '@/app/components/plugins/types'-import { act, fireEvent, screen } from '@testing-library/react'+import { act, fireEvent, screen, within } from '@testing-library/react'import { describe, expect, it, vi } from 'vite-plus/test'import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types'import {@@ -607,11 +607,19 @@ describe('ModelProviderPage', () => {openUpdateSettings()fireEvent.click(screen.getByRole('button', { name: /12:00 AM/ }))- fireEvent.click(screen.getByRole('button', { name: '01' }))- fireEvent.click(screen.getByRole('button', { name: '15' }))+ fireEvent.click(+ within(screen.getByRole('listbox', { name: 'time.picker.hour' })).getByRole('option', {+ name: '1',+ }),+ )+ fireEvent.click(+ within(screen.getByRole('listbox', { name: 'time.picker.minute' })).getByRole('option', {+ name: '15',+ }),+ )fireEvent.click(screen.getByRole('button', { name: 'time.operation.ok' }))- expect(screen.getByRole('button', { name: /01:15 AM/ })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /1:15 AM/ })).toBeInTheDocument()saveUpdateSettings()diff --git a/web/app/components/header/account-setting/update-setting-dialog-form.tsx b/web/app/components/header/account-setting/update-setting-dialog-form.tsxindex 110066febb5..ffe748289f6 100644--- a/web/app/components/header/account-setting/update-setting-dialog-form.tsx+++ b/web/app/components/header/account-setting/update-setting-dialog-form.tsx@@ -1,14 +1,18 @@import type { ReactNode } from 'react'-import type { TimePickerProps } from '@/app/components/base/date-and-time-picker/types'import type { AutoUpdateConfig } from '@/app/components/plugins/reference-setting-modal/auto-update-setting/types'-import type { dayjsToTimeOfDay } from '@/app/components/plugins/reference-setting-modal/auto-update-setting/utils'import type { PluginCategoryEnum } from '@/app/components/plugins/types'import { cn } from '@langgenius/dify-ui/cn'import { RadioGroup } from '@langgenius/dify-ui/radio-group'import { useQueryState } from 'nuqs'import { useState } from 'react'import { Trans, useTranslation } from 'react-i18next'-import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'+import {+ TimePicker,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+} from '@/app/components/base/date-time-picker/time-picker'import {settingsQueryParamName,settingsQueryParser,@@ -18,7 +22,7 @@ import {AUTO_UPDATE_MODE,AUTO_UPDATE_STRATEGY,} from '@/app/components/plugins/reference-setting-modal/auto-update-setting/types'-import { convertLocalSecondsToUTCDaySeconds } from '@/app/components/plugins/reference-setting-modal/auto-update-setting/utils'+import { convertTimezoneToOffsetStr } from '@/utils/timezone'import UpdateSettingOptionCard from './update-setting-option-card'type Option<Value extends string> = {@@ -34,12 +38,10 @@ type UpdateSettingDialogFormProps = {strategyOptions: Option<AUTO_UPDATE_STRATEGY>[]timezone: stringupdateTimeValue: string- minuteFilter: (minutes: string[]) => string[]onAutoUpgradeChange: (payload: Partial<AutoUpdateConfig>) => voidonPluginsChange: (newPlugins: string[]) => voidonRequestClose: () => void- onUpdateTimeChange: (value: Parameters<typeof dayjsToTimeOfDay>[0]) => void- renderTimePickerTrigger: NonNullable<TimePickerProps['renderTrigger']>+ onUpdateTimeChange: (value: string | null) => void}const updateSettingFormLabelClassName =@@ -81,12 +83,10 @@ const UpdateSettingDialogForm = ({strategyOptions,timezone,updateTimeValue,- minuteFilter,onAutoUpgradeChange,onPluginsChange,onRequestClose,onUpdateTimeChange,- renderTimePickerTrigger,}: UpdateSettingDialogFormProps) => {const { t } = useTranslation(['plugin'])const [previewStrategy, setPreviewStrategy] = useState<AUTO_UPDATE_STRATEGY>()@@ -137,34 +137,41 @@ const UpdateSettingDialogForm = ({<><div className="h-px w-full bg-divider-subtle" /><div className="flex w-full flex-col items-start gap-1">- <div className="flex w-full items-center gap-2">- <div className={cn(updateSettingFormLabelClassName, 'min-w-0 flex-1')}>- {t(($) => $['autoUpdate.updateTime'], { ns: 'plugin' })}- </div>- <div className="body-xs-regular text-text-tertiary">- <Trans- i18nKey={($) => $['autoUpdate.changeTimezone']}- ns="plugin"- components={{- setTimezone: <SettingTimeZone onRequestClose={onRequestClose} />,- }}- />- </div>- </div><TimePicker- value={updateTimeValue}- timezone={timezone}- onChange={onUpdateTimeChange}- onClear={() =>- onAutoUpgradeChange({- upgrade_time_of_day: convertLocalSecondsToUTCDaySeconds(0, timezone),- })- }- title={t(($) => $['autoUpdate.updateTime'], { ns: 'plugin' })}- minuteFilter={minuteFilter}- renderTrigger={renderTimePickerTrigger}- triggerNativeButton- />+ timeZone={timezone}+ value={updateTimeValue || null}+ onValueChange={onUpdateTimeChange}+ minuteStep={15}+ >+ <div className="flex w-full items-center gap-2">+ <TimePickerLabel className={cn(updateSettingFormLabelClassName, 'min-w-0 flex-1')}>+ {t(($) => $['autoUpdate.updateTime'], { ns: 'plugin' })}+ </TimePickerLabel>+ <div className="body-xs-regular text-text-tertiary">+ <Trans+ i18nKey={($) => $['autoUpdate.changeTimezone']}+ ns="plugin"+ components={{+ setTimezone: <SettingTimeZone onRequestClose={onRequestClose} />,+ }}+ />+ </div>+ </div>+ <TimePickerTrigger className="w-full px-2">+ <span aria-hidden="true" className="i-ri-time-line size-4 text-text-tertiary" />+ <TimePickerValue className="flex min-w-0 flex-1 items-center justify-between gap-1">+ {(displayValue) => (+ <>+ <span>{displayValue}</span>+ <span className="text-text-tertiary">+ {convertTimezoneToOffsetStr(timezone)}+ </span>+ </>+ )}+ </TimePickerValue>+ </TimePickerTrigger>+ <TimePickerContent />+ </TimePicker></div><div className="flex w-full flex-col items-start gap-2"><div className="flex h-15 w-full flex-col items-start gap-1">diff --git a/web/app/components/header/account-setting/update-setting-dialog.tsx b/web/app/components/header/account-setting/update-setting-dialog.tsxindex 9a46a5e20f3..487d3491636 100644--- a/web/app/components/header/account-setting/update-setting-dialog.tsx+++ b/web/app/components/header/account-setting/update-setting-dialog.tsx@@ -1,12 +1,7 @@'use client'-import type {- TimePickerProps,- TriggerParams,-} from '@/app/components/base/date-and-time-picker/types'import type { AutoUpdateConfig } from '@/app/components/plugins/reference-setting-modal/auto-update-setting/types'import type { PluginCategoryEnum } from '@/app/components/plugins/types'import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'import {Dialog,DialogClose,@@ -18,7 +13,6 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'import { useSuspenseQuery } from '@tanstack/react-query'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { convertTimezoneToOffsetStr } from '@/app/components/base/date-and-time-picker/utils/dayjs'import {AUTO_UPDATE_MODE,AUTO_UPDATE_STRATEGY,@@ -26,8 +20,6 @@ import {import {convertLocalSecondsToUTCDaySeconds,convertUTCDaySecondsToLocalSeconds,- dayjsToTimeOfDay,- timeOfDayToDayjs,} from '@/app/components/plugins/reference-setting-modal/auto-update-setting/utils'import { toast } from '@/app/notifications'import { userProfileQueryOptions } from '@/features/account-profile/client'@@ -95,15 +87,12 @@ const UpdateSettingDialog = ({ category, disabled = false }: Props) => {return []}}, [autoUpgrade])- const updateTimeValue = useMemo(() => {- if (!autoUpgrade) return ''-- const localSeconds = convertUTCDaySecondsToLocalSeconds(- autoUpgrade.upgrade_time_of_day,- timezone,- )- return timeOfDayToDayjs(localSeconds).format('HH:mm')- }, [autoUpgrade, timezone])+ const localSeconds = autoUpgrade+ ? convertUTCDaySecondsToLocalSeconds(autoUpgrade.upgrade_time_of_day, timezone)+ : 0+ const updateTimeValue = autoUpgrade+ ? `${String(Math.floor(localSeconds / 3600)).padStart(2, '0')}:${String(Math.floor((localSeconds % 3600) / 60)).padStart(2, '0')}`+ : ''const strategyOptions = useMemo(() => [{@@ -170,20 +159,15 @@ const UpdateSettingDialog = ({ category, disabled = false }: Props) => {},[autoUpgrade, updateAutoUpgrade],)- const minuteFilter = useCallback((minutes: string[]) => {- return minutes.filter((m) => {- const time = Number.parseInt(m, 10)- return time % 15 === 0+ const handleUpdateTimeChange = (value: string | null) => {+ const [hour, minute] = (value ?? '00:00').split(':').map(Number)+ updateAutoUpgrade({+ upgrade_time_of_day: convertLocalSecondsToUTCDaySeconds(+ hour! * 3600 + minute! * 60,+ timezone,+ ),})- }, [])- const handleUpdateTimeChange = useCallback(- (value: Parameters<typeof dayjsToTimeOfDay>[0]) => {- updateAutoUpgrade({- upgrade_time_of_day: convertLocalSecondsToUTCDaySeconds(dayjsToTimeOfDay(value), timezone),- })- },- [timezone, updateAutoUpgrade],- )+ }const handleOpenChange = useCallback((open: boolean) => {if (disabled) {@@ -208,40 +192,6 @@ const UpdateSettingDialog = ({ category, disabled = false }: Props) => {setDraftAutoUpgrade(undefined)setIsOpen(false)}, [autoUpgrade, saveAutoUpgrade])- const renderTimePickerTrigger = useCallback<NonNullable<TimePickerProps['renderTrigger']>>(- (props, state, { displayText, onClick }: TriggerParams) => {- return (- <button- {...props}- type="button"- className={cn(- 'group flex h-8 w-full cursor-pointer items-center gap-1 rounded-lg border-none bg-components-input-bg-normal px-2 py-1 text-left shadow-none hover:bg-state-base-hover-alt focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden',- props.className,- )}- onClick={(event) => {- onClick(event)- props.onClick?.(event)- }}- >- <span- aria-hidden- className={cn(- 'i-ri-time-line size-4 shrink-0 text-text-tertiary',- state.open ? 'text-text-secondary' : 'group-hover:text-text-secondary',- )}- />- <span className="sr-only">{t(($) => $['autoUpdate.updateTime'], { ns: 'plugin' })}</span>- <span className="min-w-0 flex-1 p-1 system-sm-regular text-components-input-text-filled">- {displayText}- </span>- <span className="shrink-0 pr-0.5 system-sm-regular text-text-tertiary">- {convertTimezoneToOffsetStr(timezone)}- </span>- </button>- )- },- [t, timezone],- )return (<Dialog open={isOpen} onOpenChange={handleOpenChange}>@@ -303,12 +253,10 @@ const UpdateSettingDialog = ({ category, disabled = false }: Props) => {strategyOptions={strategyOptions}timezone={timezone}updateTimeValue={updateTimeValue}- minuteFilter={minuteFilter}onAutoUpgradeChange={updateAutoUpgrade}onPluginsChange={handlePluginsChange}onRequestClose={handleCancel}onUpdateTimeChange={handleUpdateTimeChange}- renderTimePickerTrigger={renderTimePickerTrigger}/><div className="flex h-19 items-center justify-end gap-2 px-6 pt-5 pb-6"><Button variant="secondary" className="min-w-18" onClick={handleCancel}>diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsxindex fbdafc55c72..e0122da3d13 100644--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx@@ -140,6 +140,31 @@ describe('ReasoningConfigForm', () => {vi.clearAllMocks()})+ it('names date parameters from their field title and emits tool storage values', async () => {+ const user = userEvent.setup()+ const onChange = vi.fn()+ render(+ <ReasoningConfigForm+ value={{ field: { auto: 0, value: { type: VarKindType.constant, value: '2025-01-15' } } }}+ onChange={onChange}+ schemas={[+ createSchema({+ type: FormTypeEnum.date,+ label: { en_US: 'Departure', zh_Hans: '出发日期' },+ }),+ ]}+ nodeOutputVars={[]}+ availableNodes={[]}+ nodeId="node-1"+ />,+ )+ await user.click(screen.getByRole('button', { name: 'Departure Jan 15, 2025' }))+ await user.click(await screen.findByRole('button', { name: /January 16th, 2025/ }))+ expect(onChange).toHaveBeenCalledWith({+ field: { auto: 0, value: { type: VarKindType.constant, value: '2025-01-16' } },+ })+ })+it('should toggle automatic values for text fields', () => {const onChange = vi.fn()diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsxindex 7263674c0ea..4a14332a656 100644--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx@@ -16,7 +16,6 @@ import {} from '@langgenius/dify-ui/select'import { Switch } from '@langgenius/dify-ui/switch'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { useCallback, useId, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -24,6 +23,8 @@ import { FormTypeEnum } from '@/app/components/header/account-setting/model-provimport { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'import { AppSelector } from '@/app/components/plugins/plugin-detail-panel/app-selector'import ModelParameterModal from '@/app/components/plugins/plugin-detail-panel/model-selector'+import { ToolDatePicker } from '@/app/components/tools/parameters/tool-date-picker'+import { ToolDateRangePicker } from '@/app/components/tools/parameters/tool-date-range-picker'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import FormInputBoolean from '@/app/components/workflow/nodes/_base/components/form-input-boolean'import FormInputTypeSwitch from '@/app/components/workflow/nodes/_base/components/form-input-type-switch'@@ -31,9 +32,6 @@ import VarReferencePicker from '@/app/components/workflow/nodes/_base/componentsimport { VarKindType } from '@/app/components/workflow/nodes/_base/types'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import MixedVariableTextInput from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input'-import ToolDatePicker from '@/app/components/workflow/nodes/tool/components/tool-date-picker'-import ToolDateRangePicker from '@/app/components/workflow/nodes/tool/components/tool-date-range-picker'-import { userProfileQueryOptions } from '@/features/account-profile/client'import {createPickerProps,getFieldFlags,@@ -70,10 +68,6 @@ const ReasoningConfigForm: React.FC<Props> = ({const { t } = useTranslation(['plugin', 'tools', 'workflowAgent'])const language = useLanguage()- const { data: timezone } = useSuspenseQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.timezone ?? 'UTC',- })const handleAutomatic = (key: string, val: boolean, type: string) => {onChange(updateInputAutoState(value, key, val, type))@@ -262,9 +256,9 @@ const ReasoningConfigForm: React.FC<Props> = ({{isDate && isConstant && (<div className="min-w-0 grow"><ToolDatePicker- value={typeof varInput?.value === 'string' ? varInput.value : ''}+ aria-label={fieldTitle || variable}+ value={varInput?.value}onChange={handleValueChange(variable, type)}- timezone={timezone}placeholder={placeholder?.[language] || placeholder?.en_US}/></div>@@ -272,9 +266,9 @@ const ReasoningConfigForm: React.FC<Props> = ({{isDateRange && varInput?.type !== VarKindType.variable && (<div className="grow"><ToolDateRangePicker+ label={fieldTitle || variable}value={varInput?.value}onChange={handleValueChange(variable, type)}- timezone={timezone}/></div>)}diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsxindex 319a87043c6..35ed90f1bdb 100644--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx@@ -77,7 +77,6 @@ export function ToolSettingsPanel({const settingsForm = (<div className="px-4 py-2"><ToolForm- inPanelreadOnly={false}nodeId={nodeId}schema={settingsFormSchemas as CredentialFormSchema[]}diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/utils.spec.ts b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/utils.spec.tsindex 02ecb4b22dc..5ffbfce458f 100644--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/utils.spec.ts+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/utils.spec.ts@@ -1,6 +1,15 @@import { convertLocalSecondsToUTCDaySeconds, convertUTCDaySecondsToLocalSeconds } from '../utils'-describe('convertLocalSecondsToUTCDaySeconds', () => {+describe('auto-update daily clock conversion', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-01-15T12:00:00Z'))+ })++ afterEach(() => {+ vi.useRealTimers()+ })+it('should convert local seconds to UTC day seconds correctly', () => {const localTimezone = 'Asia/Shanghai'const utcSeconds = convertLocalSecondsToUTCDaySeconds(0, localTimezone)@@ -16,4 +25,32 @@ describe('convertLocalSecondsToUTCDaySeconds', () => {),).toBe(0)})++ it.each([+ ['2026-11-02T12:00:00Z', 16200],+ ['2026-03-09T12:00:00Z', 12600],+ ])('displays 23:30 across the DST transition preceding %s', (now, utcSeconds) => {+ vi.setSystemTime(new Date(now))+ expect(convertUTCDaySecondsToLocalSeconds(utcSeconds, 'America/New_York')).toBe(84600)+ })++ it.each([+ ['2026-11-01T12:00:00Z', 70200],+ ['2026-03-08T12:00:00Z', 66600],+ ])('saves and restores a 14:30 wall time on the DST transition at %s', (now, utcSeconds) => {+ vi.setSystemTime(new Date(now))+ const saved = convertLocalSecondsToUTCDaySeconds(52200, 'America/New_York')+ expect(saved).toBe(utcSeconds)+ expect(convertUTCDaySecondsToLocalSeconds(saved, 'America/New_York')).toBe(52200)+ })++ it.each([+ ['2026-11-01T12:00:00Z', 16200],+ ['2026-03-08T12:00:00Z', 12600],+ ])('preserves 23:30 when saving crosses the UTC date boundary at %s', (now, utcSeconds) => {+ vi.setSystemTime(new Date(now))+ const saved = convertLocalSecondsToUTCDaySeconds(84600, 'America/New_York')+ expect(saved).toBe(utcSeconds)+ expect(convertUTCDaySecondsToLocalSeconds(saved, 'America/New_York')).toBe(84600)+ })})diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/utils.ts b/web/app/components/plugins/reference-setting-modal/auto-update-setting/utils.tsindex 93eb3affb86..02181556982 100644--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/utils.ts+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/utils.ts@@ -17,17 +17,13 @@ export const convertLocalSecondsToUTCDaySeconds = (secondsInDay: number,localTimezone: string,): number => {- const localDayStart = dayjs().tz(localTimezone).startOf('day')- const localTargetTime = localDayStart.add(secondsInDay, 'second')- const utcTargetTime = localTargetTime.utc()- const utcDayStart = utcTargetTime.startOf('day')- const secondsFromUTCMidnight = utcTargetTime.diff(utcDayStart, 'second')- return secondsFromUTCMidnight-}--export const dayjsToTimeOfDay = (date?: Dayjs): number => {- if (!date) return 0- return date.hour() * 3600 + date.minute() * 60+ // The API stores a daily UTC clock, not a date. Use the same current offset in both directions.+ const offset = dayjs().tz(localTimezone).utcOffset()+ const utcTargetTime = dayjs+ .utc()+ .startOf('day')+ .add(secondsInDay - offset * 60, 'second')+ return utcTargetTime.hour() * 3600 + utcTargetTime.minute() * 60 + utcTargetTime.second()}export const convertUTCDaySecondsToLocalSeconds = (@@ -36,8 +32,6 @@ export const convertUTCDaySecondsToLocalSeconds = (): number => {const utcDayStart = dayjs().utc().startOf('day')const utcTargetTime = utcDayStart.add(utcDaySeconds, 'second')- const localTargetTime = utcTargetTime.tz(localTimezone)- const localDayStart = localTargetTime.startOf('day')- const secondsInLocalDay = localTargetTime.diff(localDayStart, 'second')- return secondsInLocalDay+ const localTargetTime = utcTargetTime.utcOffset(dayjs().tz(localTimezone).utcOffset())+ return localTargetTime.hour() * 3600 + localTargetTime.minute() * 60 + localTargetTime.second()}diff --git a/web/app/components/workflow/nodes/tool/components/__tests__/tool-date-picker.spec.tsx b/web/app/components/tools/parameters/__tests__/tool-date-picker.spec.tsxsimilarity index 81%rename from web/app/components/workflow/nodes/tool/components/__tests__/tool-date-picker.spec.tsxrename to web/app/components/tools/parameters/__tests__/tool-date-picker.spec.tsxindex 104074850ee..2547e2fdccb 100644--- a/web/app/components/workflow/nodes/tool/components/__tests__/tool-date-picker.spec.tsx+++ b/web/app/components/tools/parameters/__tests__/tool-date-picker.spec.tsx@@ -1,7 +1,7 @@import { fireEvent, render, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { describe, expect, it, vi } from 'vite-plus/test'-import ToolDatePicker from '../tool-date-picker'+import { ToolDatePicker } from '../tool-date-picker'vi.mock('react-i18next', async () => {const actual = await vi.importActual<typeof import('react-i18next')>('react-i18next')@@ -9,7 +9,6 @@ vi.mock('react-i18next', async () => {return {...actual,...createReactI18nextMock({- 'time.dateFormats.display': 'MMMM D, YYYY','time.operation.pickDate': 'Select date','common.operation.clear': 'Clear',}),@@ -20,23 +19,23 @@ describe('ToolDatePicker', () => {it('preserves a stored date-only value when rendering in a negative timezone', () => {render(<ToolDatePicker+ aria-label="Select date"value="2024-05-01"onChange={vi.fn()}- timezone="America/Los_Angeles"placeholder="Select date"/>,)- expect(screen.getByRole('button', { name: 'Select date: May 1, 2024' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Select date May 1, 2024' })).toBeInTheDocument()})it('returns an empty string when clearing the date', () => {const onChange = vi.fn()render(<ToolDatePicker+ aria-label="Select date"value="2024-05-01"onChange={onChange}- timezone="UTC"placeholder="Select date"/>,)@@ -49,23 +48,26 @@ describe('ToolDatePicker', () => {it('disables interaction and clearing when read only', () => {render(<ToolDatePicker+ aria-label="Select date"value="2024-05-01"onChange={vi.fn()}- timezone="UTC"placeholder="Select date"readOnly/>,)- expect(screen.getByRole('button', { name: 'Select date: May 1, 2024' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Select date May 1, 2024' })).toHaveAttribute(+ 'aria-disabled',+ 'true',+ )expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()})it('opens from the keyboard and restores focus to the date button on dismissal', async () => {const user = userEvent.setup()- render(<ToolDatePicker value="2024-05-01" onChange={vi.fn()} timezone="UTC" />)+ render(<ToolDatePicker aria-label="Select date" value="2024-05-01" onChange={vi.fn()} />)- const trigger = screen.getByRole('button', { name: 'Select date: May 1, 2024' })+ const trigger = screen.getByRole('button', { name: 'Select date May 1, 2024' })expect(within(trigger).queryByRole('button')).not.toBeInTheDocument()await user.tab()expect(trigger).toHaveFocus()@@ -80,7 +82,7 @@ describe('ToolDatePicker', () => {it('lets the keyboard reach and activate clear without opening the calendar', async () => {const user = userEvent.setup()const onChange = vi.fn()- render(<ToolDatePicker value="2024-05-01" onChange={onChange} timezone="UTC" />)+ render(<ToolDatePicker aria-label="Select date" value="2024-05-01" onChange={onChange} />)await user.tab()await user.tab()diff --git a/web/app/components/workflow/nodes/tool/components/__tests__/tool-date-range-picker.spec.tsx b/web/app/components/tools/parameters/__tests__/tool-date-range-picker.spec.tsxsimilarity index 82%rename from web/app/components/workflow/nodes/tool/components/__tests__/tool-date-range-picker.spec.tsxrename to web/app/components/tools/parameters/__tests__/tool-date-range-picker.spec.tsxindex b0405330c00..e10280a879f 100644--- a/web/app/components/workflow/nodes/tool/components/__tests__/tool-date-range-picker.spec.tsx+++ b/web/app/components/tools/parameters/__tests__/tool-date-range-picker.spec.tsx@@ -1,7 +1,7 @@import { fireEvent, render, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { describe, expect, it, vi } from 'vite-plus/test'-import ToolDateRangePicker from '../tool-date-range-picker'+import { ToolDateRangePicker } from '../tool-date-range-picker'vi.mock('react-i18next', async () => {const actual = await vi.importActual<typeof import('react-i18next')>('react-i18next')@@ -9,8 +9,6 @@ vi.mock('react-i18next', async () => {return {...actual,...createReactI18nextMock({- 'time.dateFormats.display': 'MMMM D, YYYY',- 'time.defaultPlaceholder': 'Select date','common.operation.clear': 'Clear','workflow.nodes.tool.dateRange.start': 'Start','workflow.nodes.tool.dateRange.end': 'End',@@ -24,23 +22,23 @@ describe('ToolDateRangePicker', () => {it('preserves stored date-only values when rendering in a negative timezone', () => {render(<ToolDateRangePicker+ label="Booking dates"value={JSON.stringify({ start: '2024-05-01', end: '2024-05-03' })}onChange={vi.fn()}- timezone="America/Los_Angeles"/>,)- expect(screen.getByRole('button', { name: 'Start date: May 1, 2024' })).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'End date: May 3, 2024' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Start date May 1, 2024' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'End date May 3, 2024' })).toBeInTheDocument()})it('clears one boundary without changing the other', () => {const onChange = vi.fn()render(<ToolDateRangePicker+ label="Booking dates"value={JSON.stringify({ start: '2024-05-01', end: '2024-05-03' })}onChange={onChange}- timezone="UTC"/>,)@@ -53,16 +51,16 @@ describe('ToolDateRangePicker', () => {const user = userEvent.setup()render(<ToolDateRangePicker+ label="Booking dates"value={JSON.stringify({ start: '2024-05-01', end: '2024-05-03' })}onChange={vi.fn()}- timezone="UTC"/>,)for (const name of [- 'Start date: May 1, 2024',+ 'Start date May 1, 2024','Start date: Clear',- 'End date: May 3, 2024',+ 'End date May 3, 2024','End date: Clear',]) {const button = screen.getByRole('button', { name })@@ -76,9 +74,9 @@ describe('ToolDateRangePicker', () => {const onChange = vi.fn()render(<ToolDateRangePicker+ label="Booking dates"value={JSON.stringify({ start: '2024-05-01' })}onChange={onChange}- timezone="UTC"/>,)diff --git a/web/app/components/tools/parameters/__tests__/tool-date-range-value.spec.ts b/web/app/components/tools/parameters/__tests__/tool-date-range-value.spec.tsnew file mode 100644index 00000000000..40d6c149ddc--- /dev/null+++ b/web/app/components/tools/parameters/__tests__/tool-date-range-value.spec.ts@@ -0,0 +1,20 @@+import { parseToolDateRangeValue, stringifyToolDateRangeValue } from '../tool-date-range-value'++it('round-trips the tool parameter JSON contract and clears empty ranges', () => {+ const value = { start: '2025-01-15', end: '2025-01-20' }+ expect(parseToolDateRangeValue(value)).toEqual(value)+ expect(parseToolDateRangeValue(stringifyToolDateRangeValue(value))).toEqual(value)+ expect(stringifyToolDateRangeValue({})).toBe('')+})++it('rejects invalid endpoints instead of passing them to the picker', () => {+ expect(parseToolDateRangeValue('{"start":"2025-02-30","end":"2025-03-01"}')).toEqual({+ start: undefined,+ end: '2025-03-01',+ })+})++it.each(['2025-01-15', '2025-01-15T12:00:00Z', '{', 'null'])(+ 'does not reinterpret unsupported stored data as a date range: %j',+ (value) => expect(parseToolDateRangeValue(value)).toEqual({}),+)diff --git a/web/app/components/tools/parameters/tool-date-picker.tsx b/web/app/components/tools/parameters/tool-date-picker.tsxnew file mode 100644index 00000000000..0178c1b6007--- /dev/null+++ b/web/app/components/tools/parameters/tool-date-picker.tsx@@ -0,0 +1,62 @@+'use client'++import type {+ DatePickerProps,+ DatePickerTriggerProps,+} from '@/app/components/base/date-time-picker/date-picker'+import { useTranslation } from 'react-i18next'+import {+ DatePicker,+ DatePickerClear,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+ DatePickerValue,+} from '@/app/components/base/date-time-picker/date-picker'+import { parseDateValue } from '@/app/components/base/date-time-picker/date-value'++type Props = Pick<DatePickerProps, 'placeholder' | 'readOnly' | 'minDate' | 'maxDate'> &+ Pick<DatePickerTriggerProps, 'aria-label' | 'aria-labelledby'> & {+ value: unknown+ onChange: (next: string) => void+ clearLabel?: string+ }++export function ToolDatePicker({+ value,+ onChange,+ 'aria-label': ariaLabel,+ 'aria-labelledby': ariaLabelledBy,+ placeholder,+ clearLabel,+ readOnly = false,+ minDate,+ maxDate,+}: Props) {+ const { t } = useTranslation(['common'])+ return (+ <DatePicker+ value={parseDateValue(value) ?? null}+ onValueChange={(next) => onChange(next ?? '')}+ placeholder={placeholder}+ readOnly={readOnly}+ minDate={parseDateValue(minDate)}+ maxDate={parseDateValue(maxDate)}+ >+ {!ariaLabelledBy && <DatePickerLabel className="sr-only">{ariaLabel}</DatePickerLabel>}+ <div className="flex w-full min-w-0 items-center rounded-lg bg-components-input-bg-normal">+ <DatePickerTrigger aria-labelledby={ariaLabelledBy} className="min-w-0 flex-1 px-2">+ <span+ className="i-ri-calendar-line size-4 shrink-0 text-text-tertiary"+ aria-hidden="true"+ />+ <DatePickerValue className="min-w-0 flex-1 truncate" />+ </DatePickerTrigger>+ <DatePickerClear+ aria-label={clearLabel ?? t(($) => $['operation.clear'], { ns: 'common' })}+ />+ </div>+ <DatePickerContent aria-labelledby={ariaLabelledBy} />+ </DatePicker>+ )+}diff --git a/web/app/components/tools/parameters/tool-date-range-picker.tsx b/web/app/components/tools/parameters/tool-date-range-picker.tsxnew file mode 100644index 00000000000..233d40a6f2d--- /dev/null+++ b/web/app/components/tools/parameters/tool-date-range-picker.tsx@@ -0,0 +1,52 @@+'use client'++import type { FC } from 'react'+import { useTranslation } from 'react-i18next'+import { ToolDatePicker } from './tool-date-picker'+import { parseToolDateRangeValue, stringifyToolDateRangeValue } from './tool-date-range-value'++type Props = {+ label: string+ value: unknown+ onChange: (next: string) => void+ readOnly?: boolean+}++export const ToolDateRangePicker: FC<Props> = ({ label, value, onChange, readOnly = false }) => {+ const { t } = useTranslation(['workflow', 'common'])+ const startLabel = t(($) => $['nodes.tool.dateRange.startPlaceholder'], { ns: 'workflow' })+ const endLabel = t(($) => $['nodes.tool.dateRange.endPlaceholder'], { ns: 'workflow' })+ const clearLabel = t(($) => $['operation.clear'], { ns: 'common' })+ const parsed = parseToolDateRangeValue(value)++ const patch = (partial: Partial<{ start?: string; end?: string }>) => {+ const next = { ...parsed, ...partial }+ if (!next.start) delete next.start+ if (!next.end) delete next.end+ onChange(stringifyToolDateRangeValue(next))+ }++ return (+ <div role="group" aria-label={label} className="flex min-w-0 items-center gap-1">+ <ToolDatePicker+ aria-label={startLabel}+ clearLabel={`${startLabel}: ${clearLabel}`}+ value={parsed.start}+ onChange={(start) => patch({ start: start || undefined })}+ readOnly={readOnly}+ maxDate={parsed.end || undefined}+ placeholder={startLabel}+ />+ <span aria-hidden="true">–</span>+ <ToolDatePicker+ aria-label={endLabel}+ clearLabel={`${endLabel}: ${clearLabel}`}+ value={parsed.end}+ onChange={(end) => patch({ end: end || undefined })}+ readOnly={readOnly}+ minDate={parsed.start || undefined}+ placeholder={endLabel}+ />+ </div>+ )+}diff --git a/web/app/components/tools/parameters/tool-date-range-value.ts b/web/app/components/tools/parameters/tool-date-range-value.tsnew file mode 100644index 00000000000..9c3251953f8--- /dev/null+++ b/web/app/components/tools/parameters/tool-date-range-value.ts@@ -0,0 +1,28 @@+import { parseDateValue } from '@/app/components/base/date-time-picker/date-value'++export type ToolDateRangeStored = {+ start?: string+ end?: string+}++export function parseToolDateRangeValue(raw: unknown): ToolDateRangeStored {+ let value: unknown = raw+ if (typeof value === 'string') {+ try {+ value = JSON.parse(value)+ } catch {+ return {}+ }+ }+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}+ const range = value as Record<string, unknown>+ return { start: parseDateValue(range.start), end: parseDateValue(range.end) }+}++export function stringifyToolDateRangeValue(v: ToolDateRangeStored): string {+ const out: ToolDateRangeStored = {}+ if (v.start) out.start = v.start+ if (v.end) out.end = v.end+ if (!out.start && !out.end) return ''+ return JSON.stringify(out)+}diff --git a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx b/web/app/components/workflow/nodes/_base/components/form-input-item.tsxindex ed549b833f8..9a3a550fcd1 100644--- a/web/app/components/workflow/nodes/_base/components/form-input-item.tsx+++ b/web/app/components/workflow/nodes/_base/components/form-input-item.tsx@@ -17,20 +17,18 @@ import {SelectItemText,SelectTrigger,} from '@langgenius/dify-ui/select'-import { useSuspenseQuery } from '@tanstack/react-query'import { useEffect, useMemo, useState } from 'react'import { CheckboxList } from '@/app/components/base/checkbox-list'import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'import { AppSelector } from '@/app/components/plugins/plugin-detail-panel/app-selector'import ModelParameterModal from '@/app/components/plugins/plugin-detail-panel/model-selector'import { PluginCategoryEnum } from '@/app/components/plugins/types'+import { ToolDatePicker } from '@/app/components/tools/parameters/tool-date-picker'+import { ToolDateRangePicker } from '@/app/components/tools/parameters/tool-date-range-picker'import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'import MixedVariableTextInput from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input'-import ToolDatePicker from '@/app/components/workflow/nodes/tool/components/tool-date-picker'-import ToolDateRangePicker from '@/app/components/workflow/nodes/tool/components/tool-date-range-picker'import { VarType } from '@/app/components/workflow/types'-import { userProfileQueryOptions } from '@/features/account-profile/client'import { useFetchDynamicOptions } from '@/service/use-plugins'import { useTriggerPluginDynamicOptions } from '@/service/use-triggers'import { VarKindType } from '../types'@@ -57,7 +55,6 @@ type Props = Readonly<{schema: FormInputSchemavalue: ResourceVarInputsonChange: (value: ResourceVarInputs) => void- inPanel?: booleancurrentTool?: Tool | EventcurrentProvider?: ToolWithProvider | TriggerWithProvidershowManageInputField?: boolean@@ -92,14 +89,8 @@ const FormInputItem: FC<Props> = ({providerType,staticSchema = false,disableVariableInsertion = false,- inPanel,}) => {const language = useLanguage()- const { data: userProfile } = useSuspenseQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile,- })- const timezone = userProfile.timezone ?? 'UTC'const [toolsOptions, setToolsOptions] = useState<FormOption[] | null>(null)const [isLoadingToolsOptions, setIsLoadingToolsOptions] = useState(false)@@ -360,9 +351,9 @@ const FormInputItem: FC<Props> = ({{isDate && isConstant && (<div className="min-w-0 grow"><ToolDatePicker+ aria-labelledby={labelId}value={varInput?.value}onChange={handleValueChange}- timezone={timezone}readOnly={readOnly}placeholder={placeholder?.[language] || placeholder?.en_US}/>@@ -371,11 +362,10 @@ const FormInputItem: FC<Props> = ({{isDateRange && varInput?.type !== VarKindType.variable && (<div className="min-w-0 grow"><ToolDateRangePicker+ label={schema.label?.[language] || schema.label?.en_US || variable}value={varInput?.value}onChange={handleValueChange}readOnly={readOnly}- timezone={timezone}- inPanel={inPanel}/></div>)}diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsxindex d7befdc9bb9..033eab299ee 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/integration.spec.tsx@@ -743,7 +743,7 @@ describe('knowledge-retrieval path', () => {fireEvent.click(container.querySelector('.ml-1.mt-1') as Element)expect(onSelect).toHaveBeenCalledWith(MetadataComparisonOperator.is as ComparisonOperator)- expect(onDateChange).toHaveBeenCalledWith()+ expect(onDateChange).toHaveBeenCalledWith(undefined)expect(onUpdateCondition).toHaveBeenCalledWith('condition-1',expect.objectContaining({ value: 'updated-agent' }),diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/__tests__/condition-date.spec.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/__tests__/condition-date.spec.tsxnew file mode 100644index 00000000000..5f993b3fe8f--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/__tests__/condition-date.spec.tsx@@ -0,0 +1,20 @@+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'+import ConditionDate from '../condition-date'++it('disables both selecting and clearing an unavailable metadata condition', async () => {+ const user = userEvent.setup()+ const changed = vi.fn()+ render(<ConditionDate value={1736947800} onChange={changed} disabled />, {+ wrapper: createAccountProfileQueryWrapper(),+ })+ const trigger = screen.getByRole('button', { name: /datePlaceholder/ })+ const clear = screen.getByRole('button', { name: 'common.operation.clear' })+ expect(trigger).toBeDisabled()+ expect(clear).toBeDisabled()+ await user.click(trigger)+ await user.click(clear)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(changed).not.toHaveBeenCalled()+})diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-date.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-date.tsxindex 95a919f6327..bc7283971f0 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-date.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-date.tsx@@ -1,92 +1,39 @@-import type { DatePickerProps } from '@/app/components/base/date-and-time-picker/types'-import { cn } from '@langgenius/dify-ui/cn'-import { RiCalendarLine, RiCloseCircleFill } from '@remixicon/react'import { useQuery } from '@tanstack/react-query'-import dayjs from 'dayjs'-import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'+import {+ DateTimePicker,+ DateTimePickerClear,+ DateTimePickerContent,+ DateTimePickerLabel,+ DateTimePickerTrigger,+} from '@/app/components/base/date-time-picker/date-time-picker'import { userProfileQueryOptions } from '@/features/account-profile/client'-type ConditionDateProps = {- value?: number- onChange: (date?: number) => void-}-const ConditionDate = ({ value, onChange }: ConditionDateProps) => {- const { t } = useTranslation(['common', 'workflow', 'workflowModels'])- const { data: timezone } = useQuery({+type ConditionDateProps = { value?: number; disabled?: boolean; onChange: (date?: number) => void }+function ConditionDate({ value, disabled, onChange }: ConditionDateProps) {+ const { t } = useTranslation(['common', 'workflowModels'])+ const { data: timezone = 'UTC' } = useQuery({...userProfileQueryOptions(),- select: (data) => data.profile.timezone ?? undefined,+ select: (data) => data.profile.timezone || 'UTC',+ })+ const label = t(($) => $['nodes.knowledgeRetrieval.metadata.panel.datePlaceholder'], {+ ns: 'workflowModels',})-- const handleDateChange = useCallback(- (date?: dayjs.Dayjs) => {- if (date) onChange(date.unix())- else onChange()- },- [onChange],- )-- const renderTrigger = useCallback<NonNullable<DatePickerProps['renderTrigger']>>(- (props) => {- const hasValue = Boolean(value)- const triggerText = value- ? dayjs(value * 1000)- .tz(timezone)- .format('MMMM DD YYYY HH:mm A')- : t(($) => $['nodes.knowledgeRetrieval.metadata.panel.datePlaceholder'], {- ns: 'workflowModels',- })-- return (- <div className={cn('group flex items-center', props.className)}>- <button- {...props}- type="button"- className={cn(- 'mr-0.5 flex h-6 grow cursor-pointer items-center border-none bg-transparent px-1 py-0 text-left system-sm-regular focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden',- hasValue ? 'text-text-secondary' : 'text-text-tertiary',- )}- >- <span className="grow">{triggerText}</span>- <RiCalendarLine- className={cn(- 'block size-4 shrink-0',- hasValue ? 'text-text-quaternary' : 'text-text-tertiary',- )}- aria-hidden="true"- />- </button>- {hasValue ? (- <button- type="button"- aria-label={t(($) => $['operation.clear'], { ns: 'common' })}- className="size-4 shrink-0 cursor-pointer border-none bg-transparent p-0 text-text-quaternary opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 hover:text-components-input-text-filled focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden [@media(hover:none)]:opacity-100"- onClick={(e) => {- e.stopPropagation()- handleDateChange()- }}- >- <RiCloseCircleFill className="size-4" aria-hidden="true" />- </button>- ) : null}- </div>- )- },- [value, handleDateChange, timezone, t],- )-return (- <div className="h-8 px-2 py-1">- <DatePicker- timezone={timezone}- value={value ? dayjs(value * 1000) : undefined}- onChange={handleDateChange}- onClear={handleDateChange}- renderTrigger={renderTrigger}- />- </div>+ <DateTimePicker+ disabled={disabled}+ placeholder={label}+ timeZone={timezone}+ value={value === undefined ? null : new Date(value * 1000)}+ onValueChange={(next) => onChange(next ? Math.floor(next.getTime() / 1000) : undefined)}+ >+ <DateTimePickerLabel className="sr-only">{label}</DateTimePickerLabel>+ <div className="flex items-center px-2">+ <DateTimePickerTrigger className="min-w-0 flex-1 bg-transparent px-1" />+ <DateTimePickerClear aria-label={t(($) => $['operation.clear'], { ns: 'common' })} />+ </div>+ <DateTimePickerContent />+ </DateTimePicker>)}-export default ConditionDatediff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-item.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-item.tsxindex 276e83f095b..b0139f2a487 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-item.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-item.tsx@@ -196,7 +196,11 @@ const ConditionItem = ({)}{!comparisonOperatorNotRequireValue(condition.comparison_operator) &¤tMetadata?.type === MetadataFilteringVariableType.time && (- <ConditionDate value={condition.value as number} onChange={handleValueChange} />+ <ConditionDate+ disabled={disabled}+ value={condition.value as number}+ onChange={handleValueChange}+ />)}</div></div>diff --git a/web/app/components/workflow/nodes/tool/components/tool-date-picker.tsx b/web/app/components/workflow/nodes/tool/components/tool-date-picker.tsxdeleted file mode 100644index b0f608dec34..00000000000--- a/web/app/components/workflow/nodes/tool/components/tool-date-picker.tsx+++ /dev/null@@ -1,110 +0,0 @@-'use client'--import type { FC } from 'react'-import type {- DatePickerProps,- TriggerProps,-} from '@/app/components/base/date-and-time-picker/types'-import { cn } from '@langgenius/dify-ui/cn'-import { noop } from 'es-toolkit/function'-import { useCallback } from 'react'-import { useTranslation } from 'react-i18next'-import { useLocale } from '#i18n'-import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'-import { toDayjs } from '@/app/components/base/date-and-time-picker/utils/dayjs'-import { formatToLocalTime } from '@/utils/format'--const DATE_FMT = 'YYYY-MM-DD'--type Props = Readonly<{- value: unknown- onChange: (next: string) => void- timezone: string- placeholder?: string- readOnly?: boolean-}>--const ToolDatePicker: FC<Props> = ({- value,- onChange,- timezone,- placeholder,- readOnly = false,-}) => {- const { t } = useTranslation(['common', 'time'])- const locale = useLocale()- const displayFormat = t(($) => $['dateFormats.display'], { ns: 'time' })- const resolvedPlaceholder = placeholder || t(($) => $['operation.pickDate'], { ns: 'time' })- const rawValue = typeof value === 'string' ? value : ''- const parsedValue = toDayjs(rawValue, { timezone, format: DATE_FMT })-- const renderTrigger = useCallback<NonNullable<DatePickerProps['renderTrigger']>>(- (props, _state, { value: date, handleClear }: TriggerProps) => {- const displayValue = date ? formatToLocalTime(date, locale, displayFormat) : ''- const triggerLabel = resolvedPlaceholder- ? `${resolvedPlaceholder}${displayValue ? `: ${displayValue}` : ''}`- : displayValue-- return (- <div className="group/date-trigger relative w-full min-w-0">- <button- {...props}- type="button"- aria-label={triggerLabel}- className={cn(- 'flex h-8 w-full min-w-0 cursor-pointer items-center space-x-0.5 rounded-lg bg-components-input-bg-normal px-2 text-left system-sm-regular text-components-input-text-filled hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover',- readOnly && 'cursor-default opacity-60 hover:bg-components-input-bg-normal',- props.className,- )}- >- <span className="shrink-0 p-px">- <span- className="i-ri-calendar-line block size-3.5 text-text-tertiary"- aria-hidden="true"- />- </span>- <span- className={cn(- 'min-w-0 flex-1 truncate px-1',- !date && 'text-components-input-text-placeholder',- date && 'pr-5',- )}- >- {displayValue || resolvedPlaceholder}- </span>- </button>- {date && !readOnly && (- <button- type="button"- aria-label={t(($) => $['operation.clear'], { ns: 'common' })}- className="pointer-events-none absolute top-1/2 right-2 z-1 flex size-4 -translate-y-1/2 items-center justify-center rounded border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg text-text-tertiary opacity-0 shadow-xs group-focus-within/date-trigger:pointer-events-auto group-focus-within/date-trigger:opacity-100 group-hover/date-trigger:pointer-events-auto group-hover/date-trigger:opacity-100 hover:bg-components-button-secondary-bg-hover hover:text-text-secondary [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"- onClick={(event) => {- handleClear(event)- onChange('')- }}- >- <span className="i-ri-close-circle-fill size-3.5" aria-hidden="true" />- </button>- )}- </div>- )- },- [displayFormat, locale, onChange, readOnly, resolvedPlaceholder, t],- )-- return (- <DatePicker- disabled={readOnly}- value={parsedValue}- timezone={timezone}- onChange={(date) => onChange(date?.format(DATE_FMT) ?? '')}- onClear={noop}- renderTrigger={renderTrigger}- triggerWrapClassName="w-full min-w-0"- needTimePicker={false}- noConfirm- />- )-}--export default ToolDatePickerdiff --git a/web/app/components/workflow/nodes/tool/components/tool-date-range-picker.tsx b/web/app/components/workflow/nodes/tool/components/tool-date-range-picker.tsxdeleted file mode 100644index a67db8b73a9..00000000000--- a/web/app/components/workflow/nodes/tool/components/tool-date-range-picker.tsx+++ /dev/null@@ -1,55 +0,0 @@-'use client'--import type { Dayjs } from 'dayjs'-import type { FC } from 'react'-import { useTranslation } from 'react-i18next'-import DateRangePicker from '@/app/components/base/date-and-time-picker/date-range-picker'-import { toDayjs as parseDayjs } from '@/app/components/base/date-and-time-picker/utils/dayjs'-import { parseToolDateRangeValue, stringifyToolDateRangeValue } from './tool-date-range-value'--const DATE_FMT = 'YYYY-MM-DD'--const toDayjs = (raw?: string, timezone?: string): Dayjs | undefined => {- if (!raw) return undefined- return parseDayjs(raw, { timezone, format: DATE_FMT })-}--type Props = {- value: unknown- onChange: (next: string) => void- readOnly?: boolean- timezone: string- inPanel?: boolean-}--const ToolDateRangePicker: FC<Props> = ({ value, onChange, readOnly = false, timezone }) => {- const { t } = useTranslation(['time', 'workflow'])- const parsed = parseToolDateRangeValue(value)-- const patch = (partial: Partial<{ start?: string; end?: string }>) => {- const next = { ...parsed, ...partial }- if (!next.start) delete next.start- if (!next.end) delete next.end- onChange(stringifyToolDateRangeValue(next))- }-- return (- <div className="min-w-0">- <DateRangePicker- className="max-w-full"- start={toDayjs(parsed.start, timezone)}- end={toDayjs(parsed.end, timezone)}- timezone={timezone}- displayFormat={t(($) => $['dateFormats.display'], { ns: 'time' })}- startPlaceholder={t(($) => $['nodes.tool.dateRange.startPlaceholder'], { ns: 'workflow' })}- endPlaceholder={t(($) => $['nodes.tool.dateRange.endPlaceholder'], { ns: 'workflow' })}- onStartChange={(date) => patch({ start: date?.format(DATE_FMT) })}- onEndChange={(date) => patch({ end: date?.format(DATE_FMT) })}- clearable- disabled={readOnly}- />- </div>- )-}--export default ToolDateRangePickerdiff --git a/web/app/components/workflow/nodes/tool/components/tool-date-range-value.ts b/web/app/components/workflow/nodes/tool/components/tool-date-range-value.tsdeleted file mode 100644index 797567e21ca..00000000000--- a/web/app/components/workflow/nodes/tool/components/tool-date-range-value.ts+++ /dev/null@@ -1,36 +0,0 @@-export type ToolDateRangeStored = {- start?: string- end?: string-}--export function parseToolDateRangeValue(raw: unknown): ToolDateRangeStored {- if (raw === null || raw === undefined || raw === '') return {}- if (typeof raw === 'object' && !Array.isArray(raw)) {- const o = raw as Record<string, unknown>- return {- start: typeof o.start === 'string' && o.start ? o.start : undefined,- end: typeof o.end === 'string' && o.end ? o.end : undefined,- }- }- if (typeof raw === 'string') {- const trimmed = raw.trim()- if (!trimmed) return {}- try {- const parsed = JSON.parse(trimmed) as unknown- if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))- return parseToolDateRangeValue(parsed)- } catch {- // legacy single-day value from the earlier date-range implementation- }- if (/^\d{4}-\d{2}-\d{2}/.test(trimmed)) return { start: trimmed, end: undefined }- }- return {}-}--export function stringifyToolDateRangeValue(v: ToolDateRangeStored): string {- const out: ToolDateRangeStored = {}- if (v.start) out.start = v.start- if (v.end) out.end = v.end- if (!out.start && !out.end) return ''- return JSON.stringify(out)-}diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsxindex 59ee2e46819..0f629f48763 100644--- a/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx@@ -11,7 +11,6 @@ type MockToolFormItemProps = {schema: CredentialFormSchemavalue: ResourceVarInputsonChange: (value: ResourceVarInputs) => void- inPanel?: booleanshowManageInputField?: booleanonManageInputField?: () => voidextraParams?: Record<string, unknown>@@ -74,7 +73,6 @@ describe('tool/tool-form', () => {]}value={value}onChange={handleChange}- inPanelshowManageInputFieldonManageInputField={handleManageInputField}extraParams={{ mode: 'panel' }}@@ -90,7 +88,6 @@ describe('tool/tool-form', () => {schema: expect.objectContaining({ variable: 'api_key' }),value,onChange: handleChange,- inPanel: true,showManageInputField: true,onManageInputField: handleManageInputField,extraParams: { mode: 'panel' },diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/index.tsxindex 0e23a91042f..e1658481c75 100644--- a/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx+++ b/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx@@ -14,7 +14,6 @@ type Props = Readonly<{value: ResourceVarInputsonChange: (value: ResourceVarInputs) => voidonOpen?: (index: number) => void- inPanel?: booleancurrentTool?: ToolcurrentProvider?: ToolWithProvidershowManageInputField?: boolean@@ -29,7 +28,6 @@ const ToolForm: FC<Props> = ({schema,value,onChange,- inPanel,currentTool,currentProvider,showManageInputField,@@ -47,7 +45,6 @@ const ToolForm: FC<Props> = ({schema={schema}value={value}onChange={onChange}- inPanel={inPanel}currentTool={currentTool}currentProvider={currentProvider}showManageInputField={showManageInputField}diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsxindex 2c1d10e54b2..76720e1cbce 100644--- a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx+++ b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx@@ -55,7 +55,6 @@ type Props = Readonly<{schema: FormInputSchemavalue: ResourceVarInputsonChange: (value: ResourceVarInputs) => void- inPanel?: booleancurrentTool?: ToolcurrentProvider?: ToolWithProvidershowManageInputField?: boolean@@ -71,7 +70,6 @@ const ToolFormItem: FC<Props> = ({schema,value,onChange,- inPanel,currentTool,currentProvider,showManageInputField,@@ -140,7 +138,6 @@ const ToolFormItem: FC<Props> = ({schema={schema}value={value}onChange={onChange}- inPanel={inPanel}currentTool={currentTool}currentProvider={currentProvider}showManageInputField={showManageInputField}diff --git a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/index.tsx b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/index.tsxindex e7257d7b124..d3f941e8608 100644--- a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/index.tsx+++ b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/index.tsx@@ -13,7 +13,6 @@ type Props = Readonly<{value: PluginTriggerVarInputsonChange: (value: PluginTriggerVarInputs) => voidonOpen?: (index: number) => void- inPanel?: booleancurrentEvent?: EventcurrentProvider?: TriggerWithProviderextraParams?: Record<string, any>@@ -26,7 +25,6 @@ const TriggerForm: FC<Props> = ({schema,value,onChange,- inPanel,currentEvent,currentProvider,extraParams,@@ -42,7 +40,6 @@ const TriggerForm: FC<Props> = ({schema={schema}value={value}onChange={onChange}- inPanel={inPanel}currentEvent={currentEvent}currentProvider={currentProvider}extraParams={extraParams}diff --git a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsxindex 54382ac837c..b21883110d7 100644--- a/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx+++ b/web/app/components/workflow/nodes/trigger-plugin/components/trigger-form/item.tsx@@ -18,7 +18,6 @@ type Props = Readonly<{schema: CredentialFormSchemavalue: PluginTriggerVarInputsonChange: (value: PluginTriggerVarInputs) => void- inPanel?: booleancurrentEvent?: EventcurrentProvider?: TriggerWithProviderextraParams?: Record<string, unknown>@@ -31,7 +30,6 @@ const TriggerFormItem: FC<Props> = ({schema,value,onChange,- inPanel,currentEvent,currentProvider,extraParams,@@ -94,7 +92,6 @@ const TriggerFormItem: FC<Props> = ({schema={schema}value={value}onChange={onChange}- inPanel={inPanel}currentTool={currentEvent}currentProvider={currentProvider}providerType="trigger"diff --git a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsxindex c094ac2559c..d2a0d5a4a41 100644--- a/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/trigger-schedule/__tests__/panel.spec.tsx@@ -119,14 +119,28 @@ describe('TriggerSchedulePanel', () => {// The panel should wire the visual and cron controls back to the schedule config handlers.describe('Panel Wiring', () => {+ it('prevents time editing when the workflow is read only', async () => {+ const user = userEvent.setup()+ mockUseConfig.mockReturnValue({ ...mockUseConfig('node-1', createData()), readOnly: true })+ renderPanel('node-1', createData())+ const trigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })+ await user.click(trigger)+ expect(trigger).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(handleTimeChange).not.toHaveBeenCalled()+ })it('should render the visual controls and forward their callbacks', async () => {const user = userEvent.setup()renderPanel('node-1', createData())await user.click(screen.getByRole('button', { name: 'visual' }))await user.click(screen.getByRole('button', { name: 'daily' }))- await user.click(screen.getByDisplayValue('11:30 AM'))- await user.click(screen.getAllByText('02')[0]!)+ await user.click(screen.getByText('workflow.nodes.triggerSchedule.time', { exact: true }))+ const timeTrigger = screen.getByRole('button', { name: /11:30 AM.*UTC/ })+ expect(timeTrigger).toHaveFocus()+ expect(timeTrigger).toHaveAttribute('aria-expanded', 'false')+ await user.keyboard('{Enter}')+ await user.click(screen.getByRole('option', { name: '2' }))await user.click(screen.getByText('45'))await user.click(screen.getByText('PM'))await user.click(screen.getByRole('button', { name: /operation\.ok/i }))@@ -228,7 +242,7 @@ describe('TriggerSchedulePanel', () => {const { rerender } = renderPanel('node-6', createData({ frequency: undefined }) as any)expect(screen.getByRole('button', { name: 'daily' })).toBeInTheDocument()- expect(screen.getByDisplayValue('11:30 AM')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /11:30 AM/ })).toBeInTheDocument()mockUseConfig.mockReturnValueOnce({readOnly: false,diff --git a/web/app/components/workflow/nodes/trigger-schedule/panel.tsx b/web/app/components/workflow/nodes/trigger-schedule/panel.tsxindex ec6e6a26b65..8a459aa4f18 100644--- a/web/app/components/workflow/nodes/trigger-schedule/panel.tsx+++ b/web/app/components/workflow/nodes/trigger-schedule/panel.tsx@@ -5,7 +5,13 @@ import { Field, FieldLabel } from '@langgenius/dify-ui/field'import { Input } from '@langgenius/dify-ui/input'import * as React from 'react'import { useTranslation } from 'react-i18next'-import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'+import {+ TimePicker,+ TimePickerContent,+ TimePickerLabel,+ TimePickerTrigger,+ TimePickerValue,+} from '@/app/components/base/date-time-picker/time-picker'import WorkflowField from '@/app/components/workflow/nodes/_base/components/field'import FrequencySelector from './components/frequency-selector'import ModeToggle from './components/mode-toggle'@@ -14,13 +20,14 @@ import NextExecutionTimes from './components/next-execution-times'import OnMinuteSelector from './components/on-minute-selector'import WeekdaySelector from './components/weekday-selector'import useConfig from './use-config'+import { formatClockTime, parseClockTime } from './utils/clock-time'const i18nPrefix = 'nodes.triggerSchedule'const Panel: FC<NodePanelProps<ScheduleTriggerNodeType>> = ({ id, data }) => {const { t } = useTranslation(['workflow', 'workflowIntegrations'])- const timeInputId = React.useId()const {+ readOnly,inputs,setInputs,handleModeChange,@@ -53,31 +60,31 @@ const Panel: FC<NodePanelProps<ScheduleTriggerNodeType>> = ({ id, data }) => {onChange={handleOnMinuteChange}/>) : (- <Field className="gap-0">- <FieldLabel htmlFor={timeInputId} className="text-xs">- {t(($) => $['nodes.triggerSchedule.time'], { ns: 'workflow' })}- </FieldLabel>+ <div className="flex flex-col"><TimePicker- id={timeInputId}- notClearable={true}- timezone={inputs.timezone}- value={inputs.visual_config?.time || '12:00 AM'}- triggerFullWidth={true}- onChange={(time) => {- if (time) {- const timeString = time.format('h:mm A')- handleTimeChange(timeString)- }+ readOnly={readOnly}+ timeZone={inputs.timezone}+ value={parseClockTime(inputs.visual_config?.time || '12:00 AM')}+ onValueChange={(time) => {+ if (time) handleTimeChange(formatClockTime(time))}}- onClear={() => {- handleTimeChange('12:00 AM')- }}- placeholder={t(($) => $['nodes.triggerSchedule.selectTime'], {- ns: 'workflowIntegrations',- })}- showTimezone={true}- />- </Field>+ >+ <TimePickerLabel className="text-xs">+ {t(($) => $['nodes.triggerSchedule.time'], { ns: 'workflow' })}+ </TimePickerLabel>+ <TimePickerTrigger className="w-full">+ <TimePickerValue className="flex flex-1 items-center justify-between">+ {(value) => (+ <>+ {value}+ <span className="text-text-tertiary">{inputs.timezone}</span>+ </>+ )}+ </TimePickerValue>+ </TimePickerTrigger>+ <TimePickerContent />+ </TimePicker>+ </div>)}</div></div>diff --git a/web/app/components/workflow/nodes/trigger-schedule/utils/clock-time.ts b/web/app/components/workflow/nodes/trigger-schedule/utils/clock-time.tsnew file mode 100644index 00000000000..9a782db50d8--- /dev/null+++ b/web/app/components/workflow/nodes/trigger-schedule/utils/clock-time.ts@@ -0,0 +1,10 @@+export function parseClockTime(value: string): string {+ const match = /^(\d{1,2}):(\d{2})\s*(AM|PM)$/i.exec(value)+ if (!match) return '00:00'+ const hour = (Number(match[1]) % 12) + (match[3]!.toUpperCase() === 'PM' ? 12 : 0)+ return `${String(hour).padStart(2, '0')}:${match[2]}`+}+export function formatClockTime(value: string): string {+ const hour = Number(value.slice(0, 2))+ return `${hour % 12 || 12}:${value.slice(3)} ${hour < 12 ? 'AM' : 'PM'}`+}diff --git a/web/app/components/workflow/nodes/trigger-schedule/utils/execution-time-calculator.ts b/web/app/components/workflow/nodes/trigger-schedule/utils/execution-time-calculator.tsindex 9d8536c0352..90d5b66093c 100644--- a/web/app/components/workflow/nodes/trigger-schedule/utils/execution-time-calculator.ts+++ b/web/app/components/workflow/nodes/trigger-schedule/utils/execution-time-calculator.ts@@ -1,5 +1,5 @@import type { ScheduleTriggerNodeType } from '../types'-import { convertTimezoneToOffsetStr } from '@/app/components/base/date-and-time-picker/utils/dayjs'+import { convertTimezoneToOffsetStr } from '@/utils/timezone'import { isValidCronExpression, parseCronExpression } from './cron-parser'const DEFAULT_TIMEZONE = 'UTC'diff --git a/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx b/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsxindex 4b057fa56b8..8f59e71d305 100644--- a/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx+++ b/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx@@ -1,9 +1,7 @@'use client'import type { Dayjs } from 'dayjs'-import type { DatePickerProps } from '@/app/components/base/date-and-time-picker/types'import type { I18nKeysWithPrefix } from '@/types/i18n'-import { cn } from '@langgenius/dify-ui/cn'import {Select,SelectContent,@@ -13,11 +11,10 @@ import {SelectTrigger,} from '@langgenius/dify-ui/select'import dayjs from 'dayjs'-import { noop } from 'es-toolkit/function'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { useLocale } from '#i18n'-import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'+import { MonitoringDateRangePicker } from '@/features/monitoring/date-range-picker'import { formatToLocalTime } from '@/utils/format'export type AgentMonitoringPeriod = {@@ -41,7 +38,6 @@ type AgentMonitoringTimeRangePickerProps = {onChange: (period: AgentMonitoringPeriod) => void}-const today = dayjs()const queryDateFormat = 'YYYY-MM-DD HH:mm'const timeRangeOptions: TimeRangeOption[] = [@@ -51,6 +47,7 @@ const timeRangeOptions: TimeRangeOption[] = []const getRangePeriod = (option: TimeRangeOption): AgentMonitoringPeriod => {+ const today = dayjs()const end = today.endOf('day')const start =option.days === 0 ? today.startOf('day') : today.subtract(option.days, 'day').startOf('day')@@ -64,78 +61,6 @@ const getRangePeriod = (option: TimeRangeOption): AgentMonitoringPeriod => {}}-function DateRangePart({- start,- end,- onStartChange,- onEndChange,-}: {- start: Dayjs- end: Dayjs- onStartChange: (date?: Dayjs) => void- onEndChange: (date?: Dayjs) => void-}) {- const locale = useLocale()-- const renderDate: DatePickerProps['renderTrigger'] = (props, _state, { value }) => (- <button- {...props}- type="button"- className={cn(- 'flex h-7 cursor-pointer items-center rounded-lg px-1 system-sm-regular text-components-input-text-filled hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover',- props.className,- )}- >- {value ? formatToLocalTime(value, locale, 'MMM D') : ''}- </button>- )-- const availableStartDate = end.subtract(30, 'day')- const isStartDateDisabled = (date: Dayjs) => {- if (date.isAfter(today, 'date')) return true-- return !(- (date.isAfter(availableStartDate, 'date') || date.isSame(availableStartDate, 'date')) &&- (date.isBefore(end, 'date') || date.isSame(end, 'date'))- )- }-- const availableEndDate = start.add(30, 'day')- const isEndDateDisabled = (date: Dayjs) => {- if (date.isAfter(today, 'date')) return true-- return !(- (date.isAfter(start, 'date') || date.isSame(start, 'date')) &&- (date.isBefore(availableEndDate, 'date') || date.isSame(availableEndDate, 'date'))- )- }-- return (- <div className="flex h-8 items-center space-x-0.5 rounded-lg bg-components-input-bg-normal px-2">- <span aria-hidden className="i-ri-calendar-line size-3.5 text-text-tertiary" />- <DatePicker- value={start}- onChange={onStartChange}- renderTrigger={renderDate}- needTimePicker={false}- onClear={noop}- noConfirm- getIsDateDisabled={isStartDateDisabled}- />- <span className="system-sm-regular text-text-tertiary">-</span>- <DatePicker- value={end}- onChange={onEndChange}- renderTrigger={renderDate}- needTimePicker={false}- onClear={noop}- noConfirm- getIsDateDisabled={isEndDateDisabled}- />- </div>- )-}-export function AgentMonitoringTimeRangePicker({value,onChange,@@ -216,7 +141,7 @@ export function AgentMonitoringTimeRangePicker({aria-hiddenclassName="i-custom-vender-other-hourglass-shape h-3.5 w-2 text-components-input-bg-normal"/>- <DateRangePart+ <MonitoringDateRangePickerstart={start}end={end}onStartChange={handleDateChange('start')}diff --git a/web/features/monitoring/__tests__/date-range-picker.spec.tsx b/web/features/monitoring/__tests__/date-range-picker.spec.tsxnew file mode 100644index 00000000000..05ae2be159e--- /dev/null+++ b/web/features/monitoring/__tests__/date-range-picker.spec.tsx@@ -0,0 +1,49 @@+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import dayjs from 'dayjs'+import { MonitoringDateRangePicker } from '../date-range-picker'++it('limits monitoring ranges to 30 days and updates only the selected endpoint', async () => {+ vi.setSystemTime(new Date('2025-02-28T12:00:00Z'))+ try {+ const user = userEvent.setup()+ const startChanged = vi.fn()+ const endChanged = vi.fn()+ render(+ <MonitoringDateRangePicker+ start={dayjs('2025-01-01')}+ end={dayjs('2025-01-20')}+ onStartChange={startChanged}+ onEndChange={endChanged}+ />,+ )+ await user.click(screen.getByRole('button', { name: /picker.endDate/ }))+ expect(screen.getByRole('button', { name: /picker.nextMonth/ })).toBeDisabled()+ await user.click(screen.getByRole('button', { name: /January 31st, 2025/ }))+ expect(endChanged).toHaveBeenCalledOnce()+ expect(endChanged.mock.calls[0]![0].format('YYYY-MM-DD')).toBe('2025-01-31')+ expect(startChanged).not.toHaveBeenCalled()+ } finally {+ vi.useRealTimers()+ }+})++it('disallows future dates even when they fit within the 30-day range', async () => {+ vi.setSystemTime(new Date('2025-01-25T12:00:00Z'))+ try {+ const user = userEvent.setup()+ render(+ <MonitoringDateRangePicker+ start={dayjs('2025-01-10')}+ end={dayjs('2025-01-20')}+ onStartChange={vi.fn()}+ onEndChange={vi.fn()}+ />,+ )+ await user.click(screen.getByRole('button', { name: /picker.endDate/ }))+ expect(screen.getByRole('button', { name: /January 25th, 2025/ })).toBeEnabled()+ expect(screen.getByRole('button', { name: /January 26th, 2025/ })).toBeDisabled()+ } finally {+ vi.useRealTimers()+ }+})diff --git a/web/features/monitoring/date-range-picker.tsx b/web/features/monitoring/date-range-picker.tsxnew file mode 100644index 00000000000..a541aa5f01a--- /dev/null+++ b/web/features/monitoring/date-range-picker.tsx@@ -0,0 +1,60 @@+'use client'+import type { Dayjs } from 'dayjs'+import dayjs from 'dayjs'+import { useTranslation } from 'react-i18next'+import { useLocale } from '#i18n'+import {+ DatePicker,+ DatePickerContent,+ DatePickerLabel,+ DatePickerTrigger,+ DatePickerValue,+} from '@/app/components/base/date-time-picker/date-picker'+import { formatToLocalTime } from '@/utils/format'+type Props = {+ start: Dayjs+ end: Dayjs+ onStartChange: (date: Dayjs) => void+ onEndChange: (date: Dayjs) => void+}+export function MonitoringDateRangePicker({ start, end, onStartChange, onEndChange }: Props) {+ const locale = useLocale()+ const { t } = useTranslation(['time'])+ const today = dayjs().format('YYYY-MM-DD')+ const startMax = [end.format('YYYY-MM-DD'), today].sort()[0]+ const endMax = [start.add(30, 'day').format('YYYY-MM-DD'), today].sort()[0]+ return (+ <div className="flex h-8 items-center gap-0.5 rounded-lg bg-components-input-bg-normal px-2">+ <span aria-hidden="true" className="i-ri-calendar-line size-3.5 text-text-tertiary" />+ <DatePicker+ value={start.format('YYYY-MM-DD')}+ minDate={end.subtract(30, 'day').format('YYYY-MM-DD')}+ maxDate={startMax}+ onValueChange={(next) => {+ if (next) onStartChange(dayjs(next))+ }}+ >+ <DatePickerLabel className="sr-only">{t(($) => $['picker.startDate'])}</DatePickerLabel>+ <DatePickerTrigger className="h-7 w-auto px-1">+ <DatePickerValue>{formatToLocalTime(start, locale, 'MMM D')}</DatePickerValue>+ </DatePickerTrigger>+ <DatePickerContent />+ </DatePicker>+ <span aria-hidden="true">–</span>+ <DatePicker+ value={end.format('YYYY-MM-DD')}+ minDate={start.format('YYYY-MM-DD')}+ maxDate={endMax}+ onValueChange={(next) => {+ if (next) onEndChange(dayjs(next))+ }}+ >+ <DatePickerLabel className="sr-only">{t(($) => $['picker.endDate'])}</DatePickerLabel>+ <DatePickerTrigger className="h-7 w-auto px-1">+ <DatePickerValue>{formatToLocalTime(end, locale, 'MMM D')}</DatePickerValue>+ </DatePickerTrigger>+ <DatePickerContent />+ </DatePicker>+ </div>+ )+}diff --git a/web/i18n/locales/ar-TN/common.json b/web/i18n/locales/ar-TN/common.jsonindex 545ac543109..9ddc3358e9e 100644--- a/web/i18n/locales/ar-TN/common.json+++ b/web/i18n/locales/ar-TN/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "هل أنت متأكد أنك تريد إزالة صورة ملفك الشخصي؟ سيستخدم حسابك الصورة الرمزية الأولية الافتراضية.","avatar.deleteTitle": "إزالة الصورة الرمزية","avatar.editAction": "تعديل الصورة الرمزية",- "calendar.selectedDate": "تم التحديد","chat.citation.characters": "الشخصيات:","chat.citation.hitCount": "عدد الاسترجاع:","chat.citation.hitScore": "درجة الاسترجاع:",diff --git a/web/i18n/locales/ar-TN/time.json b/web/i18n/locales/ar-TN/time.jsonindex b8c94dcb26b..1067a5ca510 100644--- a/web/i18n/locales/ar-TN/time.json+++ b/web/i18n/locales/ar-TN/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "الجمعة",- "daysInWeek.Mon": "الاثنين",- "daysInWeek.Sat": "السبت",- "daysInWeek.Sun": "الأحد",- "daysInWeek.Thu": "الخميس",- "daysInWeek.Tue": "الثلاثاء",- "daysInWeek.Wed": "الأربعاء",- "defaultPlaceholder": "اختر وقتًا...",- "months.April": "أبريل",- "months.August": "أغسطس",- "months.December": "ديسمبر",- "months.February": "فبراير",- "months.January": "يناير",- "months.July": "يوليو",- "months.June": "يونيو",- "months.March": "مارس",- "months.May": "مايو",- "months.November": "نوفمبر",- "months.October": "أكتوبر",- "months.September": "سبتمبر","operation.cancel": "إلغاء","operation.now": "الآن","operation.ok": "موافق","operation.pickDate": "اختر التاريخ",+ "picker.chooseMonthAndYear": "اختر الشهر والسنة",+ "picker.endDate": "تاريخ الانتهاء",+ "picker.hour": "الساعة",+ "picker.minute": "الدقيقة",+ "picker.month": "الشهر",+ "picker.nextMonth": "الشهر التالي",+ "picker.period": "صباحًا/مساءً",+ "picker.previousMonth": "الشهر السابق",+ "picker.required": "اختر قيمة.",+ "picker.requiredLabel": "مطلوب",+ "picker.startDate": "تاريخ البدء",+ "picker.unavailable": "هذا التاريخ أو الوقت غير متاح.",+ "picker.year": "السنة","title.pickTime": "اختر الوقت"}diff --git a/web/i18n/locales/ar-TN/workflow-integrations.json b/web/i18n/locales/ar-TN/workflow-integrations.jsonindex b1071c1f63a..d5476129a3e 100644--- a/web/i18n/locales/ar-TN/workflow-integrations.json+++ b/web/i18n/locales/ar-TN/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "أوقات التنفيذ الـ 5 التالية","nodes.triggerSchedule.onMinute": "في الدقيقة","nodes.triggerSchedule.selectFrequency": "حدد التكرار",- "nodes.triggerSchedule.selectTime": "اختر الوقت","nodes.triggerSchedule.title": "الجدول الزمني","nodes.triggerSchedule.useCronExpression": "استخدم تعبير cron","nodes.triggerSchedule.useVisualPicker": "استخدم منتقي مرئي",diff --git a/web/i18n/locales/az-AZ/common.json b/web/i18n/locales/az-AZ/common.jsonindex ae9b7b940cd..47288a9d2b6 100644--- a/web/i18n/locales/az-AZ/common.json+++ b/web/i18n/locales/az-AZ/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Profil şəklinizi çıxarmaq istədiyinizə əminsiniz? Hesabınızda baş hərfdən ibarət standart avatardan istifadə olunacaq.","avatar.deleteTitle": "Avatarın çıxarılması","avatar.editAction": "Avatarı redaktə et",- "calendar.selectedDate": "Seçilib","chat.citation.characters": "Simvollar:","chat.citation.hitCount": "Axtarış sayı:","chat.citation.hitScore": "Axtarış balı:",diff --git a/web/i18n/locales/az-AZ/time.json b/web/i18n/locales/az-AZ/time.jsonindex 3c271f2d865..4d9f21a0728 100644--- a/web/i18n/locales/az-AZ/time.json+++ b/web/i18n/locales/az-AZ/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD.MM.YYYY HH:mm",- "dateFormats.display": "D MMMM YYYY",- "dateFormats.displayWithTime": "D MMMM YYYY HH:mm","dateFormats.withSeconds": "DD.MM.YYYY HH:mm:ss",- "daysInWeek.Fri": "C",- "daysInWeek.Mon": "B.e",- "daysInWeek.Sat": "Ş",- "daysInWeek.Sun": "B",- "daysInWeek.Thu": "C.a",- "daysInWeek.Tue": "Ç.a",- "daysInWeek.Wed": "Ç",- "defaultPlaceholder": "Vaxt seçin...",- "months.April": "Aprel",- "months.August": "Avqust",- "months.December": "Dekabr",- "months.February": "Fevral",- "months.January": "Yanvar",- "months.July": "İyul",- "months.June": "İyun",- "months.March": "Mart",- "months.May": "May",- "months.November": "Noyabr",- "months.October": "Oktyabr",- "months.September": "Sentyabr","operation.cancel": "Ləğv et","operation.now": "İndi","operation.ok": "Təsdiqlə","operation.pickDate": "Tarix seç",+ "picker.chooseMonthAndYear": "Ay və il seçin",+ "picker.endDate": "Bitmə tarixi",+ "picker.hour": "Saat",+ "picker.minute": "Dəqiqə",+ "picker.month": "Ay",+ "picker.nextMonth": "Növbəti ay",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Əvvəlki ay",+ "picker.required": "Dəyər seçin.",+ "picker.requiredLabel": "Tələb olunur",+ "picker.startDate": "Başlanğıc tarixi",+ "picker.unavailable": "Bu tarix və ya vaxt əlçatan deyil.",+ "picker.year": "İl","title.pickTime": "Vaxt seçimi"}diff --git a/web/i18n/locales/az-AZ/workflow-integrations.json b/web/i18n/locales/az-AZ/workflow-integrations.jsonindex c0fe8a61316..7d79986e403 100644--- a/web/i18n/locales/az-AZ/workflow-integrations.json+++ b/web/i18n/locales/az-AZ/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Növbəti 5 icra vaxtı","nodes.triggerSchedule.onMinute": "Dəqiqə","nodes.triggerSchedule.selectFrequency": "Tezlik seç",- "nodes.triggerSchedule.selectTime": "Vaxt seç","nodes.triggerSchedule.title": "Cədvəl","nodes.triggerSchedule.useCronExpression": "Cron ifadəsindən istifadə et","nodes.triggerSchedule.useVisualPicker": "Vizual seçicidən istifadə et",diff --git a/web/i18n/locales/de-DE/common.json b/web/i18n/locales/de-DE/common.jsonindex 5b5117da3c9..0e7c91a6375 100644--- a/web/i18n/locales/de-DE/common.json+++ b/web/i18n/locales/de-DE/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Bist du sicher, dass du dein Profilbild entfernen möchtest? Dein Konto wird das standardmäßige Anfangs-Avatar verwenden.","avatar.deleteTitle": "Avatar entfernen","avatar.editAction": "Avatar bearbeiten",- "calendar.selectedDate": "Ausgewählt","chat.citation.characters": "Zeichen:","chat.citation.hitCount": "Abrufanzahl:","chat.citation.hitScore": "Abrufwertung:",diff --git a/web/i18n/locales/de-DE/time.json b/web/i18n/locales/de-DE/time.jsonindex 8938239d34d..c6fd15e5fbe 100644--- a/web/i18n/locales/de-DE/time.json+++ b/web/i18n/locales/de-DE/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Freitag",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Sonne",- "daysInWeek.Thu": "Donnerstag",- "daysInWeek.Tue": "Tue",- "daysInWeek.Wed": "Mittwoch",- "defaultPlaceholder": "Wähle eine Zeit...",- "months.April": "April",- "months.August": "August",- "months.December": "Dezember",- "months.February": "Februar",- "months.January": "Januar",- "months.July": "Juli",- "months.June": "Juni",- "months.March": "März",- "months.May": "Mai",- "months.November": "November",- "months.October": "Oktober",- "months.September": "September","operation.cancel": "Stornieren","operation.now": "Jetzt","operation.ok": "OK","operation.pickDate": "Datum auswählen",+ "picker.chooseMonthAndYear": "Monat und Jahr auswählen",+ "picker.endDate": "Enddatum",+ "picker.hour": "Stunde",+ "picker.minute": "Minute",+ "picker.month": "Monat",+ "picker.nextMonth": "Nächster Monat",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Vorheriger Monat",+ "picker.required": "Wählen Sie einen Wert.",+ "picker.requiredLabel": "Erforderlich",+ "picker.startDate": "Startdatum",+ "picker.unavailable": "Dieses Datum oder diese Uhrzeit ist nicht verfügbar.",+ "picker.year": "Jahr","title.pickTime": "Wähle Zeit"}diff --git a/web/i18n/locales/de-DE/workflow-integrations.json b/web/i18n/locales/de-DE/workflow-integrations.jsonindex cb5b17e2e4e..ce629972d3a 100644--- a/web/i18n/locales/de-DE/workflow-integrations.json+++ b/web/i18n/locales/de-DE/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Nächste 5 Ausführungszeiten","nodes.triggerSchedule.onMinute": "In einer Minute","nodes.triggerSchedule.selectFrequency": "Frequenz auswählen",- "nodes.triggerSchedule.selectTime": "Zeit auswählen","nodes.triggerSchedule.title": "Zeitplan","nodes.triggerSchedule.useCronExpression": "Cron-Ausdruck verwenden","nodes.triggerSchedule.useVisualPicker": "Visuellen Auswähler verwenden",diff --git a/web/i18n/locales/en-US/common.json b/web/i18n/locales/en-US/common.jsonindex c723fc6cf96..2f2a8cbcba1 100644--- a/web/i18n/locales/en-US/common.json+++ b/web/i18n/locales/en-US/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Are you sure you want to remove your profile picture? Your account will use the default initial avatar.","avatar.deleteTitle": "Remove Avatar","avatar.editAction": "Edit Avatar",- "calendar.selectedDate": "Selected","chat.citation.characters": "Characters:","chat.citation.hitCount": "Retrieval count:","chat.citation.hitScore": "Retrieval Score:",diff --git a/web/i18n/locales/en-US/time.json b/web/i18n/locales/en-US/time.jsonindex dfae6a698a8..fd54a29e68b 100644--- a/web/i18n/locales/en-US/time.json+++ b/web/i18n/locales/en-US/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Fri",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Sun",- "daysInWeek.Thu": "Thu",- "daysInWeek.Tue": "Tue",- "daysInWeek.Wed": "Wed",- "defaultPlaceholder": "Pick a time...",- "months.April": "April",- "months.August": "August",- "months.December": "December",- "months.February": "February",- "months.January": "January",- "months.July": "July",- "months.June": "June",- "months.March": "March",- "months.May": "May",- "months.November": "November",- "months.October": "October",- "months.September": "September","operation.cancel": "Cancel","operation.now": "Now","operation.ok": "OK","operation.pickDate": "Pick Date",+ "picker.chooseMonthAndYear": "Choose month and year",+ "picker.endDate": "End date",+ "picker.hour": "Hour",+ "picker.minute": "Minute",+ "picker.month": "Month",+ "picker.nextMonth": "Next month",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Previous month",+ "picker.required": "Choose a value.",+ "picker.requiredLabel": "Required",+ "picker.startDate": "Start date",+ "picker.unavailable": "This date or time is unavailable.",+ "picker.year": "Year","title.pickTime": "Pick Time"}diff --git a/web/i18n/locales/en-US/workflow-integrations.json b/web/i18n/locales/en-US/workflow-integrations.jsonindex 68ebc0d7270..7e7c94c4caf 100644--- a/web/i18n/locales/en-US/workflow-integrations.json+++ b/web/i18n/locales/en-US/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Next 5 execution times","nodes.triggerSchedule.onMinute": "On Minute","nodes.triggerSchedule.selectFrequency": "Select frequency",- "nodes.triggerSchedule.selectTime": "Select time","nodes.triggerSchedule.title": "Schedule","nodes.triggerSchedule.useCronExpression": "Use cron expression","nodes.triggerSchedule.useVisualPicker": "Use visual picker",diff --git a/web/i18n/locales/es-ES/common.json b/web/i18n/locales/es-ES/common.jsonindex bcf0e5ed393..c7cc0545efd 100644--- a/web/i18n/locales/es-ES/common.json+++ b/web/i18n/locales/es-ES/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "¿Estás seguro de que deseas eliminar tu foto de perfil? Tu cuenta usará el avatar inicial predeterminado.","avatar.deleteTitle": "Eliminar Avatar","avatar.editAction": "Editar Avatar",- "calendar.selectedDate": "Seleccionada","chat.citation.characters": "Caracteres:","chat.citation.hitCount": "Conteo de recuperaciones:","chat.citation.hitScore": "Puntuación de recuperación:",diff --git a/web/i18n/locales/es-ES/time.json b/web/i18n/locales/es-ES/time.jsonindex 65d7118e042..84f88123f0e 100644--- a/web/i18n/locales/es-ES/time.json+++ b/web/i18n/locales/es-ES/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, AAAA",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Viernes",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sáb",- "daysInWeek.Sun": "Sol",- "daysInWeek.Thu": "Jue",- "daysInWeek.Tue": "Mar",- "daysInWeek.Wed": "Miércoles",- "defaultPlaceholder": "Elige una hora...",- "months.April": "Abril",- "months.August": "Agosto",- "months.December": "Diciembre",- "months.February": "Febrero",- "months.January": "Enero",- "months.July": "Julio",- "months.June": "Junio",- "months.March": "Marzo",- "months.May": "Mayo",- "months.November": "Noviembre",- "months.October": "octubre",- "months.September": "Septiembre","operation.cancel": "Cancelar","operation.now": "Ahora","operation.ok": "De acuerdo","operation.pickDate": "Seleccionar fecha",+ "picker.chooseMonthAndYear": "Elegir mes y año",+ "picker.endDate": "Fecha de fin",+ "picker.hour": "Hora",+ "picker.minute": "Minuto",+ "picker.month": "Mes",+ "picker.nextMonth": "Mes siguiente",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Mes anterior",+ "picker.required": "Elige un valor.",+ "picker.requiredLabel": "Obligatorio",+ "picker.startDate": "Fecha de inicio",+ "picker.unavailable": "Esta fecha u hora no está disponible.",+ "picker.year": "Año","title.pickTime": "Elegir hora"}diff --git a/web/i18n/locales/es-ES/workflow-integrations.json b/web/i18n/locales/es-ES/workflow-integrations.jsonindex 81c2757f1aa..e9b9b14da30 100644--- a/web/i18n/locales/es-ES/workflow-integrations.json+++ b/web/i18n/locales/es-ES/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Próximos 5 tiempos de ejecución","nodes.triggerSchedule.onMinute": "En un minuto","nodes.triggerSchedule.selectFrequency": "Seleccionar frecuencia",- "nodes.triggerSchedule.selectTime": "Seleccionar hora","nodes.triggerSchedule.title": "Horario","nodes.triggerSchedule.useCronExpression": "Usar expresión cron","nodes.triggerSchedule.useVisualPicker": "Usar selector visual",diff --git a/web/i18n/locales/fa-IR/common.json b/web/i18n/locales/fa-IR/common.jsonindex 35bc228cf94..517cae5bcc3 100644--- a/web/i18n/locales/fa-IR/common.json+++ b/web/i18n/locales/fa-IR/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "آیا مطمئن هستید که میخواهید تصویر پروفایل خود را حذف کنید؟ حساب شما از آواتار اولیه پیشفرض استفاده خواهد کرد.","avatar.deleteTitle": "حذف آواتار","avatar.editAction": "ویرایش آواتار",- "calendar.selectedDate": "انتخابشده","chat.citation.characters": "کاراکترها:","chat.citation.hitCount": "تعداد بازیابی:","chat.citation.hitScore": "امتیاز بازیابی:",diff --git a/web/i18n/locales/fa-IR/time.json b/web/i18n/locales/fa-IR/time.jsonindex 57290b383ce..91cd2fd5a50 100644--- a/web/i18n/locales/fa-IR/time.json+++ b/web/i18n/locales/fa-IR/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "جمعه",- "daysInWeek.Mon": "مون",- "daysInWeek.Sat": "شنبه",- "daysInWeek.Sun": "خورشید",- "daysInWeek.Thu": "پنجشنبه",- "daysInWeek.Tue": "سه شنبه",- "daysInWeek.Wed": "چهارشنبه",- "defaultPlaceholder": "زمانی را انتخاب کنید...",- "months.April": "آوریل",- "months.August": "اوت",- "months.December": "دسامبر",- "months.February": "فوریه",- "months.January": "ژانویه",- "months.July": "جولای",- "months.June": "ژوئن",- "months.March": "مارس",- "months.May": "مه",- "months.November": "نوامبر",- "months.October": "اکتبر",- "months.September": "سپتامبر","operation.cancel": "لغو","operation.now": "حالا","operation.ok": "خوب","operation.pickDate": "تاریخ را انتخاب کنید",+ "picker.chooseMonthAndYear": "ماه و سال را انتخاب کنید",+ "picker.endDate": "تاریخ پایان",+ "picker.hour": "ساعت",+ "picker.minute": "دقیقه",+ "picker.month": "ماه",+ "picker.nextMonth": "ماه بعد",+ "picker.period": "قبلازظهر/بعدازظهر",+ "picker.previousMonth": "ماه قبل",+ "picker.required": "یک مقدار انتخاب کنید.",+ "picker.requiredLabel": "الزامی",+ "picker.startDate": "تاریخ شروع",+ "picker.unavailable": "این تاریخ یا زمان در دسترس نیست.",+ "picker.year": "سال","title.pickTime": "زمان انتخاب کنید"}diff --git a/web/i18n/locales/fa-IR/workflow-integrations.json b/web/i18n/locales/fa-IR/workflow-integrations.jsonindex c1dc43631eb..bd15bc8a19e 100644--- a/web/i18n/locales/fa-IR/workflow-integrations.json+++ b/web/i18n/locales/fa-IR/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "۵ زمان اجرای بعدی","nodes.triggerSchedule.onMinute": "در دقیقه","nodes.triggerSchedule.selectFrequency": "انتخاب تکرار",- "nodes.triggerSchedule.selectTime": "انتخاب زمان","nodes.triggerSchedule.title": "زمانبندی","nodes.triggerSchedule.useCronExpression": "استفاده از عبارت Cron","nodes.triggerSchedule.useVisualPicker": "استفاده از انتخابگر بصری",diff --git a/web/i18n/locales/fr-FR/common.json b/web/i18n/locales/fr-FR/common.jsonindex b5bfbee920d..24dcdabd330 100644--- a/web/i18n/locales/fr-FR/common.json+++ b/web/i18n/locales/fr-FR/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Êtes-vous sûr de vouloir supprimer votre photo de profil ? Votre compte utilisera l'avatar par défaut.","avatar.deleteTitle": "Supprimer l'avatar","avatar.editAction": "Modifier l'avatar",- "calendar.selectedDate": "Sélectionnée","chat.citation.characters": "Personnages :","chat.citation.hitCount": "Nombre de récupérations :","chat.citation.hitScore": "Score de Récupération:",diff --git a/web/i18n/locales/fr-FR/time.json b/web/i18n/locales/fr-FR/time.jsonindex 1127f7a1223..8a8241f46b9 100644--- a/web/i18n/locales/fr-FR/time.json+++ b/web/i18n/locales/fr-FR/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD/MM/YYYY HH:mm",- "dateFormats.display": "MMMM D, AAAA",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Libre",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Soleil",- "daysInWeek.Thu": "Jeudi",- "daysInWeek.Tue": "Mardi",- "daysInWeek.Wed": "Mercredi",- "defaultPlaceholder": "Choisissez un moment...",- "months.April": "Avril",- "months.August": "août",- "months.December": "Décembre",- "months.February": "Février",- "months.January": "Janvier",- "months.July": "Juillet",- "months.June": "Juin",- "months.March": "Mars",- "months.May": "Mai",- "months.November": "Novembre",- "months.October": "octobre",- "months.September": "Septembre","operation.cancel": "Annuler","operation.now": "Maintenant","operation.ok": "D'accord","operation.pickDate": "Choisir une date",+ "picker.chooseMonthAndYear": "Choisir le mois et l’année",+ "picker.endDate": "Date de fin",+ "picker.hour": "Heure",+ "picker.minute": "Minute",+ "picker.month": "Mois",+ "picker.nextMonth": "Mois suivant",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Mois précédent",+ "picker.required": "Choisissez une valeur.",+ "picker.requiredLabel": "Obligatoire",+ "picker.startDate": "Date de début",+ "picker.unavailable": "Cette date ou heure n’est pas disponible.",+ "picker.year": "Année","title.pickTime": "Choisir le temps"}diff --git a/web/i18n/locales/fr-FR/workflow-integrations.json b/web/i18n/locales/fr-FR/workflow-integrations.jsonindex 2a1ac9b246d..8fe0ec3233f 100644--- a/web/i18n/locales/fr-FR/workflow-integrations.json+++ b/web/i18n/locales/fr-FR/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Prochaines 5 exécutions","nodes.triggerSchedule.onMinute": "Une minute","nodes.triggerSchedule.selectFrequency": "Sélectionner la fréquence",- "nodes.triggerSchedule.selectTime": "Sélectionner l'heure","nodes.triggerSchedule.title": "Programme","nodes.triggerSchedule.useCronExpression": "Utiliser une expression cron","nodes.triggerSchedule.useVisualPicker": "Utiliser le sélecteur visuel",diff --git a/web/i18n/locales/hi-IN/common.json b/web/i18n/locales/hi-IN/common.jsonindex e123cf4f42e..1d625178207 100644--- a/web/i18n/locales/hi-IN/common.json+++ b/web/i18n/locales/hi-IN/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "क्या आप सुनिश्चित हैं कि आप अपनी प्रोफ़ाइल तस्वीर को हटाना चाहते हैं? आपका खाता डिफ़ॉल्ट प्रारंभिक अवतार का उपयोग करेगा।","avatar.deleteTitle": "अवतार हटाएँ","avatar.editAction": "अवतार संपादित करें",- "calendar.selectedDate": "चयनित","chat.citation.characters": "वर्ण:","chat.citation.hitCount": "पुनः प्राप्ति गिनती:","chat.citation.hitScore": "पुनः प्राप्ति स्कोर:",diff --git a/web/i18n/locales/hi-IN/time.json b/web/i18n/locales/hi-IN/time.jsonindex 011eca9f479..b8fd79d8b15 100644--- a/web/i18n/locales/hi-IN/time.json+++ b/web/i18n/locales/hi-IN/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "शुक्रवार",- "daysInWeek.Mon": "मोन",- "daysInWeek.Sat": "शनिवार",- "daysInWeek.Sun": "सूर्य",- "daysInWeek.Thu": "गुरुवार",- "daysInWeek.Tue": "मंगलवार",- "daysInWeek.Wed": "बुधवार",- "defaultPlaceholder": "एक समय चुनें...",- "months.April": "अप्रैल",- "months.August": "अगस्त",- "months.December": "दिसंबर",- "months.February": "फरवरी",- "months.January": "जनवरी",- "months.July": "जुलाई",- "months.June": "जून",- "months.March": "मार्च",- "months.May": "मई",- "months.November": "नवंबर",- "months.October": "अक्टूबर",- "months.September": "सितंबर","operation.cancel": "रद्द करें","operation.now": "अब","operation.ok": "ठीक है","operation.pickDate": "तारीख़ चुनें",+ "picker.chooseMonthAndYear": "महीना और वर्ष चुनें",+ "picker.endDate": "समाप्ति तिथि",+ "picker.hour": "घंटा",+ "picker.minute": "मिनट",+ "picker.month": "महीना",+ "picker.nextMonth": "अगला महीना",+ "picker.period": "पूर्वाह्न/अपराह्न",+ "picker.previousMonth": "पिछला महीना",+ "picker.required": "कोई मान चुनें।",+ "picker.requiredLabel": "आवश्यक",+ "picker.startDate": "आरंभ तिथि",+ "picker.unavailable": "यह तारीख या समय उपलब्ध नहीं है।",+ "picker.year": "वर्ष","title.pickTime": "समय चुनें"}diff --git a/web/i18n/locales/hi-IN/workflow-integrations.json b/web/i18n/locales/hi-IN/workflow-integrations.jsonindex b39563bbfdd..80e05ac3647 100644--- a/web/i18n/locales/hi-IN/workflow-integrations.json+++ b/web/i18n/locales/hi-IN/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "अगली 5 निष्पादन समय","nodes.triggerSchedule.onMinute": "एक मिनट पर","nodes.triggerSchedule.selectFrequency": "आवृत्ति चुनें",- "nodes.triggerSchedule.selectTime": "समय चुनें","nodes.triggerSchedule.title": "अनुसूची","nodes.triggerSchedule.useCronExpression": "क्रोन एक्सप्रेशन का उपयोग करें","nodes.triggerSchedule.useVisualPicker": "विज़ुअल पिकर का उपयोग करें",diff --git a/web/i18n/locales/id-ID/common.json b/web/i18n/locales/id-ID/common.jsonindex df7dfb2e58a..5db5b4cbeff 100644--- a/web/i18n/locales/id-ID/common.json+++ b/web/i18n/locales/id-ID/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Apakah Anda yakin ingin menghapus gambar profil Anda? Akun Anda akan menggunakan avatar awal default.","avatar.deleteTitle": "Hapus Avatar","avatar.editAction": "Edit Avatar",- "calendar.selectedDate": "Dipilih","chat.citation.characters": "Karakter:","chat.citation.hitCount": "Jumlah pengambilan:","chat.citation.hitScore": "Skor Pengambilan:",diff --git a/web/i18n/locales/id-ID/time.json b/web/i18n/locales/id-ID/time.jsonindex 735892ad22e..2da182850d0 100644--- a/web/i18n/locales/id-ID/time.json+++ b/web/i18n/locales/id-ID/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Jumat",- "daysInWeek.Mon": "Senin",- "daysInWeek.Sat": "Sabtu",- "daysInWeek.Sun": "Minggu",- "daysInWeek.Thu": "Kamis",- "daysInWeek.Tue": "Selasa",- "daysInWeek.Wed": "Rabu",- "defaultPlaceholder": "Pilih waktu...",- "months.April": "April",- "months.August": "Agustus",- "months.December": "Desember",- "months.February": "Februari",- "months.January": "Januari",- "months.July": "Juli",- "months.June": "Juni",- "months.March": "Maret",- "months.May": "Mei",- "months.November": "November",- "months.October": "Oktober",- "months.September": "September","operation.cancel": "Membatalkan","operation.now": "Sekarang","operation.ok": "OKE","operation.pickDate": "Tanggal Pilih",+ "picker.chooseMonthAndYear": "Pilih bulan dan tahun",+ "picker.endDate": "Tanggal akhir",+ "picker.hour": "Jam",+ "picker.minute": "Menit",+ "picker.month": "Bulan",+ "picker.nextMonth": "Bulan berikutnya",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Bulan sebelumnya",+ "picker.required": "Pilih nilai.",+ "picker.requiredLabel": "Wajib",+ "picker.startDate": "Tanggal mulai",+ "picker.unavailable": "Tanggal atau waktu ini tidak tersedia.",+ "picker.year": "Tahun","title.pickTime": "Waktu Pilih"}diff --git a/web/i18n/locales/id-ID/workflow-integrations.json b/web/i18n/locales/id-ID/workflow-integrations.jsonindex fb0c02aa12c..5c9187a1986 100644--- a/web/i18n/locales/id-ID/workflow-integrations.json+++ b/web/i18n/locales/id-ID/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "5 waktu eksekusi berikutnya","nodes.triggerSchedule.onMinute": "Dalam Sejuta","nodes.triggerSchedule.selectFrequency": "Pilih frekuensi",- "nodes.triggerSchedule.selectTime": "Pilih waktu","nodes.triggerSchedule.title": "Jadwal","nodes.triggerSchedule.useCronExpression": "Gunakan ekspresi cron","nodes.triggerSchedule.useVisualPicker": "Gunakan pemilih visual",diff --git a/web/i18n/locales/it-IT/common.json b/web/i18n/locales/it-IT/common.jsonindex 4fd3dbc9656..67ed98f2e3f 100644--- a/web/i18n/locales/it-IT/common.json+++ b/web/i18n/locales/it-IT/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Sei sicuro di voler rimuovere la tua immagine del profilo? Il tuo account utilizzerà l'avatar iniziale predefinito.","avatar.deleteTitle": "Rimuovi avatar","avatar.editAction": "Modifica avatar",- "calendar.selectedDate": "Selezionata","chat.citation.characters": "Caratteri:","chat.citation.hitCount": "Conteggio dei recuperi:","chat.citation.hitScore": "Punteggio di recupero:",diff --git a/web/i18n/locales/it-IT/time.json b/web/i18n/locales/it-IT/time.jsonindex a6b1ba074c1..ba94de48cf9 100644--- a/web/i18n/locales/it-IT/time.json+++ b/web/i18n/locales/it-IT/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD/MM/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Venerdì",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Sole",- "daysInWeek.Thu": "Giovedì",- "daysInWeek.Tue": "Martedì",- "daysInWeek.Wed": "Mercoledì",- "defaultPlaceholder": "Scegli un orario...",- "months.April": "Aprile",- "months.August": "Agosto",- "months.December": "Dicembre",- "months.February": "Febbraio",- "months.January": "Gennaio",- "months.July": "Luglio",- "months.June": "Giugno",- "months.March": "Marzo",- "months.May": "Maggio",- "months.November": "Novembre",- "months.October": "Ottobre",- "months.September": "Settembre","operation.cancel": "Annulla","operation.now": "Ora","operation.ok": "OK","operation.pickDate": "Seleziona Data",+ "picker.chooseMonthAndYear": "Scegli mese e anno",+ "picker.endDate": "Data di fine",+ "picker.hour": "Ora",+ "picker.minute": "Minuto",+ "picker.month": "Mese",+ "picker.nextMonth": "Mese successivo",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Mese precedente",+ "picker.required": "Scegli un valore.",+ "picker.requiredLabel": "Obbligatorio",+ "picker.startDate": "Data di inizio",+ "picker.unavailable": "Questa data o ora non è disponibile.",+ "picker.year": "Anno","title.pickTime": "Scegli Tempo"}diff --git a/web/i18n/locales/it-IT/workflow-integrations.json b/web/i18n/locales/it-IT/workflow-integrations.jsonindex 2f3b34dd5f8..2b6f6f2a8ff 100644--- a/web/i18n/locales/it-IT/workflow-integrations.json+++ b/web/i18n/locales/it-IT/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Prossimi 5 tempi di esecuzione","nodes.triggerSchedule.onMinute": "In un minuto","nodes.triggerSchedule.selectFrequency": "Seleziona frequenza",- "nodes.triggerSchedule.selectTime": "Seleziona orario","nodes.triggerSchedule.title": "Programma","nodes.triggerSchedule.useCronExpression": "Usa un'espressione cron","nodes.triggerSchedule.useVisualPicker": "Usa il selettore visivo",diff --git a/web/i18n/locales/ja-JP/common.json b/web/i18n/locales/ja-JP/common.jsonindex 74163bb6b03..71a3de08302 100644--- a/web/i18n/locales/ja-JP/common.json+++ b/web/i18n/locales/ja-JP/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "本当にプロフィール写真を削除してもよろしいですか?あなたのアカウントはデフォルトの初期アバターを使用します。","avatar.deleteTitle": "アバターを削除する","avatar.editAction": "アバターを編集する",- "calendar.selectedDate": "選択済み","chat.citation.characters": "文字数:","chat.citation.hitCount": "検索回数:","chat.citation.hitScore": "検索スコア:",diff --git a/web/i18n/locales/ja-JP/time.json b/web/i18n/locales/ja-JP/time.jsonindex 701daf658f8..dd875f8a364 100644--- a/web/i18n/locales/ja-JP/time.json+++ b/web/i18n/locales/ja-JP/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "YYYY/MM/DD HH:mm",- "dateFormats.display": "YYYY年MM月DD日",- "dateFormats.displayWithTime": "YYYY年MM月DD日 HH:mm","dateFormats.withSeconds": "YYYY/MM/DD hh:mm:ss A",- "daysInWeek.Fri": "金曜日",- "daysInWeek.Mon": "月曜日",- "daysInWeek.Sat": "土曜日",- "daysInWeek.Sun": "日曜日",- "daysInWeek.Thu": "木曜日",- "daysInWeek.Tue": "火曜日",- "daysInWeek.Wed": "水曜日",- "defaultPlaceholder": "時間を選んでください...",- "months.April": "4 月",- "months.August": "8 月",- "months.December": "12 月",- "months.February": "2 月",- "months.January": "1 月",- "months.July": "7 月",- "months.June": "6 月",- "months.March": "3 月",- "months.May": "5 月",- "months.November": "11 月",- "months.October": "10 月",- "months.September": "9 月","operation.cancel": "キャンセル","operation.now": "今","operation.ok": "はい","operation.pickDate": "日付を選択",+ "picker.chooseMonthAndYear": "月と年を選択",+ "picker.endDate": "終了日",+ "picker.hour": "時",+ "picker.minute": "分",+ "picker.month": "月",+ "picker.nextMonth": "次の月",+ "picker.period": "午前・午後",+ "picker.previousMonth": "前の月",+ "picker.required": "値を選択してください。",+ "picker.requiredLabel": "必須",+ "picker.startDate": "開始日",+ "picker.unavailable": "この日時は選択できません。",+ "picker.year": "年","title.pickTime": "ピックタイム"}diff --git a/web/i18n/locales/ja-JP/workflow-integrations.json b/web/i18n/locales/ja-JP/workflow-integrations.jsonindex e0568705ed1..b18255c9913 100644--- a/web/i18n/locales/ja-JP/workflow-integrations.json+++ b/web/i18n/locales/ja-JP/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "次の5回の実行時刻","nodes.triggerSchedule.onMinute": "分","nodes.triggerSchedule.selectFrequency": "頻度を選択",- "nodes.triggerSchedule.selectTime": "時間を選択","nodes.triggerSchedule.title": "スケジュール","nodes.triggerSchedule.useCronExpression": "Cron 式を使用","nodes.triggerSchedule.useVisualPicker": "ビジュアル設定を使用",diff --git a/web/i18n/locales/ko-KR/common.json b/web/i18n/locales/ko-KR/common.jsonindex 1ff13f7354f..6e781148040 100644--- a/web/i18n/locales/ko-KR/common.json+++ b/web/i18n/locales/ko-KR/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "프로필 사진을 제거하시겠습니까? 귀하의 계정은 기본 초기 아바타를 사용하게 됩니다.","avatar.deleteTitle": "아바타 제거하기","avatar.editAction": "아바타 편집하기",- "calendar.selectedDate": "선택됨","chat.citation.characters": "문자수:","chat.citation.hitCount": "검색 횟수:","chat.citation.hitScore": "검색 점수:",diff --git a/web/i18n/locales/ko-KR/time.json b/web/i18n/locales/ko-KR/time.jsonindex 5126c1d323e..eb03fb9f1c4 100644--- a/web/i18n/locales/ko-KR/time.json+++ b/web/i18n/locales/ko-KR/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "YYYY/MM/DD HH:mm:ss",- "daysInWeek.Fri": "금요일",- "daysInWeek.Mon": "월요일",- "daysInWeek.Sat": "토요일",- "daysInWeek.Sun": "일요일",- "daysInWeek.Thu": "목요일",- "daysInWeek.Tue": "화요일",- "daysInWeek.Wed": "수요일",- "defaultPlaceholder": "시간을 선택하세요...",- "months.April": "4 월",- "months.August": "8 월",- "months.December": "12 월",- "months.February": "2 월",- "months.January": "1 월",- "months.July": "7 월",- "months.June": "6 월",- "months.March": "3 월",- "months.May": "5 월",- "months.November": "11 월",- "months.October": "10 월",- "months.September": "9 월","operation.cancel": "취소","operation.now": "오늘","operation.ok": "좋아요","operation.pickDate": "날짜 선택",+ "picker.chooseMonthAndYear": "월 및 연도 선택",+ "picker.endDate": "종료 날짜",+ "picker.hour": "시",+ "picker.minute": "분",+ "picker.month": "월",+ "picker.nextMonth": "다음 달",+ "picker.period": "오전/오후",+ "picker.previousMonth": "이전 달",+ "picker.required": "값을 선택하세요.",+ "picker.requiredLabel": "필수",+ "picker.startDate": "시작 날짜",+ "picker.unavailable": "이 날짜 또는 시간은 사용할 수 없습니다.",+ "picker.year": "연도","title.pickTime": "시간 선택"}diff --git a/web/i18n/locales/ko-KR/workflow-integrations.json b/web/i18n/locales/ko-KR/workflow-integrations.jsonindex 56c06d04038..c596e1f063c 100644--- a/web/i18n/locales/ko-KR/workflow-integrations.json+++ b/web/i18n/locales/ko-KR/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "다음 5회 실행 시간","nodes.triggerSchedule.onMinute": "분 안에","nodes.triggerSchedule.selectFrequency": "주파수 선택",- "nodes.triggerSchedule.selectTime": "시간 선택","nodes.triggerSchedule.title": "일정","nodes.triggerSchedule.useCronExpression": "크론 표현식 사용","nodes.triggerSchedule.useVisualPicker": "시각적 선택기 사용",diff --git a/web/i18n/locales/lo-LA/common.json b/web/i18n/locales/lo-LA/common.jsonindex 8b36d6080fc..be18d65c1db 100644--- a/web/i18n/locales/lo-LA/common.json+++ b/web/i18n/locales/lo-LA/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "ທ່ານແນ່ໃຈບໍວ່າຕ້ອງການລຶບຮູບໂປຣໄຟລ໌ຂອງທ່ານ? ບັນຊີຂອງທ່ານຈະກັບໄປໃຊ້ຮູບເລີ່ມຕົ້ນ.","avatar.deleteTitle": "ລຶບຮູບໂປຣໄຟລ໌","avatar.editAction": "ແກ້ໄຂຮູບໂປຣໄຟລ໌",- "calendar.selectedDate": "ເລືອກແລ້ວ","chat.citation.characters": "ຕົວອັກສອນ:","chat.citation.hitCount": "ຈຳນວນການດຶງຂໍ້ມູນ:","chat.citation.hitScore": "ຄະແນນການດຶງຂໍ້ມູນ:",diff --git a/web/i18n/locales/lo-LA/time.json b/web/i18n/locales/lo-LA/time.jsonindex 93878b8a44c..b79ec0cdb0d 100644--- a/web/i18n/locales/lo-LA/time.json+++ b/web/i18n/locales/lo-LA/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "D MMMM YYYY",- "dateFormats.displayWithTime": "D MMMM YYYY hh:mm A","dateFormats.withSeconds": "DD/MM/YYYY hh:mm:ss A",- "daysInWeek.Fri": "ວັນສຸກ",- "daysInWeek.Mon": "ວັນຈັນ",- "daysInWeek.Sat": "ວັນເສົາ",- "daysInWeek.Sun": "ວັນອາທິດ",- "daysInWeek.Thu": "ວັນພະຫັດ",- "daysInWeek.Tue": "ວັນອັງຄານ",- "daysInWeek.Wed": "ວັນພຸດ",- "defaultPlaceholder": "ເລືອກເວລາ...",- "months.April": "ເມສາ",- "months.August": "ສິງຫາ",- "months.December": "ທັນວາ",- "months.February": "ກຸມພາ",- "months.January": "ມັງກອນ",- "months.July": "ກໍລະກົດ",- "months.June": "ມິຖຸນາ",- "months.March": "ມີນາ",- "months.May": "ພຶດສະພາ",- "months.November": "ພະຈິກ",- "months.October": "ຕຸລາ",- "months.September": "ກັນຍາ","operation.cancel": "ຍົກເລີກ","operation.now": "ດຽວນີ້","operation.ok": "ຕົກລົງ","operation.pickDate": "ເລືອກວັນທີ",+ "picker.chooseMonthAndYear": "ເລືອກເດືອນ ແລະ ປີ",+ "picker.endDate": "ວັນທີສິ້ນສຸດ",+ "picker.hour": "ຊົ່ວໂມງ",+ "picker.minute": "ນາທີ",+ "picker.month": "ເດືອນ",+ "picker.nextMonth": "ເດືອນຖັດໄປ",+ "picker.period": "ກ່ອນທ່ຽງ/ຫຼັງທ່ຽງ",+ "picker.previousMonth": "ເດືອນກ່ອນ",+ "picker.required": "ກະລຸນາເລືອກຄ່າ.",+ "picker.requiredLabel": "ຈຳເປັນ",+ "picker.startDate": "ວັນທີເລີ່ມ",+ "picker.unavailable": "ວັນທີ ຫຼື ເວລານີ້ບໍ່ພ້ອມໃຊ້.",+ "picker.year": "ປີ","title.pickTime": "ເລືອກເວລາ"}diff --git a/web/i18n/locales/lo-LA/workflow-integrations.json b/web/i18n/locales/lo-LA/workflow-integrations.jsonindex 7dea8e4d831..2d9271c784b 100644--- a/web/i18n/locales/lo-LA/workflow-integrations.json+++ b/web/i18n/locales/lo-LA/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "5 ເວລາດຳເນີນການຖັດໄປ","nodes.triggerSchedule.onMinute": "ໃນນາທີທີ","nodes.triggerSchedule.selectFrequency": "ເລືອກຄວາມຖີ່",- "nodes.triggerSchedule.selectTime": "ເລືອກເວລາ","nodes.triggerSchedule.title": "ກຳນົດເວລາ","nodes.triggerSchedule.useCronExpression": "ໃຊ້ Cron expression","nodes.triggerSchedule.useVisualPicker": "ໃຊ້ Visual picker",diff --git a/web/i18n/locales/nl-NL/common.json b/web/i18n/locales/nl-NL/common.jsonindex e662c1cd00c..03ebe3f035f 100644--- a/web/i18n/locales/nl-NL/common.json+++ b/web/i18n/locales/nl-NL/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Are you sure you want to remove your profile picture? Your account will use the default initial avatar.","avatar.deleteTitle": "Remove Avatar","avatar.editAction": "Avatar bewerken",- "calendar.selectedDate": "Geselecteerd","chat.citation.characters": "Characters:","chat.citation.hitCount": "Retrieval count:","chat.citation.hitScore": "Retrieval Score:",diff --git a/web/i18n/locales/nl-NL/time.json b/web/i18n/locales/nl-NL/time.jsonindex dfae6a698a8..faca4703124 100644--- a/web/i18n/locales/nl-NL/time.json+++ b/web/i18n/locales/nl-NL/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Fri",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Sun",- "daysInWeek.Thu": "Thu",- "daysInWeek.Tue": "Tue",- "daysInWeek.Wed": "Wed",- "defaultPlaceholder": "Pick a time...",- "months.April": "April",- "months.August": "August",- "months.December": "December",- "months.February": "February",- "months.January": "January",- "months.July": "July",- "months.June": "June",- "months.March": "March",- "months.May": "May",- "months.November": "November",- "months.October": "October",- "months.September": "September","operation.cancel": "Cancel","operation.now": "Now","operation.ok": "OK","operation.pickDate": "Pick Date",+ "picker.chooseMonthAndYear": "Kies maand en jaar",+ "picker.endDate": "Einddatum",+ "picker.hour": "Uur",+ "picker.minute": "Minuut",+ "picker.month": "Maand",+ "picker.nextMonth": "Volgende maand",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Vorige maand",+ "picker.required": "Kies een waarde.",+ "picker.requiredLabel": "Verplicht",+ "picker.startDate": "Begindatum",+ "picker.unavailable": "Deze datum of tijd is niet beschikbaar.",+ "picker.year": "Jaar","title.pickTime": "Pick Time"}diff --git a/web/i18n/locales/nl-NL/workflow-integrations.json b/web/i18n/locales/nl-NL/workflow-integrations.jsonindex 68ebc0d7270..7e7c94c4caf 100644--- a/web/i18n/locales/nl-NL/workflow-integrations.json+++ b/web/i18n/locales/nl-NL/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Next 5 execution times","nodes.triggerSchedule.onMinute": "On Minute","nodes.triggerSchedule.selectFrequency": "Select frequency",- "nodes.triggerSchedule.selectTime": "Select time","nodes.triggerSchedule.title": "Schedule","nodes.triggerSchedule.useCronExpression": "Use cron expression","nodes.triggerSchedule.useVisualPicker": "Use visual picker",diff --git a/web/i18n/locales/pl-PL/common.json b/web/i18n/locales/pl-PL/common.jsonindex b3cb134b49e..a42e708dbe3 100644--- a/web/i18n/locales/pl-PL/common.json+++ b/web/i18n/locales/pl-PL/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Czy na pewno chcesz usunąć swoje zdjęcie profilowe? Twoje konto będzie używać domyślnego, początkowego awatara.","avatar.deleteTitle": "Usuń awatar","avatar.editAction": "Edytuj awatar",- "calendar.selectedDate": "Wybrana","chat.citation.characters": "Postacie:","chat.citation.hitCount": "Liczba trafień:","chat.citation.hitScore": "Wynik trafień:",diff --git a/web/i18n/locales/pl-PL/time.json b/web/i18n/locales/pl-PL/time.jsonindex f968a1d9d8c..5152e70df42 100644--- a/web/i18n/locales/pl-PL/time.json+++ b/web/i18n/locales/pl-PL/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "DD/MM/YYYY HH:mm:ss",- "daysInWeek.Fri": "Wolny",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Słońce",- "daysInWeek.Thu": "Czw",- "daysInWeek.Tue": "Wtorek",- "daysInWeek.Wed": "Środa",- "defaultPlaceholder": "Wybierz czas...",- "months.April": "Kwiecień",- "months.August": "Sierpień",- "months.December": "Grudzień",- "months.February": "Luty",- "months.January": "Styczeń",- "months.July": "lipiec",- "months.June": "Czerwiec",- "months.March": "Marzec",- "months.May": "Maj",- "months.November": "Listopad",- "months.October": "Październik",- "months.September": "Wrzesień","operation.cancel": "Anuluj","operation.now": "Teraz","operation.ok": "OK","operation.pickDate": "Wybierz datę",+ "picker.chooseMonthAndYear": "Wybierz miesiąc i rok",+ "picker.endDate": "Data zakończenia",+ "picker.hour": "Godzina",+ "picker.minute": "Minuta",+ "picker.month": "Miesiąc",+ "picker.nextMonth": "Następny miesiąc",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Poprzedni miesiąc",+ "picker.required": "Wybierz wartość.",+ "picker.requiredLabel": "Wymagane",+ "picker.startDate": "Data rozpoczęcia",+ "picker.unavailable": "Ta data lub godzina jest niedostępna.",+ "picker.year": "Rok","title.pickTime": "Wybierz czas"}diff --git a/web/i18n/locales/pl-PL/workflow-integrations.json b/web/i18n/locales/pl-PL/workflow-integrations.jsonindex ddca884cd6c..8b4a6507e47 100644--- a/web/i18n/locales/pl-PL/workflow-integrations.json+++ b/web/i18n/locales/pl-PL/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Następne 5 terminów wykonania","nodes.triggerSchedule.onMinute": "Za minutę","nodes.triggerSchedule.selectFrequency": "Wybierz częstotliwość",- "nodes.triggerSchedule.selectTime": "Wybierz czas","nodes.triggerSchedule.title": "Harmonogram","nodes.triggerSchedule.useCronExpression": "Użyj wyrażenia cron","nodes.triggerSchedule.useVisualPicker": "Użyj selektora wizualnego",diff --git a/web/i18n/locales/pt-BR/common.json b/web/i18n/locales/pt-BR/common.jsonindex 41cff4a544b..7be259127ec 100644--- a/web/i18n/locales/pt-BR/common.json+++ b/web/i18n/locales/pt-BR/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Você tem certeza de que deseja remover sua foto de perfil? Sua conta usará o avatar padrão inicial.","avatar.deleteTitle": "Remover Avatar","avatar.editAction": "Editar Avatar",- "calendar.selectedDate": "Selecionada","chat.citation.characters": "Personagens:","chat.citation.hitCount": "Contagem de recuperação:","chat.citation.hitScore": "Pontuação de recuperação:",diff --git a/web/i18n/locales/pt-BR/time.json b/web/i18n/locales/pt-BR/time.jsonindex 4bd59aa4f54..84a57077f34 100644--- a/web/i18n/locales/pt-BR/time.json+++ b/web/i18n/locales/pt-BR/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD/MM/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Sexta",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sábado",- "daysInWeek.Sun": "Sol",- "daysInWeek.Thu": "Quinta-feira",- "daysInWeek.Tue": "Terça-feira",- "daysInWeek.Wed": "Quarta-feira",- "defaultPlaceholder": "Escolha um horário...",- "months.April": "abril",- "months.August": "Agosto",- "months.December": "Dezembro",- "months.February": "Fevereiro",- "months.January": "Janeiro",- "months.July": "Julho",- "months.June": "junho",- "months.March": "Março",- "months.May": "Maio",- "months.November": "Novembro",- "months.October": "Outubro",- "months.September": "Setembro","operation.cancel": "Cancelar","operation.now": "Agora","operation.ok": "OK","operation.pickDate": "Escolher Data",+ "picker.chooseMonthAndYear": "Escolher mês e ano",+ "picker.endDate": "Data final",+ "picker.hour": "Hora",+ "picker.minute": "Minuto",+ "picker.month": "Mês",+ "picker.nextMonth": "Próximo mês",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Mês anterior",+ "picker.required": "Escolha um valor.",+ "picker.requiredLabel": "Obrigatório",+ "picker.startDate": "Data inicial",+ "picker.unavailable": "Esta data ou hora não está disponível.",+ "picker.year": "Ano","title.pickTime": "Escolha o Horário"}diff --git a/web/i18n/locales/pt-BR/workflow-integrations.json b/web/i18n/locales/pt-BR/workflow-integrations.jsonindex d9eb8d3abe1..1625ddc249e 100644--- a/web/i18n/locales/pt-BR/workflow-integrations.json+++ b/web/i18n/locales/pt-BR/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Próximos 5 tempos de execução","nodes.triggerSchedule.onMinute": "No Minuto","nodes.triggerSchedule.selectFrequency": "Selecionar frequência",- "nodes.triggerSchedule.selectTime": "Selecionar horário","nodes.triggerSchedule.title": "Agenda","nodes.triggerSchedule.useCronExpression": "Use expressão cron","nodes.triggerSchedule.useVisualPicker": "Usar seletor visual",diff --git a/web/i18n/locales/ro-RO/common.json b/web/i18n/locales/ro-RO/common.jsonindex 6652076e361..dc9b5eb9d94 100644--- a/web/i18n/locales/ro-RO/common.json+++ b/web/i18n/locales/ro-RO/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Ești sigur că vrei să îți ștergi fotografia de profil? Contul tău va folosi avatarul inițial implicit.","avatar.deleteTitle": "Îndepărtează avatarul","avatar.editAction": "Editează avatarul",- "calendar.selectedDate": "Selectată","chat.citation.characters": "Caractere:","chat.citation.hitCount": "Număr de recuperări:","chat.citation.hitScore": "Scor de recuperare:",diff --git a/web/i18n/locales/ro-RO/time.json b/web/i18n/locales/ro-RO/time.jsonindex 940c7c1878b..6e0ad833740 100644--- a/web/i18n/locales/ro-RO/time.json+++ b/web/i18n/locales/ro-RO/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "DD/MM/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Vineri",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Sat",- "daysInWeek.Sun": "Soare",- "daysInWeek.Thu": "Joia",- "daysInWeek.Tue": "Marți",- "daysInWeek.Wed": "Miercuri",- "defaultPlaceholder": "Alege o oră...",- "months.April": "Aprilie",- "months.August": "August",- "months.December": "Decembrie",- "months.February": "Februarie",- "months.January": "ianuarie",- "months.July": "Iulie",- "months.June": "Iunie",- "months.March": "Martie",- "months.May": "Mai",- "months.November": "Noiembrie",- "months.October": "Octombrie",- "months.September": "septembrie","operation.cancel": "Anulează","operation.now": "Acum","operation.ok": "Bine","operation.pickDate": "Alege o dată",+ "picker.chooseMonthAndYear": "Alege luna și anul",+ "picker.endDate": "Data de sfârșit",+ "picker.hour": "Oră",+ "picker.minute": "Minut",+ "picker.month": "Lună",+ "picker.nextMonth": "Luna următoare",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Luna precedentă",+ "picker.required": "Alege o valoare.",+ "picker.requiredLabel": "Obligatoriu",+ "picker.startDate": "Data de început",+ "picker.unavailable": "Această dată sau oră nu este disponibilă.",+ "picker.year": "An","title.pickTime": "Alegeți timpul"}diff --git a/web/i18n/locales/ro-RO/workflow-integrations.json b/web/i18n/locales/ro-RO/workflow-integrations.jsonindex 69582c5e7d5..ea4acdb215d 100644--- a/web/i18n/locales/ro-RO/workflow-integrations.json+++ b/web/i18n/locales/ro-RO/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Următoarele 5 momente de execuție","nodes.triggerSchedule.onMinute": "Într-un minut","nodes.triggerSchedule.selectFrequency": "Selectați frecvența",- "nodes.triggerSchedule.selectTime": "Selectează ora","nodes.triggerSchedule.title": "Program","nodes.triggerSchedule.useCronExpression": "Utilizați expresie cron","nodes.triggerSchedule.useVisualPicker": "Utilizați selectorul vizual",diff --git a/web/i18n/locales/ru-RU/common.json b/web/i18n/locales/ru-RU/common.jsonindex f80bff96605..9081d161a8f 100644--- a/web/i18n/locales/ru-RU/common.json+++ b/web/i18n/locales/ru-RU/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Вы уверены, что хотите удалить свою фотографию профиля? Ваш аккаунт будет использовать стандартный аватар.","avatar.deleteTitle": "Удалить аватар","avatar.editAction": "Изменить аватар",- "calendar.selectedDate": "Выбрана","chat.citation.characters": "Символы:","chat.citation.hitCount": "Количество совпадений:","chat.citation.hitScore": "Оценка совпадения:",diff --git a/web/i18n/locales/ru-RU/time.json b/web/i18n/locales/ru-RU/time.jsonindex 80d96fb1573..c68967fe09d 100644--- a/web/i18n/locales/ru-RU/time.json+++ b/web/i18n/locales/ru-RU/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "DD.MM.YYYY HH:mm:ss",- "daysInWeek.Fri": "Свободно",- "daysInWeek.Mon": "Мой",- "daysInWeek.Sat": "Суббота",- "daysInWeek.Sun": "Солнце",- "daysInWeek.Thu": "Четверг",- "daysInWeek.Tue": "Вторник",- "daysInWeek.Wed": "Сряда",- "defaultPlaceholder": "Выберите время...",- "months.April": "Апрель",- "months.August": "Август",- "months.December": "Декабрь",- "months.February": "Февраль",- "months.January": "Январь",- "months.July": "Июль",- "months.June": "Июнь",- "months.March": "Март",- "months.May": "Май",- "months.November": "Ноябрь",- "months.October": "Октябрь",- "months.September": "Сентябрь","operation.cancel": "Отмена","operation.now": "Теперь","operation.ok": "Хорошо","operation.pickDate": "Выберите дату",+ "picker.chooseMonthAndYear": "Выберите месяц и год",+ "picker.endDate": "Дата окончания",+ "picker.hour": "Час",+ "picker.minute": "Минута",+ "picker.month": "Месяц",+ "picker.nextMonth": "Следующий месяц",+ "picker.period": "До/после полудня",+ "picker.previousMonth": "Предыдущий месяц",+ "picker.required": "Выберите значение.",+ "picker.requiredLabel": "Обязательное поле",+ "picker.startDate": "Дата начала",+ "picker.unavailable": "Эта дата или время недоступны.",+ "picker.year": "Год","title.pickTime": "Выберите время"}diff --git a/web/i18n/locales/ru-RU/workflow-integrations.json b/web/i18n/locales/ru-RU/workflow-integrations.jsonindex 6d1e1886e3b..3ef924bb793 100644--- a/web/i18n/locales/ru-RU/workflow-integrations.json+++ b/web/i18n/locales/ru-RU/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Следующие 5 времен выполнения","nodes.triggerSchedule.onMinute": "На минуту","nodes.triggerSchedule.selectFrequency": "Выберите частоту",- "nodes.triggerSchedule.selectTime": "Выбрать время","nodes.triggerSchedule.title": "Расписание","nodes.triggerSchedule.useCronExpression": "Используйте cron-выражение","nodes.triggerSchedule.useVisualPicker": "Использовать визуальный выбор",diff --git a/web/i18n/locales/sl-SI/common.json b/web/i18n/locales/sl-SI/common.jsonindex 7400ee967f3..d8710f7eb83 100644--- a/web/i18n/locales/sl-SI/common.json+++ b/web/i18n/locales/sl-SI/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Ali ste prepričani, da želite odstraniti svojo profilno sliko? Vaš račun bo uporabljal privzeti začetni avatar.","avatar.deleteTitle": "Odstrani avatar","avatar.editAction": "Uredi avatar",- "calendar.selectedDate": "Izbran","chat.citation.characters": "Znakov:","chat.citation.hitCount": "Število pridobivanja:","chat.citation.hitScore": "Rezultat pridobivanja:",diff --git a/web/i18n/locales/sl-SI/time.json b/web/i18n/locales/sl-SI/time.jsonindex 4d3fb6705d9..59b2fc82493 100644--- a/web/i18n/locales/sl-SI/time.json+++ b/web/i18n/locales/sl-SI/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "DD.MM.YYYY hh:mm:ss A",- "daysInWeek.Fri": "Petek",- "daysInWeek.Mon": "Mon",- "daysInWeek.Sat": "Satelit",- "daysInWeek.Sun": "Sonce",- "daysInWeek.Thu": "Četrtek",- "daysInWeek.Tue": "Torek",- "daysInWeek.Wed": "Sreda",- "defaultPlaceholder": "Izberi čas...",- "months.April": "April",- "months.August": "Avgust",- "months.December": "December",- "months.February": "Februar",- "months.January": "Januar",- "months.July": "Julij",- "months.June": "Junij",- "months.March": "Marec",- "months.May": "Maj",- "months.November": "November",- "months.October": "oktober",- "months.September": "September","operation.cancel": "Prekliči","operation.now": "Zdaj","operation.ok": "V redu","operation.pickDate": "Izberi datum",+ "picker.chooseMonthAndYear": "Izberite mesec in leto",+ "picker.endDate": "Končni datum",+ "picker.hour": "Ura",+ "picker.minute": "Minuta",+ "picker.month": "Mesec",+ "picker.nextMonth": "Naslednji mesec",+ "picker.period": "AM/PM",+ "picker.previousMonth": "Prejšnji mesec",+ "picker.required": "Izberite vrednost.",+ "picker.requiredLabel": "Obvezno",+ "picker.startDate": "Začetni datum",+ "picker.unavailable": "Ta datum ali čas ni na voljo.",+ "picker.year": "Leto","title.pickTime": "Izberi čas"}diff --git a/web/i18n/locales/sl-SI/workflow-integrations.json b/web/i18n/locales/sl-SI/workflow-integrations.jsonindex 237bf2a049a..ed42af9dc8d 100644--- a/web/i18n/locales/sl-SI/workflow-integrations.json+++ b/web/i18n/locales/sl-SI/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Naslednjih 5 časov izvajanja","nodes.triggerSchedule.onMinute": "Na minuto","nodes.triggerSchedule.selectFrequency": "Izberite frekvenco",- "nodes.triggerSchedule.selectTime": "Izberi čas","nodes.triggerSchedule.title": "Urnik","nodes.triggerSchedule.useCronExpression": "Uporabi cron izraz","nodes.triggerSchedule.useVisualPicker": "Uporabi vizualni izbirnik",diff --git a/web/i18n/locales/th-TH/common.json b/web/i18n/locales/th-TH/common.jsonindex 7b118af0822..7bcbe023d6e 100644--- a/web/i18n/locales/th-TH/common.json+++ b/web/i18n/locales/th-TH/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "คุณแน่ใจหรือไม่ว่าต้องการลบรูปโปรไฟล์ของคุณ? บัญชีของคุณจะใช้รูปโปรไฟล์เริ่มต้นตามค่าเริ่มต้น.","avatar.deleteTitle": "ลบอวตาร","avatar.editAction": "แก้ไขอวตาร",- "calendar.selectedDate": "เลือกแล้ว","chat.citation.characters": "อักขระ:","chat.citation.hitCount": "จํานวนการดึงข้อมูล:","chat.citation.hitScore": "คะแนนการดึงข้อมูล:",diff --git a/web/i18n/locales/th-TH/time.json b/web/i18n/locales/th-TH/time.jsonindex eefee97737d..145e0cd400f 100644--- a/web/i18n/locales/th-TH/time.json+++ b/web/i18n/locales/th-TH/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "MM/DD/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "เสรี",- "daysInWeek.Mon": "มอน",- "daysInWeek.Sat": "เสาร์",- "daysInWeek.Sun": "ดวงอาทิตย์",- "daysInWeek.Thu": "วันพฤหัสบดี",- "daysInWeek.Tue": "อังคาร",- "daysInWeek.Wed": "วันพุธ",- "defaultPlaceholder": "เลือกเวลา...",- "months.April": "เมษายน",- "months.August": "สิงหาคม",- "months.December": "ธันวาคม",- "months.February": "กุมภาพันธ์",- "months.January": "มกราคม",- "months.July": "กรกฎาคม",- "months.June": "มิถุนายน",- "months.March": "มีนาคม",- "months.May": "พฤษภาคม",- "months.November": "พฤศจิกายน",- "months.October": "ตุลาคม",- "months.September": "กันยายน","operation.cancel": "ยกเลิก","operation.now": "ตอนนี้","operation.ok": "ตกลง","operation.pickDate": "เลือกวันที่",+ "picker.chooseMonthAndYear": "เลือกเดือนและปี",+ "picker.endDate": "วันที่สิ้นสุด",+ "picker.hour": "ชั่วโมง",+ "picker.minute": "นาที",+ "picker.month": "เดือน",+ "picker.nextMonth": "เดือนถัดไป",+ "picker.period": "ก่อน/หลังเที่ยง",+ "picker.previousMonth": "เดือนก่อนหน้า",+ "picker.required": "โปรดเลือกค่า",+ "picker.requiredLabel": "จำเป็น",+ "picker.startDate": "วันที่เริ่มต้น",+ "picker.unavailable": "ไม่สามารถเลือกวันที่หรือเวลานี้ได้",+ "picker.year": "ปี","title.pickTime": "เลือกเวลา"}diff --git a/web/i18n/locales/th-TH/workflow-integrations.json b/web/i18n/locales/th-TH/workflow-integrations.jsonindex 34b64247c76..45801a8dd6d 100644--- a/web/i18n/locales/th-TH/workflow-integrations.json+++ b/web/i18n/locales/th-TH/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "เวลาการประมวลผล 5 ครั้งถัดไป","nodes.triggerSchedule.onMinute": "ในนาที","nodes.triggerSchedule.selectFrequency": "เลือกความถี่",- "nodes.triggerSchedule.selectTime": "เลือกเวลา","nodes.triggerSchedule.title": "ตารางเวลา","nodes.triggerSchedule.useCronExpression": "ใช้สำนวน cron","nodes.triggerSchedule.useVisualPicker": "ใช้ตัวเลือกแบบภาพ",diff --git a/web/i18n/locales/tr-TR/common.json b/web/i18n/locales/tr-TR/common.jsonindex 06688adf00e..d37f2947b75 100644--- a/web/i18n/locales/tr-TR/common.json+++ b/web/i18n/locales/tr-TR/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Profil resminizi kaldırmak istediğinize emin misiniz? Hesabınız varsayılan başlangıç avatarını kullanacaktır.","avatar.deleteTitle": "Avatarı kaldır","avatar.editAction": "Avatarı düzenle",- "calendar.selectedDate": "Seçili","chat.citation.characters": "Karakterler:","chat.citation.hitCount": "Geri Alım Sayısı:","chat.citation.hitScore": "Geri Alım Skoru:",diff --git a/web/i18n/locales/tr-TR/time.json b/web/i18n/locales/tr-TR/time.jsonindex 190123d5085..3df4fdfc00f 100644--- a/web/i18n/locales/tr-TR/time.json+++ b/web/i18n/locales/tr-TR/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD/MM/YYYY HH:mm",- "dateFormats.display": "D MMMM YYYY",- "dateFormats.displayWithTime": "D MMMM YYYY hh:mm A","dateFormats.withSeconds": "DD/MM/YYYY HH:mm:ss",- "daysInWeek.Fri": "Cum",- "daysInWeek.Mon": "Pzt",- "daysInWeek.Sat": "Cmt",- "daysInWeek.Sun": "Paz",- "daysInWeek.Thu": "Per",- "daysInWeek.Tue": "Sal",- "daysInWeek.Wed": "Çar",- "defaultPlaceholder": "Bir zaman seç...",- "months.April": "Nisan",- "months.August": "Ağustos",- "months.December": "Aralık",- "months.February": "Şubat",- "months.January": "Ocak",- "months.July": "Temmuz",- "months.June": "Haziran",- "months.March": "Mart",- "months.May": "Mayıs",- "months.November": "Kasım",- "months.October": "Ekim",- "months.September": "Eylül","operation.cancel": "İptal","operation.now": "Şimdi","operation.ok": "Tamam","operation.pickDate": "Tarih Seç",+ "picker.chooseMonthAndYear": "Ay ve yıl seçin",+ "picker.endDate": "Bitiş tarihi",+ "picker.hour": "Saat",+ "picker.minute": "Dakika",+ "picker.month": "Ay",+ "picker.nextMonth": "Sonraki ay",+ "picker.period": "ÖÖ/ÖS",+ "picker.previousMonth": "Önceki ay",+ "picker.required": "Bir değer seçin.",+ "picker.requiredLabel": "Zorunlu",+ "picker.startDate": "Başlangıç tarihi",+ "picker.unavailable": "Bu tarih veya saat kullanılamıyor.",+ "picker.year": "Yıl","title.pickTime": "Zamanı Seç"}diff --git a/web/i18n/locales/tr-TR/workflow-integrations.json b/web/i18n/locales/tr-TR/workflow-integrations.jsonindex cbd4bd7cb7f..6d23eb4522e 100644--- a/web/i18n/locales/tr-TR/workflow-integrations.json+++ b/web/i18n/locales/tr-TR/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Sonraki 5 yürütme zamanı","nodes.triggerSchedule.onMinute": "On Dakika","nodes.triggerSchedule.selectFrequency": "Frekansı seç",- "nodes.triggerSchedule.selectTime": "Zaman seç","nodes.triggerSchedule.title": "Program","nodes.triggerSchedule.useCronExpression": "Cron ifadesi kullan","nodes.triggerSchedule.useVisualPicker": "Görsel seçici kullan",diff --git a/web/i18n/locales/uk-UA/common.json b/web/i18n/locales/uk-UA/common.jsonindex 8958a016432..7e4ba183565 100644--- a/web/i18n/locales/uk-UA/common.json+++ b/web/i18n/locales/uk-UA/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Ви впевнені, що хочете видалити своє фото профілю? Ваш обліковий запис використовуватиме стандартний початковий аватар.","avatar.deleteTitle": "Видалити аватар","avatar.editAction": "Редагувати аватар",- "calendar.selectedDate": "Вибрано","chat.citation.characters": "Символів:","chat.citation.hitCount": "Кількість звернень:","chat.citation.hitScore": "Оцінка звернення:",diff --git a/web/i18n/locales/uk-UA/time.json b/web/i18n/locales/uk-UA/time.jsonindex 45a67b73e8a..06d2186f81c 100644--- a/web/i18n/locales/uk-UA/time.json+++ b/web/i18n/locales/uk-UA/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD.MM.YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Вільний",- "daysInWeek.Mon": "Мон",- "daysInWeek.Sat": "Субота",- "daysInWeek.Sun": "Сонце",- "daysInWeek.Thu": "Четвер",- "daysInWeek.Tue": "Вівторок",- "daysInWeek.Wed": "Середа",- "defaultPlaceholder": "Виберіть час...",- "months.April": "Квітень",- "months.August": "Серпень",- "months.December": "Грудень",- "months.February": "Лютий",- "months.January": "Січень",- "months.July": "Липень",- "months.June": "Червень",- "months.March": "Березень",- "months.May": "Травень",- "months.November": "Листопад",- "months.October": "Жовтень",- "months.September": "Вересень","operation.cancel": "Скасувати","operation.now": "Тепер","operation.ok": "Добре","operation.pickDate": "Виберіть дату",+ "picker.chooseMonthAndYear": "Виберіть місяць і рік",+ "picker.endDate": "Дата завершення",+ "picker.hour": "Година",+ "picker.minute": "Хвилина",+ "picker.month": "Місяць",+ "picker.nextMonth": "Наступний місяць",+ "picker.period": "До/після полудня",+ "picker.previousMonth": "Попередній місяць",+ "picker.required": "Виберіть значення.",+ "picker.requiredLabel": "Обов’язкове поле",+ "picker.startDate": "Дата початку",+ "picker.unavailable": "Ця дата або час недоступні.",+ "picker.year": "Рік","title.pickTime": "Виберіть час"}diff --git a/web/i18n/locales/uk-UA/workflow-integrations.json b/web/i18n/locales/uk-UA/workflow-integrations.jsonindex 33850d31f03..11ecf371856 100644--- a/web/i18n/locales/uk-UA/workflow-integrations.json+++ b/web/i18n/locales/uk-UA/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "Наступні 5 разів виконання","nodes.triggerSchedule.onMinute": "Що хвилина","nodes.triggerSchedule.selectFrequency": "Виберіть частоту",- "nodes.triggerSchedule.selectTime": "Виберіть час","nodes.triggerSchedule.title": "Розклад","nodes.triggerSchedule.useCronExpression": "Використовувати cron-вираз","nodes.triggerSchedule.useVisualPicker": "Використати візуальний вибір",diff --git a/web/i18n/locales/vi-VN/common.json b/web/i18n/locales/vi-VN/common.jsonindex bf3eff83b81..ee50dbaac03 100644--- a/web/i18n/locales/vi-VN/common.json+++ b/web/i18n/locales/vi-VN/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "Bạn có chắc chắn muốn xóa ảnh đại diện của mình không? Tài khoản của bạn sẽ sử dụng avatar mặc định.","avatar.deleteTitle": "Xóa Ảnh Đại Diện","avatar.editAction": "Chỉnh Sửa Ảnh Đại Diện",- "calendar.selectedDate": "Đã chọn","chat.citation.characters": "Ký tự:","chat.citation.hitCount": "Số lượt truy xuất:","chat.citation.hitScore": "Điểm truy xuất:",diff --git a/web/i18n/locales/vi-VN/time.json b/web/i18n/locales/vi-VN/time.jsonindex d33b4f001bd..a28cc1c1db7 100644--- a/web/i18n/locales/vi-VN/time.json+++ b/web/i18n/locales/vi-VN/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "DD/MM/YYYY HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "MM/DD/YYYY hh:mm:ss A",- "daysInWeek.Fri": "Thứ Sáu",- "daysInWeek.Mon": "Môn",- "daysInWeek.Sat": "Ngồi",- "daysInWeek.Sun": "Mặt trời",- "daysInWeek.Thu": "Thu",- "daysInWeek.Tue": "Thứ Ba",- "daysInWeek.Wed": "Thứ Tư",- "defaultPlaceholder": "Chọn một thời gian...",- "months.April": "Tháng Tư",- "months.August": "Tháng Tám",- "months.December": "Tháng Mười Hai",- "months.February": "Tháng Hai",- "months.January": "Tháng Một",- "months.July": "Tháng Bảy",- "months.June": "Tháng Sáu",- "months.March": "Tháng Ba",- "months.May": "Tháng Năm",- "months.November": "Tháng Mười Một",- "months.October": "Tháng Mười",- "months.September": "Tháng Chín","operation.cancel": "Hủy bỏ","operation.now": "Bây giờ","operation.ok": "Được rồi","operation.pickDate": "Chọn Ngày",+ "picker.chooseMonthAndYear": "Chọn tháng và năm",+ "picker.endDate": "Ngày kết thúc",+ "picker.hour": "Giờ",+ "picker.minute": "Phút",+ "picker.month": "Tháng",+ "picker.nextMonth": "Tháng sau",+ "picker.period": "SA/CH",+ "picker.previousMonth": "Tháng trước",+ "picker.required": "Chọn một giá trị.",+ "picker.requiredLabel": "Bắt buộc",+ "picker.startDate": "Ngày bắt đầu",+ "picker.unavailable": "Ngày hoặc giờ này không khả dụng.",+ "picker.year": "Năm","title.pickTime": "Chọn Thời Gian"}diff --git a/web/i18n/locales/vi-VN/workflow-integrations.json b/web/i18n/locales/vi-VN/workflow-integrations.jsonindex 0c5264b4181..5023638674c 100644--- a/web/i18n/locales/vi-VN/workflow-integrations.json+++ b/web/i18n/locales/vi-VN/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "5 lần thực thi tiếp theo","nodes.triggerSchedule.onMinute": "Trong một phút","nodes.triggerSchedule.selectFrequency": "Chọn tần suất",- "nodes.triggerSchedule.selectTime": "Chọn thời gian","nodes.triggerSchedule.title": "Lịch trình","nodes.triggerSchedule.useCronExpression": "Sử dụng biểu thức cron","nodes.triggerSchedule.useVisualPicker": "Sử dụng trình chọn trực quan",diff --git a/web/i18n/locales/zh-Hans/common.json b/web/i18n/locales/zh-Hans/common.jsonindex cdcc832ef89..448903fee58 100644--- a/web/i18n/locales/zh-Hans/common.json+++ b/web/i18n/locales/zh-Hans/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "确定要删除你的个人头像吗?你的账号将使用默认的首字母头像。","avatar.deleteTitle": "删除头像","avatar.editAction": "编辑头像",- "calendar.selectedDate": "已选中","chat.citation.characters": "字符:","chat.citation.hitCount": "召回次数:","chat.citation.hitScore": "召回得分:",diff --git a/web/i18n/locales/zh-Hans/time.json b/web/i18n/locales/zh-Hans/time.jsonindex 4729d206a82..afbe72aa1ec 100644--- a/web/i18n/locales/zh-Hans/time.json+++ b/web/i18n/locales/zh-Hans/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "YYYY/MM/DD HH:mm",- "dateFormats.display": "YYYY年MM月DD日",- "dateFormats.displayWithTime": "YYYY年MM月DD日 HH:mm","dateFormats.withSeconds": "YYYY-MM-DD HH:mm:ss",- "daysInWeek.Fri": "五",- "daysInWeek.Mon": "一",- "daysInWeek.Sat": "六",- "daysInWeek.Sun": "日",- "daysInWeek.Thu": "四",- "daysInWeek.Tue": "二",- "daysInWeek.Wed": "三",- "defaultPlaceholder": "请选择时间...",- "months.April": "四月",- "months.August": "八月",- "months.December": "十二月",- "months.February": "二月",- "months.January": "一月",- "months.July": "七月",- "months.June": "六月",- "months.March": "三月",- "months.May": "五月",- "months.November": "十一月",- "months.October": "十月",- "months.September": "九月","operation.cancel": "取消","operation.now": "此刻","operation.ok": "确定","operation.pickDate": "选择日期",+ "picker.chooseMonthAndYear": "选择月份和年份",+ "picker.endDate": "结束日期",+ "picker.hour": "小时",+ "picker.minute": "分钟",+ "picker.month": "月份",+ "picker.nextMonth": "下个月",+ "picker.period": "上午或下午",+ "picker.previousMonth": "上个月",+ "picker.required": "请选择一个值。",+ "picker.requiredLabel": "必填",+ "picker.startDate": "开始日期",+ "picker.unavailable": "此日期或时间不可用。",+ "picker.year": "年份","title.pickTime": "选择时间"}diff --git a/web/i18n/locales/zh-Hans/workflow-integrations.json b/web/i18n/locales/zh-Hans/workflow-integrations.jsonindex 7efdc7ce647..a4ccd19be3a 100644--- a/web/i18n/locales/zh-Hans/workflow-integrations.json+++ b/web/i18n/locales/zh-Hans/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "接下来 5 次执行时间","nodes.triggerSchedule.onMinute": "分钟","nodes.triggerSchedule.selectFrequency": "选择频率",- "nodes.triggerSchedule.selectTime": "选择时间","nodes.triggerSchedule.title": "定时触发","nodes.triggerSchedule.useCronExpression": "使用 Cron 表达式","nodes.triggerSchedule.useVisualPicker": "使用可视化配置",diff --git a/web/i18n/locales/zh-Hant/common.json b/web/i18n/locales/zh-Hant/common.jsonindex ea64c55fcc1..5ac701b12ed 100644--- a/web/i18n/locales/zh-Hant/common.json+++ b/web/i18n/locales/zh-Hant/common.json@@ -47,7 +47,6 @@"avatar.deleteDescription": "您確定要刪除您的個人資料照片嗎?您的帳戶將使用默認的初始頭像。","avatar.deleteTitle": "移除頭像","avatar.editAction": "編輯頭像",- "calendar.selectedDate": "已選取","chat.citation.characters": "字元:","chat.citation.hitCount": "檢索次數:","chat.citation.hitScore": "檢索得分:",diff --git a/web/i18n/locales/zh-Hant/time.json b/web/i18n/locales/zh-Hant/time.jsonindex 435bf5fd32f..7ffa4f411f2 100644--- a/web/i18n/locales/zh-Hant/time.json+++ b/web/i18n/locales/zh-Hant/time.json@@ -1,31 +1,22 @@{"dateFormats.compact": "YYYY/MM/DD HH:mm",- "dateFormats.display": "MMMM D, YYYY",- "dateFormats.displayWithTime": "MMMM D, YYYY hh:mm A","dateFormats.withSeconds": "YYYY-MM-DD HH:mm:ss",- "daysInWeek.Fri": "五",- "daysInWeek.Mon": "一",- "daysInWeek.Sat": "六",- "daysInWeek.Sun": "日",- "daysInWeek.Thu": "四",- "daysInWeek.Tue": "二",- "daysInWeek.Wed": "三",- "defaultPlaceholder": "選擇一個時間...",- "months.April": "四月",- "months.August": "八月",- "months.December": "十二月",- "months.February": "二月",- "months.January": "一月",- "months.July": "七月",- "months.June": "六月",- "months.March": "三月",- "months.May": "五月",- "months.November": "十一月",- "months.October": "十月",- "months.September": "九月","operation.cancel": "取消","operation.now": "現在","operation.ok": "好","operation.pickDate": "選擇日期",+ "picker.chooseMonthAndYear": "選擇月份和年份",+ "picker.endDate": "結束日期",+ "picker.hour": "小時",+ "picker.minute": "分鐘",+ "picker.month": "月份",+ "picker.nextMonth": "下個月",+ "picker.period": "上午或下午",+ "picker.previousMonth": "上個月",+ "picker.required": "請選擇一個值。",+ "picker.requiredLabel": "必填",+ "picker.startDate": "開始日期",+ "picker.unavailable": "此日期或時間無法使用。",+ "picker.year": "年份","title.pickTime": "選擇時間"}diff --git a/web/i18n/locales/zh-Hant/workflow-integrations.json b/web/i18n/locales/zh-Hant/workflow-integrations.jsonindex 1ed7c059eb0..88dc8599fd3 100644--- a/web/i18n/locales/zh-Hant/workflow-integrations.json+++ b/web/i18n/locales/zh-Hant/workflow-integrations.json@@ -45,7 +45,6 @@"nodes.triggerSchedule.nextExecutionTimes": "接下來的 5 次執行時間","nodes.triggerSchedule.onMinute": "在一分鐘內","nodes.triggerSchedule.selectFrequency": "選擇頻率",- "nodes.triggerSchedule.selectTime": "選擇時間","nodes.triggerSchedule.title": "時間表","nodes.triggerSchedule.useCronExpression": "使用 cron 表達式","nodes.triggerSchedule.useVisualPicker": "使用視覺選擇器",diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.tsindex 4173bed5986..543baabf210 100644--- a/web/i18n/resources.generated.d.ts+++ b/web/i18n/resources.generated.d.ts@@ -1590,7 +1590,6 @@ export default interface Resources {'avatar.deleteDescription': 'Are you sure you want to remove your profile picture? Your account will use the default initial avatar.''avatar.deleteTitle': 'Remove Avatar''avatar.editAction': 'Edit Avatar'- 'calendar.selectedDate': 'Selected''chat.citation.characters': 'Characters:''chat.citation.hitCount': 'Retrieval count:''chat.citation.hitScore': 'Retrieval Score:'@@ -4519,33 +4518,24 @@ export default interface Resources {}time: {'dateFormats.compact': 'MM/DD/YYYY HH:mm'- 'dateFormats.display': 'MMMM D, YYYY'- 'dateFormats.displayWithTime': 'MMMM D, YYYY hh:mm A''dateFormats.withSeconds': 'MM/DD/YYYY hh:mm:ss A'- 'daysInWeek.Fri': 'Fri'- 'daysInWeek.Mon': 'Mon'- 'daysInWeek.Sat': 'Sat'- 'daysInWeek.Sun': 'Sun'- 'daysInWeek.Thu': 'Thu'- 'daysInWeek.Tue': 'Tue'- 'daysInWeek.Wed': 'Wed'- defaultPlaceholder: 'Pick a time...'- 'months.April': 'April'- 'months.August': 'August'- 'months.December': 'December'- 'months.February': 'February'- 'months.January': 'January'- 'months.July': 'July'- 'months.June': 'June'- 'months.March': 'March'- 'months.May': 'May'- 'months.November': 'November'- 'months.October': 'October'- 'months.September': 'September''operation.cancel': 'Cancel''operation.now': 'Now''operation.ok': 'OK''operation.pickDate': 'Pick Date'+ 'picker.chooseMonthAndYear': 'Choose month and year'+ 'picker.endDate': 'End date'+ 'picker.hour': 'Hour'+ 'picker.minute': 'Minute'+ 'picker.month': 'Month'+ 'picker.nextMonth': 'Next month'+ 'picker.period': 'AM/PM'+ 'picker.previousMonth': 'Previous month'+ 'picker.required': 'Choose a value.'+ 'picker.requiredLabel': 'Required'+ 'picker.startDate': 'Start date'+ 'picker.unavailable': 'This date or time is unavailable.'+ 'picker.year': 'Year''title.pickTime': 'Pick Time'}tools: {@@ -5731,7 +5721,6 @@ export default interface Resources {'nodes.triggerSchedule.nextExecutionTimes': 'Next 5 execution times''nodes.triggerSchedule.onMinute': 'On Minute''nodes.triggerSchedule.selectFrequency': 'Select frequency'- 'nodes.triggerSchedule.selectTime': 'Select time''nodes.triggerSchedule.title': 'Schedule''nodes.triggerSchedule.useCronExpression': 'Use cron expression''nodes.triggerSchedule.useVisualPicker': 'Use visual picker'diff --git a/web/package.json b/web/package.jsonindex c948011a869..7010fdfb09f 100644--- a/web/package.json+++ b/web/package.json@@ -40,6 +40,7 @@"@amplitude/analytics-browser": "catalog:","@amplitude/plugin-session-replay-browser": "catalog:","@base-ui/react": "catalog:",+ "@daypicker/react": "catalog:","@floating-ui/react": "catalog:","@formatjs/intl-localematcher": "catalog:","@heroicons/react": "catalog:",@@ -72,6 +73,7 @@"class-variance-authority": "catalog:","copy-to-clipboard": "catalog:","cron-parser": "catalog:",+ "date-fns": "catalog:","dayjs": "catalog:","decimal.js": "catalog:","dompurify": "catalog:",diff --git a/web/utils/timezone.ts b/web/utils/timezone.tsindex 19abbc8c216..84a18666105 100644--- a/web/utils/timezone.ts+++ b/web/utils/timezone.ts@@ -11,3 +11,23 @@ export const getBrowserTimezone = () => {return new Intl.DateTimeFormat().resolvedOptions().timeZone || undefined}++const DEFAULT_OFFSET_STR = 'UTC+0'++export const convertTimezoneToOffsetStr = (timezone?: string) => {+ if (!timezone) return DEFAULT_OFFSET_STR+ const tzItem = tz.find((item) => item.value === timezone)+ if (!tzItem) return DEFAULT_OFFSET_STR+ // Extract offset from name format like "-11:00 Niue Time" or "+05:30 India Time"+ // Name format is always "{offset}:{minutes} {timezone name}"+ const offsetMatch = /^([+-]?\d{1,2}):(\d{2})/.exec(tzItem.name)+ /* v8 ignore next 2 -- timezone.json entries are normalized to "{offset} {name}"; this protects against malformed data only. */+ if (!offsetMatch) return DEFAULT_OFFSET_STR+ // Parse hours and minutes separately+ const hours = Number.parseInt(offsetMatch[1]!, 10)+ const minutes = Number.parseInt(offsetMatch[2]!, 10)+ const sign = hours >= 0 ? '+' : ''+ // If minutes are non-zero, include them in the output (e.g., "UTC+5:30")+ // Otherwise, only show hours (e.g., "UTC+8")+ return minutes !== 0 ? `UTC${sign}${hours}:${offsetMatch[2]}` : `UTC${sign}${hours}`+}