Repository: wojtekmaj/react-daterange-picker Branch: main Commit: 6f19427d70e9 Files: 48 Total size: 117.5 KB Directory structure: gitextract_9pvwexcp/ ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ └── workflows/ │ ├── ci.yml │ ├── close-stale-issues.yml │ └── publish.yml ├── .gitignore ├── .husky/ │ └── pre-commit ├── .vscode/ │ ├── extensions.json │ └── settings.json ├── .yarnrc.yml ├── LICENSE ├── biome.json ├── package.json ├── packages/ │ └── react-daterange-picker/ │ ├── LICENSE │ ├── README.md │ ├── package.json │ ├── src/ │ │ ├── DateRangePicker.css │ │ ├── DateRangePicker.spec.tsx │ │ ├── DateRangePicker.tsx │ │ ├── index.ts │ │ └── shared/ │ │ └── types.ts │ ├── tsconfig.build.json │ ├── tsconfig.json │ └── vitest.config.ts ├── sample/ │ ├── .gitignore │ ├── Sample.css │ ├── Sample.tsx │ ├── index.html │ ├── index.tsx │ ├── package.json │ ├── tsconfig.json │ └── vite.config.ts └── test/ ├── .gitignore ├── LocaleOptions.tsx ├── MaxDetailOptions.tsx ├── MinDetailOptions.tsx ├── Test.css ├── Test.tsx ├── ValidityOptions.tsx ├── ValueOptions.tsx ├── ViewOptions.tsx ├── global.d.ts ├── index.html ├── index.tsx ├── package.json ├── shared/ │ └── types.ts ├── tsconfig.json └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto # Custom for Visual Studio *.cs diff=csharp # Standard to msysgit *.doc diff=astextplain *.DOC diff=astextplain *.docx diff=astextplain *.DOCX diff=astextplain *.dot diff=astextplain *.DOT diff=astextplain *.pdf diff=astextplain *.PDF diff=astextplain *.rtf diff=astextplain *.RTF diff=astextplain ================================================ FILE: .github/FUNDING.yml ================================================ github: wojtekmaj open_collective: react-date-picker ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: ['*'] pull_request: branches: [main] env: HUSKY: 0 jobs: lint: name: Static code analysis runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Biome uses: biomejs/setup-biome@v2 - name: Run tests run: biome lint typescript: name: Type checking runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v6 - name: Cache Yarn cache uses: actions/cache@v5 env: cache-name: yarn-cache with: path: ~/.yarn/berry/cache key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-${{ env.cache-name }} - name: Use Node.js uses: actions/setup-node@v6 with: node-version: '24' - name: Install Corepack run: npm install -g corepack - name: Install dependencies run: yarn --immutable env: PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: true - name: Build package run: yarn build - name: Run type checking run: yarn tsc format: name: Formatting runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v6 - name: Setup Biome uses: biomejs/setup-biome@v2 - name: Run formatting run: biome format unit: name: Unit tests runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v6 - name: Cache Yarn cache uses: actions/cache@v5 env: cache-name: yarn-cache with: path: ~/.yarn/berry/cache key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-${{ env.cache-name }} - name: Cache ~/.cache/ms-playwright id: playwright-cache uses: actions/cache@v5 env: cache-name: playwright-cache with: path: ~/.cache/ms-playwright key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} - name: Use Node.js uses: actions/setup-node@v6 with: node-version: '24' - name: Install Corepack run: npm install -g corepack - name: Install dependencies run: yarn --immutable - name: Install Playwright browsers if: steps.playwright-cache.outputs.cache-hit != 'true' run: yarn workspace @wojtekmaj/react-daterange-picker playwright install chromium-headless-shell - name: Run tests run: yarn unit ================================================ FILE: .github/workflows/close-stale-issues.yml ================================================ name: Close stale issues on: schedule: - cron: '0 0 * * 1' # Every Monday workflow_dispatch: jobs: close-issues: name: Close stale issues runs-on: ubuntu-24.04-arm steps: - name: Close stale issues uses: actions/stale@v8 with: days-before-issue-stale: 90 days-before-issue-close: 14 stale-issue-label: 'stale' stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this issue will be closed in 14 days.' close-issue-message: 'This issue was closed because it has been stalled for 14 days with no activity.' exempt-issue-labels: 'fresh' remove-issue-stale-when-updated: true days-before-pr-stale: -1 days-before-pr-close: -1 ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish on: release: types: [published] env: HUSKY: 0 permissions: id-token: write jobs: publish: name: Publish runs-on: ubuntu-24.04-arm steps: - name: Checkout uses: actions/checkout@v6 - name: Cache Yarn cache uses: actions/cache@v5 env: cache-name: yarn-cache with: path: ~/.yarn/berry/cache key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-${{ env.cache-name }} - name: Use Node.js uses: actions/setup-node@v6 with: node-version: '24' registry-url: 'https://registry.npmjs.org' - name: Install Corepack run: npm install -g corepack - name: Install dependencies run: yarn --immutable - name: Publish with latest tag if: github.event.release.prerelease == false run: yarn npm publish --tag latest working-directory: packages/react-daterange-picker - name: Publish with next tag if: github.event.release.prerelease == true run: yarn npm publish --tag next working-directory: packages/react-daterange-picker ================================================ FILE: .gitignore ================================================ # OS .DS_Store # Cache .cache .playwright .tmp *.tsbuildinfo .eslintcache # Yarn .pnp.* **/.yarn/* !**/.yarn/patches !**/.yarn/plugins !**/.yarn/releases !**/.yarn/sdks !**/.yarn/versions # Project-generated directories and files __screenshots__ coverage dist node_modules playwright-report test-results package.tgz # Logs npm-debug.log yarn-error.log # .env files **/.env **/.env.* !**/.env.example ================================================ FILE: .husky/pre-commit ================================================ yarn format --staged --no-errors-on-unmatched --write ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": ["biomejs.biome"], "unwantedRecommendations": ["dbaeumer.jshint", "dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] } ================================================ FILE: .vscode/settings.json ================================================ { "editor.defaultFormatter": "biomejs.biome", "editor.formatOnSave": true, "search.exclude": { "**/.yarn": true } } ================================================ FILE: .yarnrc.yml ================================================ enableHardenedMode: false enableScripts: false logFilters: - code: YN0076 level: discard nodeLinker: node-modules ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2018–2026 Wojciech Maj Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: biome.json ================================================ { "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json", "files": { "includes": [ "**", "!**/.yarn", "!**/coverage", "!**/dist", "!**/.pnp.cjs", "!**/.pnp.loader.mjs" ] }, "assist": { "actions": { "source": { "organizeImports": { "level": "on", "options": { "groups": [ { "type": false, "source": ":NODE:" }, { "type": false, "source": ["vitest", "vitest/**", "@vitest/**", "vitest-*"] }, { "type": false, "source": ["react", "react-dom", "react-dom/**", "react-native"] }, { "type": false, "source": [":PACKAGE:"] }, ":BLANK_LINE:", { "type": false, "source": [ ":PATH:", "!**/hooks/*", "!**/use*.js", "!**/shared/*", "!**/utils/*", "!**/__mocks__/*", "!**/test-utils.js" ] }, ":BLANK_LINE:", { "type": false, "source": ["**/hooks/*", "**/use*.js"] }, ":BLANK_LINE:", { "type": false, "source": ["**/shared/*", "**/utils/*"] }, ":BLANK_LINE:", { "type": false, "source": "**/__mocks__/*" }, ":BLANK_LINE:", { "type": false, "source": "**/test-utils.js" }, ":BLANK_LINE:", ":NODE:", ":PACKAGE:", ":PATH:" ] } } } } }, "formatter": { "lineWidth": 100, "indentStyle": "space" }, "linter": { "rules": { "complexity": { "noUselessSwitchCase": "off" }, "correctness": { "noUnusedImports": "warn", "noUnusedVariables": { "level": "warn", "options": { "ignoreRestSiblings": true } } }, "suspicious": { "noConsole": "warn" } } }, "css": { "formatter": { "quoteStyle": "single" } }, "javascript": { "formatter": { "quoteStyle": "single" } }, "overrides": [ { "includes": ["**/vite.config.ts"], "linter": { "rules": { "suspicious": { "noConsole": "off" } } } } ] } ================================================ FILE: package.json ================================================ { "name": "@wojtekmaj/react-daterange-picker-monorepo", "version": "1.0.0", "description": "@wojtekmaj/react-daterange-picker monorepo", "type": "module", "workspaces": [ "packages/*", "test" ], "scripts": { "build": "yarn workspace @wojtekmaj/react-daterange-picker build", "dev": "yarn workspace @wojtekmaj/react-daterange-picker watch & yarn workspace test dev", "format": "yarn workspaces foreach --all run format", "lint": "yarn workspaces foreach --all run lint", "postinstall": "husky", "test": "yarn workspaces foreach --all run test", "tsc": "yarn workspaces foreach --all run tsc", "unit": "yarn workspaces foreach --all run unit" }, "devDependencies": { "husky": "^9.0.0" }, "packageManager": "yarn@4.10.3" } ================================================ FILE: packages/react-daterange-picker/LICENSE ================================================ MIT License Copyright (c) 2018–2026 Wojciech Maj Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: packages/react-daterange-picker/README.md ================================================ [![npm](https://img.shields.io/npm/v/@wojtekmaj/react-daterange-picker.svg)](https://www.npmjs.com/package/@wojtekmaj/react-daterange-picker) ![downloads](https://img.shields.io/npm/dt/@wojtekmaj/react-daterange-picker.svg) [![CI](https://github.com/wojtekmaj/react-daterange-picker/actions/workflows/ci.yml/badge.svg)](https://github.com/wojtekmaj/react-daterange-picker/actions) # React-DateRange-Picker A date range picker for your React app. - Pick days, months, years, or even decades - Supports virtually any language - No moment.js needed ## tl;dr - Install by executing `npm install @wojtekmaj/react-daterange-picker` or `yarn add @wojtekmaj/react-daterange-picker`. - Import by adding `import DateRangePicker from '@wojtekmaj/react-daterange-picker'`. - Use by adding ``. Use `onChange` prop for getting new values. ## Demo A minimal demo page can be found in `sample` directory. [Online demo](https://projects.wojtekmaj.pl/react-daterange-picker/) is also available! ## Consider native alternative If you don't need to support legacy browsers and don't need the advanced features this package provides, consider using native date input instead. It's more accessible, adds no extra weight to your bundle, and works better on mobile devices. ```tsx ``` ## Looking for a time picker or a datetime picker? React-DateRange-Picker will play nicely with [React-Date-Picker](https://github.com/wojtekmaj/react-date-picker), [React-Time-Picker](https://github.com/wojtekmaj/react-time-picker) and [React-DateTime-Picker](https://github.com/wojtekmaj/react-datetime-picker). Check them out! ## Getting started ### Compatibility Your project needs to use React 16.3 or later. If you use an older version of React, please refer to the table below to find a suitable React-DateRange-Picker version. | React version | Newest compatible React-DateRange-Picker version | | ------------- | ------------------------------------------------ | | ≥16.8 | latest | | ≥16.3 | 4.x | | ≥16.0 | 2.x | [React-Calendar](https://github.com/wojtekmaj/react-calendar), on which React-DateRange-Picker relies heavily, uses modern web technologies. That's why it's so fast, lightweight and easy to style. This, however, comes at a cost of [supporting only modern browsers](https://caniuse.com/#feat=internationalization). ### Installation Add React-DateRange-Picker to your project by executing `npm install @wojtekmaj/react-daterange-picker` or `yarn add @wojtekmaj/react-daterange-picker`. ### Usage Here's an example of basic usage: ```tsx import { useState } from 'react'; import DateRangePicker from '@wojtekmaj/react-daterange-picker'; type ValuePiece = Date | null; type Value = ValuePiece | [ValuePiece, ValuePiece]; function MyApp() { const [value, onChange] = useState([new Date(), new Date()]); return (
); } ``` ### Custom styling If you want to use default React-DateRange-Picker and React-Calendar styling to build upon it, you can import them by using: ```ts import '@wojtekmaj/react-daterange-picker/dist/DateRangePicker.css'; import 'react-calendar/dist/Calendar.css'; ``` ## User guide ### DateRangePicker Displays an input field complete with custom inputs, native input, and a calendar. #### Props | Prop name | Description | Default value | Example values | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | autoFocus | Automatically focuses the input on mount. | n/a | `true` | | calendarAriaLabel | `aria-label` for the calendar button. | n/a | `"Toggle calendar"` | | calendarProps | Props to pass to React-Calendar component. | n/a | See [React-Calendar documentation](https://github.com/wojtekmaj/react-calendar) | | calendarIcon | Content of the calendar button. Setting the value explicitly to `null` will hide the icon. | (default icon) | | | className | Class name(s) that will be added along with `"react-daterange-picker"` to the main React-DateRange-Picker `
` element. | n/a |
  • String: `"class1 class2"`
  • Array of strings: `["class1", "class2 class3"]`
| | clearAriaLabel | `aria-label` for the clear button. | n/a | `"Clear value"` | | clearIcon | Content of the clear button. Setting the value explicitly to `null` will hide the icon. | (default icon) |
  • String: `"Clear"`
  • React element: ``
  • React function: `ClearIcon`
| | closeCalendar | Whether to close the calendar on value selection. **Note**: It's recommended to use `shouldCloseCalendar` function instead. | `true` | `false` | | data-testid | `data-testid` attribute for the main React-DateRange-Picker `
` element. | n/a | `"daterange-picker"` | | dayAriaLabel | `aria-label` for the day input. | n/a | `"Day"` | | dayPlaceholder | `placeholder` for the day input. | `"--"` | `"dd"` | | disableCalendar | When set to `true`, will remove the calendar and the button toggling its visibility. | `false` | `true` | | disabled | Whether the date range picker should be disabled. | `false` | `true` | | format | Input format based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). Supported values are: `y`, `M`, `MM`, `MMM`, `MMMM`, `d`, `dd`. **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. | n/a | `"y-MM-dd"` | | id | `id` attribute for the main React-DateRange-Picker `
` element. | n/a | `"daterange-picker"` | | isOpen | Whether the calendar should be opened. | `false` | `true` | | locale | Locale that should be used by the date range picker and the calendar. Can be any [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag). **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. | Server locale/User's browser settings | `"hu-HU"` | | maxDate | Maximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although React-DateRange-Picker will ensure that no later date is selected. | n/a | Date: `new Date()` | | maxDetail | The most detailed calendar view that the user shall see. View defined here also becomes the one on which clicking an item in the calendar will select a date and pass it to onChange. Can be `"month"`, `"year"`, `"decade"` or `"century"`. | `"month"` | `"year"` | | minDate | Minimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although React-DateRange-Picker will ensure that no earlier date is selected. | n/a | Date: `new Date()` | | monthAriaLabel | `aria-label` for the month input. | n/a | `"Month"` | | monthPlaceholder | `placeholder` for the month input. | `"--"` | `"mm"` | | name | Input name prefix. Date from/Date to fields will be named `"yourprefix_from"` and `"yourprefix_to"` respectively. | `"daterange"` | `"myCustomName"` | | nativeInputAriaLabel | `aria-label` for the native date input. | n/a | `"Date"` | | onCalendarClose | Function called when the calendar closes. | n/a | `() => alert('Calendar closed')` | | onCalendarOpen | Function called when the calendar opens. | n/a | `() => alert('Calendar opened')` | | onChange | Function called when the user picks a valid date. If any of the fields were excluded using custom `format`, `new Date(y, 0, 1, 0, 0, 0)`, where `y` is the current year, is going to serve as a "base". | n/a | `(value) => alert('New date is: ', value)` | | onFocus | Function called when the user focuses an input. | n/a | `(event) => alert('Focused input: ', event.target.name)` | | onInvalidChange | Function called when the user picks an invalid date. | n/a | `() => alert('Invalid date')` | | openCalendarOnFocus | Whether to open the calendar on input focus. **Note**: It's recommended to use `shouldOpenCalendar` function instead. | `true` | `false` | | portalContainer | Element to render the calendar in using portal. | n/a | `document.getElementById('my-div')` | | rangeDivider | Divider between date inputs. | `"–"` | `" to "` | | required | Whether date input should be required. | `false` | `true` | | shouldCloseCalendar | Function called before the calendar closes. `reason` can be `"buttonClick"`, `"escape"`, `"outsideAction"`, or `"select"`. If it returns `false`, the calendar will not close. | n/a | `({ reason }) => reason !== 'outsideAction'` | | shouldOpenCalendar | Function called before the calendar opens. `reason` can be `"buttonClick"` or `"focus"`. If it returns `false`, the calendar will not open. | n/a | `({ reason }) => reason !== 'focus'` | | showLeadingZeros | Whether leading zeros should be rendered in date inputs. | `false` | `true` | | value | Input value. | n/a |
  • Date: `new Date(2017, 0, 1)`
  • String: `"2017-01-01"`
  • An array of dates: `[new Date(2017, 0, 1), new Date(2017, 7, 1)]`
  • An array of strings: `["2017-01-01", "2017-08-01"]`
| | yearAriaLabel | `aria-label` for the year input. | n/a | `"Year"` | | yearPlaceholder | `aria-label` for the year input. | `"----"` | `"yyyy"` | ### Calendar DateRangePicker component passes all props to React-Calendar, with the exception of `className` (you can use `calendarClassName` for that instead). There are tons of customizations you can do! For more information, see [Calendar component props](https://github.com/wojtekmaj/react-calendar#props). ## License The MIT License. ## Author
Wojciech Maj Wojciech Maj
================================================ FILE: packages/react-daterange-picker/package.json ================================================ { "name": "@wojtekmaj/react-daterange-picker", "version": "7.0.0", "description": "A date range picker for your React app.", "type": "module", "sideEffects": [ "*.css" ], "main": "./dist/index.js", "source": "./src/index.ts", "types": "./dist/index.d.ts", "exports": { ".": "./dist/index.js", "./*": "./*" }, "scripts": { "build": "yarn build-js && yarn copy-styles", "build-js": "tsc --project tsconfig.build.json", "clean": "node -e \"fs.rmSync('./dist', { recursive: true, force: true })\"", "copy-styles": "cpy 'src/**/*.css' dist", "format": "biome format", "lint": "biome lint", "prepack": "yarn clean && yarn build", "test": "yarn lint && yarn tsc && yarn format && yarn unit", "tsc": "tsc", "unit": "vitest", "watch": "yarn build-js --watch & node --eval \"fs.watch('src', () => child_process.exec('yarn copy-styles'))\"" }, "keywords": [ "calendar", "date", "date-picker", "date-range", "date-range-picker", "month-picker", "react" ], "author": { "name": "Wojciech Maj", "email": "kontakt@wojtekmaj.pl" }, "license": "MIT", "dependencies": { "clsx": "^2.0.0", "make-event-props": "^2.0.0", "react-calendar": "^6.0.0", "react-date-picker": "^12.0.1", "react-fit": "^3.0.0" }, "devDependencies": { "@biomejs/biome": "2.4.10", "@types/node": "*", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@vitest/browser-playwright": "^4.1.0", "cpy-cli": "^5.0.0", "playwright": "^1.55.1", "react": "^19.2.0", "react-dom": "^19.2.0", "typescript": "^6.0.2", "vitest": "^4.1.0", "vitest-browser-react": "^2.2.0" }, "peerDependencies": { "@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "peerDependenciesMeta": { "@types/react": { "optional": true } }, "publishConfig": { "access": "public", "provenance": true }, "files": [ "dist/**/*", "src/**/*", "!**/*.spec.ts", "!**/*.spec.tsx" ], "repository": { "type": "git", "url": "git+https://github.com/wojtekmaj/react-daterange-picker.git", "directory": "packages/react-daterange-picker" }, "funding": "https://github.com/wojtekmaj/react-daterange-picker?sponsor=1" } ================================================ FILE: packages/react-daterange-picker/src/DateRangePicker.css ================================================ .react-daterange-picker { display: inline-flex; position: relative; } .react-daterange-picker, .react-daterange-picker *, .react-daterange-picker *:before, .react-daterange-picker *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .react-daterange-picker--disabled { background-color: #f0f0f0; color: #6d6d6d; } .react-daterange-picker__wrapper { display: flex; flex-grow: 1; flex-shrink: 0; align-items: center; border: thin solid gray; } .react-daterange-picker__inputGroup { min-width: calc((4px * 3) + 0.54em * 8 + 0.217em * 2); height: 100%; flex-grow: 1; padding: 0 2px; box-sizing: content-box; } .react-daterange-picker__inputGroup__divider { padding: 1px 0; white-space: pre; } .react-daterange-picker__inputGroup__divider, .react-daterange-picker__inputGroup__leadingZero { display: inline-block; font: inherit; } .react-daterange-picker__inputGroup__input { min-width: 0.54em; height: 100%; position: relative; padding: 0 1px; border: 0; background: none; color: currentColor; font: inherit; box-sizing: content-box; -webkit-appearance: textfield; -moz-appearance: textfield; appearance: textfield; } .react-daterange-picker__inputGroup__input::-webkit-outer-spin-button, .react-daterange-picker__inputGroup__input::-webkit-inner-spin-button { -webkit-appearance: none; -moz-appearance: none; appearance: none; margin: 0; } .react-daterange-picker__inputGroup__input:invalid { background: rgba(255, 0, 0, 0.1); } .react-daterange-picker__inputGroup__input--hasLeadingZero { margin-left: -0.54em; padding-left: calc(1px + 0.54em); } .react-daterange-picker__button { border: 0; background: transparent; padding: 4px 6px; } .react-daterange-picker__button:enabled { cursor: pointer; } .react-daterange-picker__button:enabled:hover .react-daterange-picker__button__icon, .react-daterange-picker__button:enabled:focus .react-daterange-picker__button__icon { stroke: #0078d7; } .react-daterange-picker__button:disabled .react-daterange-picker__button__icon { stroke: #6d6d6d; } .react-daterange-picker__button svg { display: inherit; } .react-daterange-picker__calendar { width: 350px; max-width: 100vw; z-index: 1; } .react-daterange-picker__calendar--closed { display: none; } .react-daterange-picker__calendar .react-calendar { border-width: thin; } ================================================ FILE: packages/react-daterange-picker/src/DateRangePicker.spec.tsx ================================================ import { describe, expect, it, vi } from 'vitest'; import { page, userEvent } from 'vitest/browser'; import { render } from 'vitest-browser-react'; import { act } from 'react'; import DateRangePicker from './DateRangePicker.js'; import type { Locator } from 'vitest/browser'; async function waitForElementToBeRemovedOrHidden(callback: () => HTMLElement | null) { const element = callback(); if (element) { await vi.waitFor(() => expect(element).toHaveAttribute('class', expect.stringContaining('--closed')), ); } } describe('DateRangePicker', () => { const defaultProps = { dayAriaLabel: 'day', monthAriaLabel: 'month', yearAriaLabel: 'year', }; it('passes default name to DateInput components', async () => { const { container } = await render(); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs[0]).toHaveAttribute('name', 'daterange_from'); expect(nativeInputs[1]).toHaveAttribute('name', 'daterange_to'); }); it('passes custom name to DateInput components', async () => { const name = 'testName'; const { container } = await render(); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs[0]).toHaveAttribute('name', `${name}_from`); expect(nativeInputs[1]).toHaveAttribute('name', `${name}_to`); }); it('passes autoFocus flag to first DateInput component', async () => { await render(); const customInputs = page.getByRole('spinbutton'); expect(customInputs.nth(0)).toHaveFocus(); }); it('passes disabled flag to DateInput components', async () => { const { container } = await render(); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs[0]).toBeDisabled(); expect(nativeInputs[1]).toBeDisabled(); }); it('passes format to DateInput components', async () => { await render(); const customInputs = page.getByRole('spinbutton'); expect(customInputs).toHaveLength(2); expect(customInputs.nth(0)).toHaveAttribute('name', 'year'); expect(customInputs.nth(1)).toHaveAttribute('name', 'year'); }); it('passes aria-label props to DateInput components', async () => { const ariaLabelProps = { calendarAriaLabel: 'Toggle calendar', clearAriaLabel: 'Clear value', dayAriaLabel: 'Day', monthAriaLabel: 'Month', nativeInputAriaLabel: 'Date', yearAriaLabel: 'Year', }; const { container } = await render(); const calendarButton = page.getByTestId('calendar-button'); const clearButton = page.getByTestId('clear-button'); const dateInputs = container.querySelectorAll( '.react-daterange-picker__inputGroup', ) as unknown as [HTMLDivElement, HTMLDivElement]; const [dateFromInput, dateToInput] = dateInputs; const nativeFromInput = dateFromInput.querySelector('input[type="date"]'); const dayFromInput = dateFromInput.querySelector('input[name="day"]'); const monthFromInput = dateFromInput.querySelector('input[name="month"]'); const yearFromInput = dateFromInput.querySelector('input[name="year"]'); const nativeToInput = dateToInput.querySelector('input[type="date"]'); const dayToInput = dateToInput.querySelector('input[name="day"]'); const monthToInput = dateToInput.querySelector('input[name="month"]'); const yearToInput = dateToInput.querySelector('input[name="year"]'); expect(calendarButton).toHaveAttribute('aria-label', ariaLabelProps.calendarAriaLabel); expect(clearButton).toHaveAttribute('aria-label', ariaLabelProps.clearAriaLabel); expect(nativeFromInput).toHaveAttribute('aria-label', ariaLabelProps.nativeInputAriaLabel); expect(dayFromInput).toHaveAttribute('aria-label', ariaLabelProps.dayAriaLabel); expect(monthFromInput).toHaveAttribute('aria-label', ariaLabelProps.monthAriaLabel); expect(yearFromInput).toHaveAttribute('aria-label', ariaLabelProps.yearAriaLabel); expect(nativeToInput).toHaveAttribute('aria-label', ariaLabelProps.nativeInputAriaLabel); expect(dayToInput).toHaveAttribute('aria-label', ariaLabelProps.dayAriaLabel); expect(monthToInput).toHaveAttribute('aria-label', ariaLabelProps.monthAriaLabel); expect(yearToInput).toHaveAttribute('aria-label', ariaLabelProps.yearAriaLabel); }); it('passes placeholder props to DateInput components', async () => { const placeholderProps = { dayPlaceholder: 'dd', monthPlaceholder: 'mm', yearPlaceholder: 'yyyy', }; const { container } = await render(); const dateInputs = container.querySelectorAll( '.react-daterange-picker__inputGroup', ) as unknown as [HTMLDivElement, HTMLDivElement]; const [dateFromInput, dateToInput] = dateInputs; const dayFromInput = dateFromInput.querySelector('input[name="day"]'); const monthFromInput = dateFromInput.querySelector('input[name="month"]'); const yearFromInput = dateFromInput.querySelector('input[name="year"]'); const dayToInput = dateToInput.querySelector('input[name="day"]'); const monthToInput = dateToInput.querySelector('input[name="month"]'); const yearToInput = dateToInput.querySelector('input[name="year"]'); expect(dayFromInput).toHaveAttribute('placeholder', placeholderProps.dayPlaceholder); expect(monthFromInput).toHaveAttribute('placeholder', placeholderProps.monthPlaceholder); expect(yearFromInput).toHaveAttribute('placeholder', placeholderProps.yearPlaceholder); expect(dayToInput).toHaveAttribute('placeholder', placeholderProps.dayPlaceholder); expect(monthToInput).toHaveAttribute('placeholder', placeholderProps.monthPlaceholder); expect(yearToInput).toHaveAttribute('placeholder', placeholderProps.yearPlaceholder); }); describe('passes value to DateInput components', () => { it('passes single value to DateInput components', async () => { const value = new Date(2019, 0, 1); const { container } = await render(); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs[0]).toHaveValue('2019-01-01'); expect(nativeInputs[1]).toHaveValue(''); }); it('passes the first item of an array of values to DateInput components', async () => { const value1 = new Date(2019, 0, 1); const value2 = new Date(2019, 6, 1); const { container } = await render( , ); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs[0]).toHaveValue('2019-01-01'); expect(nativeInputs[1]).toHaveValue('2019-07-01'); }); }); it('applies className to its wrapper when given a string', async () => { const className = 'testClassName'; const { container } = await render(); const wrapper = container.firstElementChild; expect(wrapper).toHaveClass(className); }); it('applies "--open" className to its wrapper when given isOpen flag', async () => { const { container } = await render(); const wrapper = container.firstElementChild; expect(wrapper).toHaveClass('react-daterange-picker--open'); }); it('applies calendarClassName to the calendar when given a string', async () => { const calendarClassName = 'testClassName'; const { container } = await render( , ); const calendar = container.querySelector('.react-calendar'); expect(calendar).toHaveClass(calendarClassName); }); it('renders DateInput components', async () => { const { container } = await render(); const nativeInputs = container.querySelectorAll('input[type="date"]'); expect(nativeInputs.length).toBe(2); }); it('renders range divider with default divider', async () => { await render(); const rangeDivider = page.getByTestId('range-divider'); expect(rangeDivider).toBeInTheDocument(); expect(rangeDivider).toHaveTextContent('–'); }); it('renders range divider with custom divider', async () => { await render(); const rangeDivider = page.getByTestId('range-divider'); expect(rangeDivider).toBeInTheDocument(); expect(rangeDivider).toHaveTextContent('to'); }); describe('renders clear button properly', () => { it('renders clear button', async () => { await render(); const clearButton = page.getByTestId('clear-button'); expect(clearButton).toBeInTheDocument(); }); it('renders clear icon by default when clearIcon is not given', async () => { await render(); const clearButton = page.getByTestId('clear-button'); const clearIcon = clearButton.element().querySelector('svg'); expect(clearIcon).toBeInTheDocument(); }); it('renders clear icon when given clearIcon as a string', async () => { await render(); const clearButton = page.getByTestId('clear-button'); expect(clearButton).toHaveTextContent('❌'); }); it('renders clear icon when given clearIcon as a React element', async () => { function ClearIcon() { return <>❌; } await render(} />); const clearButton = page.getByTestId('clear-button'); expect(clearButton).toHaveTextContent('❌'); }); it('renders clear icon when given clearIcon as a function', async () => { function ClearIcon() { return <>❌; } await render(); const clearButton = page.getByTestId('clear-button'); expect(clearButton).toHaveTextContent('❌'); }); }); describe('renders calendar button properly', () => { it('renders calendar button', async () => { await render(); const calendarButton = page.getByTestId('calendar-button'); expect(calendarButton).toBeInTheDocument(); }); it('renders calendar icon by default when calendarIcon is not given', async () => { await render(); const calendarButton = page.getByTestId('calendar-button'); const calendarIcon = calendarButton.element().querySelector('svg'); expect(calendarIcon).toBeInTheDocument(); }); it('renders calendar icon when given calendarIcon as a string', async () => { await render(); const calendarButton = page.getByTestId('calendar-button'); expect(calendarButton).toHaveTextContent('📅'); }); it('renders calendar icon when given calendarIcon as a React element', async () => { function CalendarIcon() { return <>📅; } await render(} />); const calendarButton = page.getByTestId('calendar-button'); expect(calendarButton).toHaveTextContent('📅'); }); it('renders calendar icon when given calendarIcon as a function', async () => { function CalendarIcon() { return <>📅; } await render(); const calendarButton = page.getByTestId('calendar-button'); expect(calendarButton).toHaveTextContent('📅'); }); }); it('renders Calendar component when given isOpen flag', async () => { const { container } = await render(); const calendar = container.querySelector('.react-calendar'); expect(calendar).toBeInTheDocument(); }); it('does not render Calendar component when given disableCalendar & isOpen flags', async () => { const { container } = await render( , ); const calendar = container.querySelector('.react-calendar'); expect(calendar).not.toBeInTheDocument(); }); it('opens Calendar component when given isOpen flag by changing props', async () => { const { container, rerender } = await render(); const calendar = container.querySelector('.react-calendar'); expect(calendar).not.toBeInTheDocument(); await rerender(); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeInTheDocument(); }); it('opens Calendar component when clicking on a button', async () => { const { container } = await render(); const calendar = container.querySelector('.react-calendar'); expect(calendar).not.toBeInTheDocument(); const button = page.getByTestId('calendar-button'); await userEvent.click(button); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeInTheDocument(); }); function triggerFocusInEvent(locator: Locator) { const element = locator.element(); element.dispatchEvent( new FocusEvent('focusin', { bubbles: true, cancelable: false, composed: true }), ); } function triggerFocusEvent(locator: Locator) { triggerFocusInEvent(locator); const element = locator.element(); element.dispatchEvent( new FocusEvent('focus', { bubbles: false, cancelable: false, composed: true }), ); } describe('handles opening Calendar component when focusing on an input inside properly', () => { it('opens Calendar component when focusing on an input inside by default', async () => { const { container } = await render(); const calendar = container.querySelector('.react-calendar'); expect(calendar).not.toBeInTheDocument(); const input = page.getByRole('spinbutton', { name: 'day' }).first(); act(() => { triggerFocusEvent(input); }); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeInTheDocument(); }); it('opens Calendar component when focusing on an input inside given openCalendarOnFocus = true', async () => { const { container } = await render(); const calendar = container.querySelector('.react-calendar'); const input = page.getByRole('spinbutton', { name: 'day' }).first(); expect(calendar).not.toBeInTheDocument(); act(() => { triggerFocusEvent(input); }); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeInTheDocument(); }); it('does not open Calendar component when focusing on an input inside given openCalendarOnFocus = false', async () => { const { container } = await render( , ); const calendar = container.querySelector('.react-calendar'); const input = page.getByRole('spinbutton', { name: 'day' }).first(); expect(calendar).not.toBeInTheDocument(); act(() => { triggerFocusEvent(input); }); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeFalsy(); }); it('does not open Calendar when focusing on an input inside given shouldOpenCalendar function returning false', async () => { const shouldOpenCalendar = () => false; const { container } = await render( , ); const calendar = container.querySelector('.react-calendar'); const input = page.getByRole('spinbutton', { name: 'day' }).first(); expect(calendar).not.toBeInTheDocument(); triggerFocusEvent(input); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeFalsy(); }); it('does not open Calendar component when focusing on a select element', async () => { const { container } = await render( , ); const calendar = container.querySelector('.react-calendar'); const select = page.getByRole('combobox', { name: 'month' }).first(); expect(calendar).not.toBeInTheDocument(); triggerFocusEvent(select); const calendar2 = container.querySelector('.react-calendar'); expect(calendar2).toBeFalsy(); }); }); it('closes Calendar component when clicked outside', async () => { const { container } = await render(); await userEvent.click(document.body); await waitForElementToBeRemovedOrHidden(() => container.querySelector('.react-daterange-picker__calendar'), ); }); it('closes Calendar component when focused outside', async () => { const { container } = await render(); triggerFocusInEvent(page.elementLocator(document.body)); await waitForElementToBeRemovedOrHidden(() => container.querySelector('.react-daterange-picker__calendar'), ); }); function triggerTouchStart(element: HTMLElement) { element.dispatchEvent(new TouchEvent('touchstart', { bubbles: true, cancelable: true })); } it('closes Calendar component when tapped outside', async () => { const { container } = await render(); triggerTouchStart(document.body); await waitForElementToBeRemovedOrHidden(() => container.querySelector('.react-daterange-picker__calendar'), ); }); function triggerFocusOutEvent(locator: Locator) { const element = locator.element(); element.dispatchEvent( new FocusEvent('focusout', { bubbles: true, cancelable: false, composed: true }), ); } function triggerBlurEvent(locator: Locator) { triggerFocusOutEvent(locator); const element = locator.element(); element.dispatchEvent( new FocusEvent('blur', { bubbles: false, cancelable: false, composed: true }), ); } it('does not close Calendar component when focused inside', async () => { const { container } = await render(); const monthInput = page.getByRole('spinbutton', { name: 'month' }).first(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); triggerBlurEvent(monthInput); triggerFocusEvent(dayInput); const calendar = container.querySelector('.react-calendar'); expect(calendar).toBeInTheDocument(); }); it('closes Calendar when changing value by default', async () => { const { container } = await render(); const [firstTile, secondTile] = container.querySelectorAll( '.react-calendar__tile', ) as unknown as [HTMLButtonElement, HTMLButtonElement]; await act(async () => { await userEvent.click(firstTile); }); await act(async () => { await userEvent.click(secondTile); }); await waitForElementToBeRemovedOrHidden(() => container.querySelector('.react-daterange-picker__calendar'), ); }); it('closes Calendar when changing value with prop closeCalendar = true', async () => { const { container } = await render(); const [firstTile, secondTile] = container.querySelectorAll( '.react-calendar__tile', ) as unknown as [HTMLButtonElement, HTMLButtonElement]; await act(async () => { await userEvent.click(firstTile); }); await act(async () => { await userEvent.click(secondTile); }); await waitForElementToBeRemovedOrHidden(() => container.querySelector('.react-daterange-picker__calendar'), ); }); it('does not close Calendar when changing value with prop closeCalendar = false', async () => { const { container } = await render( , ); const [firstTile, secondTile] = container.querySelectorAll( '.react-calendar__tile', ) as unknown as [HTMLButtonElement, HTMLButtonElement]; await act(async () => { await userEvent.click(firstTile); }); await act(async () => { await userEvent.click(secondTile); }); const calendar = container.querySelector('.react-calendar'); expect(calendar).toBeInTheDocument(); }); it('does not close Calendar when changing value with shouldCloseCalendar function returning false', async () => { const shouldCloseCalendar = () => false; const { container } = await render( , ); const firstTile = container.querySelector('.react-calendar__tile') as HTMLButtonElement; await act(async () => { await userEvent.click(firstTile); }); const calendar = container.querySelector('.react-calendar'); expect(calendar).toBeInTheDocument(); }); it('does not close Calendar when changing value using inputs', async () => { const { container } = await render(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); await act(async () => { await userEvent.fill(dayInput, '1'); }); const calendar = container.querySelector('.react-calendar'); expect(calendar).toBeInTheDocument(); }); it('calls onChange callback when changing value', async () => { const value = new Date(2023, 0, 31); const onChange = vi.fn(); await render(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); await act(async () => { await userEvent.fill(dayInput, '1'); }); expect(onChange).toHaveBeenCalledWith([new Date(2023, 0, 1), null]); }); it('calls onInvalidChange callback when changing value to an invalid one', async () => { const value = new Date(2023, 0, 31); const onInvalidChange = vi.fn(); await render( , ); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); await act(async () => { await userEvent.fill(dayInput, '32'); }); expect(onInvalidChange).toHaveBeenCalled(); }); it('clears the value when clicking on a button', async () => { const onChange = vi.fn(); const { container } = await render(); const calendar = container.querySelector('.react-calendar'); const button = page.getByTestId('clear-button'); expect(calendar).not.toBeInTheDocument(); await userEvent.click(button); expect(onChange).toHaveBeenCalledWith(null); }); describe('onChangeFrom', () => { it('calls onChange properly given no initial value', async () => { const onChange = vi.fn(); await render( , ); const nextValueFrom = new Date(2018, 1, 15); const monthInput = page.getByRole('spinbutton', { name: 'month' }).first(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); const yearInput = page.getByRole('spinbutton', { name: 'year' }).first(); await act(async () => { await userEvent.fill(monthInput, '2'); await userEvent.fill(dayInput, '15'); await userEvent.fill(yearInput, '2018'); }); await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith([nextValueFrom, null])); }); it('calls onChange properly given single initial value', async () => { const onChange = vi.fn(); const value = new Date(2018, 0, 1); await render(); const nextValueFrom = new Date(2018, 1, 15); const monthInput = page.getByRole('spinbutton', { name: 'month' }).first(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); const yearInput = page.getByRole('spinbutton', { name: 'year' }).first(); await act(async () => { await userEvent.fill(monthInput, '2'); await userEvent.fill(dayInput, '15'); await userEvent.fill(yearInput, '2018'); }); expect(onChange).toHaveBeenCalled(); expect(onChange).toHaveBeenCalledWith([nextValueFrom, null]); }); it('calls onChange properly given initial value as an array', async () => { const onChange = vi.fn(); const valueFrom = new Date(2018, 0, 1); const valueTo = new Date(2018, 6, 1); const value = [valueFrom, valueTo] as [Date, Date]; await render(); const nextValueFrom = new Date(2018, 1, 15); const monthInput = page.getByRole('spinbutton', { name: 'month' }).first(); const dayInput = page.getByRole('spinbutton', { name: 'day' }).first(); const yearInput = page.getByRole('spinbutton', { name: 'year' }).first(); await act(async () => { await userEvent.fill(monthInput, '2'); await userEvent.fill(dayInput, '15'); await userEvent.fill(yearInput, '2018'); }); expect(onChange).toHaveBeenCalled(); expect(onChange).toHaveBeenCalledWith([nextValueFrom, valueTo]); }); }); describe('onChangeTo', () => { it('calls onChange properly given no initial value', async () => { const onChange = vi.fn(); await render( , ); const nextValueTo = new Date(2018, 1, 15); nextValueTo.setDate(nextValueTo.getDate() + 1); nextValueTo.setTime(nextValueTo.getTime() - 1); const monthInput = page.getByRole('spinbutton', { name: 'month' }).nth(1); const dayInput = page.getByRole('spinbutton', { name: 'day' }).nth(1); const yearInput = page.getByRole('spinbutton', { name: 'year' }).nth(1); await act(async () => { await userEvent.fill(dayInput, '15'); await userEvent.fill(monthInput, '2'); await userEvent.fill(yearInput, '2018'); }); await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith([null, nextValueTo])); }); it('calls onChange properly given single initial value', async () => { const onChange = vi.fn(); const value = new Date(2018, 0, 1); await render( , ); const nextValueTo = new Date(2018, 1, 15); nextValueTo.setDate(nextValueTo.getDate() + 1); nextValueTo.setTime(nextValueTo.getTime() - 1); const monthInput = page.getByRole('spinbutton', { name: 'month' }).nth(1); const dayInput = page.getByRole('spinbutton', { name: 'day' }).nth(1); const yearInput = page.getByRole('spinbutton', { name: 'year' }).nth(1); await act(async () => { await userEvent.fill(dayInput, '15'); await userEvent.fill(monthInput, '2'); await userEvent.fill(yearInput, '2018'); }); await vi.waitFor(() => expect(onChange).toHaveBeenCalledWith([value, nextValueTo])); }); it('calls onChange properly given initial value as an array', async () => { const onChange = vi.fn(); const valueFrom = new Date(2018, 0, 1); const valueTo = new Date(2018, 6, 1); const value = [valueFrom, valueTo] as [Date, Date]; await render(); const nextValueTo = new Date(2018, 1, 15); nextValueTo.setDate(nextValueTo.getDate() + 1); nextValueTo.setTime(nextValueTo.getTime() - 1); const monthInput = page.getByRole('spinbutton', { name: 'month' }).nth(1); const dayInput = page.getByRole('spinbutton', { name: 'day' }).nth(1); const yearInput = page.getByRole('spinbutton', { name: 'year' }).nth(1); await act(async () => { await userEvent.fill(dayInput, '15'); await userEvent.fill(monthInput, '2'); await userEvent.fill(yearInput, '2018'); }); expect(onChange).toHaveBeenCalled(); expect(onChange).toHaveBeenCalledWith([valueFrom, nextValueTo]); }); }); it('calls onClick callback when clicked a page (sample of mouse events family)', async () => { const onClick = vi.fn(); const { container } = await render(); const wrapper = container.firstElementChild as HTMLDivElement; await userEvent.click(wrapper); expect(onClick).toHaveBeenCalled(); }); it('calls onTouchStart callback when touched a page (sample of touch events family)', async () => { const onTouchStart = vi.fn(); const { container } = await render( , ); const wrapper = container.firstElementChild as HTMLDivElement; triggerTouchStart(wrapper); expect(onTouchStart).toHaveBeenCalled(); }); }); ================================================ FILE: packages/react-daterange-picker/src/DateRangePicker.tsx ================================================ 'use client'; import { createElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import clsx from 'clsx'; import makeEventProps from 'make-event-props'; import Calendar from 'react-calendar'; import DateInput from 'react-date-picker/dist/DateInput'; import Fit from 'react-fit'; import type { ClassName, CloseReason, Detail, LooseValue, OpenReason, Value, } from './shared/types.js'; const baseClassName = 'react-daterange-picker'; const outsideActionEvents = ['mousedown', 'focusin', 'touchstart'] as const; const iconProps = { xmlns: 'http://www.w3.org/2000/svg', width: 19, height: 19, viewBox: '0 0 19 19', stroke: 'black', strokeWidth: 2, }; const CalendarIcon = ( ); const ClearIcon = ( ); type ReactNodeLike = React.ReactNode | string | number | boolean | null | undefined; type Icon = ReactNodeLike | ReactNodeLike[]; type IconOrRenderFunction = Icon | React.ComponentType | React.ReactElement; type CalendarProps = Omit< React.ComponentPropsWithoutRef, 'onChange' | 'selectRange' | 'value' >; type EventProps = ReturnType; export type DateRangePickerProps = { /** * Automatically focuses the input on mount. * * @example true */ autoFocus?: boolean; /** * `aria-label` for the calendar button. * * @example 'Toggle calendar' */ calendarAriaLabel?: string; /** * Content of the calendar button. Setting the value explicitly to `null` will hide the icon. * * @example 'Calendar' * @example * @example CalendarIcon */ calendarIcon?: IconOrRenderFunction | null; /** * Props to pass to React-Calendar component. */ calendarProps?: CalendarProps; /** * Class name(s) that will be added along with `"react-daterange-picker"` to the main React-DateRange-Picker `
` element. * * @example 'class1 class2' * @example ['class1', 'class2 class3'] */ className?: ClassName; /** * `aria-label` for the clear button. * * @example 'Clear value' */ clearAriaLabel?: string; /** * Content of the clear button. Setting the value explicitly to `null` will hide the icon. * * @example 'Clear' * @example * @example ClearIcon */ clearIcon?: IconOrRenderFunction | null; /** * Whether to close the calendar on value selection. * * **Note**: It's recommended to use `shouldCloseCalendar` function instead. * * @default true * @example false */ closeCalendar?: boolean; /** * `data-testid` attribute for the main React-DateRange-Picker `
` element. * * @example 'daterange-picker' */ 'data-testid'?: string; /** * `aria-label` for the day input. * * @example 'Day' */ dayAriaLabel?: string; /** * `placeholder` for the day input. * * @default '--' * @example 'dd' */ dayPlaceholder?: string; /** * When set to `true`, will remove the calendar and the button toggling its visibility. * * @default false * @example true */ disableCalendar?: boolean; /** * Whether the date range picker should be disabled. * * @default false * @example true */ disabled?: boolean; /** * Input format based on [Unicode Technical Standard #35](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table). Supported values are: `y`, `M`, `MM`, `MMM`, `MMMM`, `d`, `dd`. * * **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. * * @example 'y-MM-dd' */ format?: string; /** * `id` attribute for the main React-DateRange-Picker `
` element. * * @example 'daterange-picker' */ id?: string; /** * Whether the calendar should be opened. * * @default false * @example true */ isOpen?: boolean; /** * Locale that should be used by the date range picker and the calendar. Can be any [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag). * * **Note**: When using SSR, setting this prop may help resolving hydration errors caused by locale mismatch between server and client. * * @example 'hu-HU' */ locale?: string; /** * Maximum date that the user can select. Periods partially overlapped by maxDate will also be selectable, although React-DateRange-Picker will ensure that no later date is selected. * * @example new Date() */ maxDate?: Date; /** * The most detailed calendar view that the user shall see. View defined here also becomes the one on which clicking an item in the calendar will select a date and pass it to onChange. Can be `"month"`, `"year"`, `"decade"` or * * @default 'month' * @example 'year' */ maxDetail?: Detail; /** * Minimum date that the user can select. Periods partially overlapped by minDate will also be selectable, although React-DateRange-Picker will ensure that no earlier date is selected. * * @example new Date() */ minDate?: Date; /** * `aria-label` for the month input. * * @example 'Month' */ monthAriaLabel?: string; /** * `placeholder` for the month input. * * @default '--' * @example 'mm' */ monthPlaceholder?: string; /** * Input name. * * @default 'daterange' */ name?: string; /** * `aria-label` for the native date input. * * @example 'Date' */ nativeInputAriaLabel?: string; /** * Function called when the calendar closes. * * @example () => alert('Calendar closed') */ onCalendarClose?: () => void; /** * Function called when the calendar opens. * * @example () => alert('Calendar opened') */ onCalendarOpen?: () => void; /** * Function called when the user picks a valid date. If any of the fields were excluded using custom `format`, `new Date(y, 0, 1, 0, 0, 0)`, where `y` is the current year, is going to serve as a "base". * * @example (value) => alert('New date is: ', value) */ onChange?: (value: Value) => void; /** * Function called when the user focuses an input. * * @example (event) => alert('Focused input: ', event.target.name) */ onFocus?: (event: React.FocusEvent) => void; /** * Function called when the user picks an invalid date. * * @example () => alert('Invalid date') */ onInvalidChange?: () => void; /** * Whether to open the calendar on input focus. **Note**: It's recommended to use `shouldOpenCalendar` function instead. * * @default true * @example false */ openCalendarOnFocus?: boolean; /** * Element to render the calendar in using portal. * * @example document.getElementById('my-div') */ portalContainer?: HTMLElement | null; /** * Divider between date inputs. * * @default '–' * @example ' to ' */ rangeDivider?: React.ReactNode; /** * Whether date input should be required. * * @default false * @example true */ required?: boolean; /** * Function called before the calendar closes. `reason` can be `"buttonClick"`, `"escape"`, `"outsideAction"`, or `"select"`. If it returns `false`, the calendar will not close. * * @example ({ reason }) => reason !== 'outsideAction' */ shouldCloseCalendar?: (props: { reason: CloseReason }) => boolean; /** * Function called before the calendar opens. `reason` can be `"buttonClick"` or `"focus"`. If it returns `false`, the calendar will not open. * * @example ({ reason }) => reason !== 'focus' */ shouldOpenCalendar?: (props: { reason: OpenReason }) => boolean; /** * Whether leading zeros should be rendered in date inputs. * * @default false * @example true */ showLeadingZeros?: boolean; /** * Input value. * * @example new Date(2017, 0, 1) * @example [new Date(2017, 0, 1), new Date(2017, 7, 1)] * @example ['2017-01-01', '2017-08-01'] */ value?: LooseValue; /** * `aria-label` for the year input. * * @example 'Year' */ yearAriaLabel?: string; /** * `placeholder` for the year input. * * @default '----' * @example 'yyyy' */ yearPlaceholder?: string; } & Omit; export default function DateRangePicker(props: DateRangePickerProps): React.ReactElement { const { autoFocus, calendarAriaLabel, calendarIcon = CalendarIcon, className, clearAriaLabel, clearIcon = ClearIcon, closeCalendar: shouldCloseCalendarOnSelect = true, 'data-testid': dataTestid, dayAriaLabel, dayPlaceholder, disableCalendar, disabled, format, id, isOpen: isOpenProps = null, locale, maxDate, maxDetail = 'month', minDate, monthAriaLabel, monthPlaceholder, name = 'daterange', nativeInputAriaLabel, onCalendarClose, onCalendarOpen, onChange: onChangeProps, onFocus: onFocusProps, onInvalidChange, openCalendarOnFocus = true, rangeDivider = '–', required, shouldCloseCalendar, shouldOpenCalendar, showLeadingZeros, value, yearAriaLabel, yearPlaceholder, ...otherProps } = props; const [isOpen, setIsOpen] = useState(isOpenProps); const wrapper = useRef(null); const calendarWrapper = useRef(null); useEffect(() => { setIsOpen(isOpenProps); }, [isOpenProps]); function openCalendar({ reason }: { reason: OpenReason }) { if (shouldOpenCalendar) { if (!shouldOpenCalendar({ reason })) { return; } } setIsOpen(true); if (onCalendarOpen) { onCalendarOpen(); } } const closeCalendar = useCallback( ({ reason }: { reason: CloseReason }) => { if (shouldCloseCalendar) { if (!shouldCloseCalendar({ reason })) { return; } } setIsOpen(false); if (onCalendarClose) { onCalendarClose(); } }, [onCalendarClose, shouldCloseCalendar], ); function toggleCalendar() { if (isOpen) { closeCalendar({ reason: 'buttonClick' }); } else { openCalendar({ reason: 'buttonClick' }); } } function onChange(value: Value, shouldCloseCalendar: boolean = shouldCloseCalendarOnSelect) { if (shouldCloseCalendar) { closeCalendar({ reason: 'select' }); } if (onChangeProps) { onChangeProps(value); } } function onChangeFrom(nextValue: Value, closeCalendar: boolean) { const [nextValueFrom] = Array.isArray(nextValue) ? nextValue : [nextValue]; const [, valueTo] = Array.isArray(value) ? value : [value]; const valueToDate = valueTo ? new Date(valueTo) : null; onChange([nextValueFrom, valueToDate], closeCalendar); } function onChangeTo(nextValue: Value, closeCalendar: boolean) { const [, nextValueTo] = Array.isArray(nextValue) ? nextValue : [null, nextValue]; const [valueFrom] = Array.isArray(value) ? value : [value]; const valueFromDate = valueFrom ? new Date(valueFrom) : null; onChange([valueFromDate, nextValueTo], closeCalendar); } function onFocus(event: React.FocusEvent) { if (onFocusProps) { onFocusProps(event); } if ( // Internet Explorer still fires onFocus on disabled elements disabled || isOpen || !openCalendarOnFocus || event.target.dataset.select === 'true' ) { return; } openCalendar({ reason: 'focus' }); } const onKeyDown = useCallback( (event: KeyboardEvent) => { if (event.key === 'Escape') { closeCalendar({ reason: 'escape' }); } }, [closeCalendar], ); function clear() { onChange(null); } function stopPropagation(event: React.FocusEvent) { event.stopPropagation(); } const onOutsideAction = useCallback( (event: Event) => { const { current: wrapperEl } = wrapper; const { current: calendarWrapperEl } = calendarWrapper; // Try event.composedPath first to handle clicks inside a Shadow DOM. const target = ( 'composedPath' in event ? event.composedPath()[0] : (event as Event).target ) as HTMLElement; if ( target && wrapperEl && !wrapperEl.contains(target) && !calendarWrapperEl?.contains(target) ) { closeCalendar({ reason: 'outsideAction' }); } }, [closeCalendar], ); const handleOutsideActionListeners = useCallback( (shouldListen = isOpen) => { for (const event of outsideActionEvents) { if (shouldListen) { document.addEventListener(event, onOutsideAction); } else { document.removeEventListener(event, onOutsideAction); } } if (shouldListen) { document.addEventListener('keydown', onKeyDown); } else { document.removeEventListener('keydown', onKeyDown); } }, [isOpen, onOutsideAction, onKeyDown], ); // biome-ignore lint/correctness/useExhaustiveDependencies: useEffect intentionally triggered on isOpen change useEffect(() => { handleOutsideActionListeners(); return () => { handleOutsideActionListeners(false); }; }, [handleOutsideActionListeners, isOpen]); function renderInputs() { const [valueFrom, valueTo] = Array.isArray(value) ? value : [value]; const ariaLabelProps = { dayAriaLabel, monthAriaLabel, nativeInputAriaLabel, yearAriaLabel, }; const placeholderProps = { dayPlaceholder, monthPlaceholder, yearPlaceholder, }; const commonProps = { ...ariaLabelProps, ...placeholderProps, className: `${baseClassName}__inputGroup`, disabled, format, isCalendarOpen: isOpen, locale, maxDate, maxDetail, minDate, onInvalidChange, required, showLeadingZeros, }; return (
{rangeDivider} {clearIcon !== null && ( )} {calendarIcon !== null && !disableCalendar && ( )}
); } function renderCalendar() { if (isOpen === null || disableCalendar) { return null; } const { calendarProps, portalContainer, value } = props; const className = `${baseClassName}__calendar`; const classNames = clsx(className, `${className}--${isOpen ? 'open' : 'closed'}`); const calendar = ( onChange(value)} selectRange value={value} {...calendarProps} /> ); return portalContainer ? ( createPortal(
{calendar}
, portalContainer, ) ) : (
{ if (ref && !isOpen) { ref.removeAttribute('style'); } }} className={classNames} > {calendar}
); } const eventProps = useMemo( () => makeEventProps(otherProps), // biome-ignore lint/correctness/useExhaustiveDependencies: FIXME [otherProps], ); return ( // biome-ignore lint/a11y/noStaticElementInteractions: False positive caused by non interactive wrapper listening for bubbling events
{renderInputs()} {renderCalendar()}
); } ================================================ FILE: packages/react-daterange-picker/src/index.ts ================================================ import DateRangePicker from './DateRangePicker.js'; export type { DateRangePickerProps } from './DateRangePicker.js'; export { DateRangePicker }; export default DateRangePicker; ================================================ FILE: packages/react-daterange-picker/src/shared/types.ts ================================================ export type Range = [T, T]; export type ClassName = string | null | undefined | (string | null | undefined)[]; export type CloseReason = 'buttonClick' | 'escape' | 'outsideAction' | 'select'; export type Detail = 'century' | 'decade' | 'year' | 'month'; type LooseValuePiece = string | Date | null; export type LooseValue = LooseValuePiece | Range; export type OpenReason = 'buttonClick' | 'focus'; export type RangeType = 'century' | 'decade' | 'year' | 'month' | 'day'; type ValuePiece = Date | null; export type Value = ValuePiece | Range; ================================================ FILE: packages/react-daterange-picker/tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "noEmit": false, "outDir": "dist", "rootDir": "src" }, "include": ["src"], "exclude": ["src/**/*.spec.ts", "src/**/*.spec.tsx"] } ================================================ FILE: packages/react-daterange-picker/tsconfig.json ================================================ { "compilerOptions": { "declaration": true, "esModuleInterop": true, "isolatedDeclarations": true, "isolatedModules": true, "jsx": "react-jsx", "module": "nodenext", "moduleDetection": "force", "noEmit": true, "noUncheckedIndexedAccess": true, "outDir": "dist", "skipLibCheck": true, "target": "es2018", "verbatimModuleSyntax": true }, "exclude": ["dist"] } ================================================ FILE: packages/react-daterange-picker/vitest.config.ts ================================================ import { playwright } from '@vitest/browser-playwright'; import { defineConfig } from 'vitest/config'; import type { ViteUserConfig } from 'vitest/config'; const config: ViteUserConfig = defineConfig({ test: { browser: { enabled: true, headless: true, instances: [{ browser: 'chromium' }], provider: playwright(), }, watch: false, }, }); export default config; ================================================ FILE: sample/.gitignore ================================================ dist node_modules ================================================ FILE: sample/Sample.css ================================================ html, body { height: 100%; } body { margin: 0; font-family: 'Segoe UI', Tahoma, sans-serif; } .Sample input, .Sample button { font: inherit; } .Sample header { background-color: #323639; box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); padding: 20px; color: white; } .Sample header h1 { font-size: inherit; margin: 0; } .Sample__container { display: flex; flex-direction: row; flex-wrap: wrap; align-items: flex-start; margin: 10px 0; padding: 10px; } .Sample__container > * > * { margin: 10px; } .Sample__container__content { display: flex; max-width: 100%; flex-basis: 420px; flex-direction: column; flex-grow: 100; align-items: stretch; } ================================================ FILE: sample/Sample.tsx ================================================ import { useState } from 'react'; import DateRangePicker from '@wojtekmaj/react-daterange-picker'; import './Sample.css'; type ValuePiece = Date | null; type Value = ValuePiece | [ValuePiece, ValuePiece]; const now = new Date(); const yesterdayBegin = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1); const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999); export default function Sample() { const [value, onChange] = useState([yesterdayBegin, todayEnd]); return (

react-daterange-picker sample page

); } ================================================ FILE: sample/index.html ================================================ react-daterange-picker sample page
================================================ FILE: sample/index.tsx ================================================ import { createRoot } from 'react-dom/client'; import Sample from './Sample.js'; const root = document.getElementById('root'); if (!root) { throw new Error('Could not find root element'); } createRoot(root).render(); ================================================ FILE: sample/package.json ================================================ { "name": "react-daterange-picker-sample-page", "version": "3.0.0", "description": "A sample page for React-DateRange-Picker.", "private": true, "type": "module", "scripts": { "build": "vite build", "dev": "vite", "preview": "vite preview" }, "author": { "name": "Wojciech Maj", "email": "kontakt@wojtekmaj.pl" }, "license": "MIT", "dependencies": { "@wojtekmaj/react-daterange-picker": "latest", "react": "^19.2.0", "react-dom": "^19.2.0" }, "devDependencies": { "@vitejs/plugin-react": "^6.0.1", "typescript": "^6.0.2", "vite": "^8.0.5" }, "packageManager": "yarn@4.10.3" } ================================================ FILE: sample/tsconfig.json ================================================ { "compilerOptions": { "isolatedModules": true, "jsx": "react-jsx", "module": "preserve", "moduleDetection": "force", "noEmit": true, "noUncheckedIndexedAccess": true, "skipLibCheck": true, "target": "esnext", "verbatimModuleSyntax": true } } ================================================ FILE: sample/vite.config.ts ================================================ import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ base: './', plugins: [react()], }); ================================================ FILE: test/.gitignore ================================================ dist node_modules ================================================ FILE: test/LocaleOptions.tsx ================================================ import { useId, useRef } from 'react'; type LocaleOptionsProps = { locale: string | undefined; setLocale: (locale: string | undefined) => void; }; export default function LocaleOptions({ locale, setLocale }: LocaleOptionsProps) { const localeDefaultId = useId(); const localeEnUSId = useId(); const localeFrFRId = useId(); const localeArEGId = useId(); const customLocaleId = useId(); const customLocale = useRef(null); function onChange(event: React.ChangeEvent) { const { value: nextLocale } = event.target; if (nextLocale === 'undefined') { setLocale(undefined); } else { setLocale(nextLocale); } } function onCustomChange(event: React.FormEvent) { event.preventDefault(); const input = customLocale.current; const { value: nextLocale } = input as HTMLInputElement; setLocale(nextLocale); } function resetLocale() { setLocale(undefined); } return (
Locale
   
); } ================================================ FILE: test/MaxDetailOptions.tsx ================================================ import type { Detail } from './shared/types.js'; const allViews = ['century', 'decade', 'year', 'month'] as const; function upperCaseFirstLetter(str: string) { return str.slice(0, 1).toUpperCase() + str.slice(1); } type MaxDetailOptionsProps = { maxDetail: Detail; minDetail: Detail; setMaxDetail: (maxDetail: Detail) => void; }; export default function MaxDetailOptions({ maxDetail, minDetail, setMaxDetail, }: MaxDetailOptionsProps) { function onChange(event: React.ChangeEvent) { const { value } = event.target; setMaxDetail(value as Detail); } const minDetailIndex = allViews.indexOf(minDetail); return (
Maximum detail {allViews.map((view, index) => (
index} id={`max-${view}`} name="maxDetail" onChange={onChange} type="radio" value={view} />
))}
); } ================================================ FILE: test/MinDetailOptions.tsx ================================================ import type { Detail } from './shared/types.js'; const allViews = ['century', 'decade', 'year', 'month'] as const; function upperCaseFirstLetter(str: string) { return str.slice(0, 1).toUpperCase() + str.slice(1); } type MinDetailOptionsProps = { maxDetail: Detail; minDetail: Detail; setMinDetail: (maxDetail: Detail) => void; }; export default function MinDetailOptions({ maxDetail, minDetail, setMinDetail, }: MinDetailOptionsProps) { function onChange(event: React.ChangeEvent) { const { value } = event.target; setMinDetail(value as Detail); } const maxDetailIndex = allViews.indexOf(maxDetail); return (
Minimum detail {allViews.map((view, index) => (
))}
); } ================================================ FILE: test/Test.css ================================================ body { margin: 0; font-family: 'Segoe UI', Tahoma, sans-serif; } .Test header { background-color: #323639; box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); padding: 20px; color: white; } .Test header h1 { font-size: inherit; margin: 0; } .Test__container { display: flex; flex-direction: row; flex-wrap: wrap; align-items: flex-start; margin: 10px 0; padding: 10px; } .Test__container > * > * { margin: 10px; } .Test__container__options { display: flex; flex-basis: 400px; flex-grow: 1; flex-wrap: wrap; margin: 0; } .Test__container__options input, .Test__container__options button { font: inherit; } .Test__container__options fieldset { border: 1px solid black; flex-grow: 1; position: relative; top: -10px; } .Test__container__options fieldset legend { font-weight: 600; } .Test__container__options fieldset legend + * { margin-top: 0 !important; } .Test__container__options fieldset label { font-weight: 600; display: block; } .Test__container__options fieldset label:not(:first-of-type) { margin-top: 1em; } .Test__container__options fieldset input[type='checkbox'] + label, .Test__container__options fieldset input[type='radio'] + label { font-weight: normal; display: inline-block; margin: 0; } .Test__container__options fieldset form:not(:first-child), .Test__container__options fieldset div:not(:first-child) { margin-top: 1em; } .Test__container__options fieldset form:not(:last-child), .Test__container__options fieldset div:not(:last-child) { margin-bottom: 1em; } .Test__container__content { display: flex; max-width: 100%; flex-basis: 420px; flex-direction: column; flex-grow: 100; align-items: stretch; } ================================================ FILE: test/Test.tsx ================================================ import { useRef, useState } from 'react'; import DateRangePicker from '@wojtekmaj/react-daterange-picker'; import '@wojtekmaj/react-daterange-picker/dist/DateRangePicker.css'; import 'react-calendar/dist/Calendar.css'; import ValidityOptions from './ValidityOptions.js'; import MaxDetailOptions from './MaxDetailOptions.js'; import MinDetailOptions from './MinDetailOptions.js'; import LocaleOptions from './LocaleOptions.js'; import ValueOptions from './ValueOptions.js'; import ViewOptions from './ViewOptions.js'; import './Test.css'; import type { Detail, LooseValue } from './shared/types.js'; const now = new Date(); const ariaLabelProps = { calendarAriaLabel: 'Toggle calendar', clearAriaLabel: 'Clear value', dayAriaLabel: 'Day', monthAriaLabel: 'Month', nativeInputAriaLabel: 'Date', yearAriaLabel: 'Year', }; const placeholderProps = { dayPlaceholder: 'dd', monthPlaceholder: 'mm', yearPlaceholder: 'yyyy', }; const nineteenNinetyFive = new Date(1995, now.getUTCMonth() + 1, 15, 12); const fifteenthOfNextMonth = new Date(now.getUTCFullYear(), now.getUTCMonth() + 1, 15, 12); export default function Test() { const portalContainer = useRef(null); const [disabled, setDisabled] = useState(false); const [locale, setLocale] = useState(); const [maxDate, setMaxDate] = useState(fifteenthOfNextMonth); const [maxDetail, setMaxDetail] = useState('month'); const [minDate, setMinDate] = useState(nineteenNinetyFive); const [minDetail, setMinDetail] = useState('century'); const [renderInPortal, setRenderInPortal] = useState(false); const [required, setRequired] = useState(true); const [showLeadingZeros, setShowLeadingZeros] = useState(true); const [showNeighboringMonth, setShowNeighboringMonth] = useState(false); const [showWeekNumbers, setShowWeekNumbers] = useState(false); const [value, setValue] = useState(now); return (

react-daterange-picker test page

{ event.preventDefault(); console.warn('Calendar triggered submitting the form.'); console.log(event); }} > console.log('Calendar closed')} onCalendarOpen={() => console.log('Calendar opened')} onChange={setValue} portalContainer={renderInPortal ? portalContainer.current : undefined} required={required} showLeadingZeros={showLeadingZeros} value={value} />


); } ================================================ FILE: test/ValidityOptions.tsx ================================================ import { useId } from 'react'; import { getISOLocalDate } from '@wojtekmaj/date-utils'; type ValidityOptionsProps = { maxDate?: Date; minDate?: Date; required?: boolean; setMaxDate: (maxDate: Date | undefined) => void; setMinDate: (minDate: Date | undefined) => void; setRequired: (required: boolean) => void; }; export default function ValidityOptions({ maxDate, minDate, required, setMaxDate, setMinDate, setRequired, }: ValidityOptionsProps) { const minDateId = useId(); const maxDateId = useId(); const requiredId = useId(); function onMinChange(event: React.ChangeEvent) { const { value } = event.target; setMinDate(value ? new Date(value) : undefined); } function onMaxChange(event: React.ChangeEvent) { const { value } = event.target; setMaxDate(value ? new Date(value) : undefined); } return (
Minimum and maximum date
 
 
setRequired(event.target.checked)} type="checkbox" />
); } ================================================ FILE: test/ValueOptions.tsx ================================================ import { useId } from 'react'; import { getDayStart, getDayEnd, getISOLocalDate } from '@wojtekmaj/date-utils'; import type { LooseValue } from './shared/types.js'; type ValueOptionsProps = { setValue: (value: LooseValue) => void; value?: LooseValue; }; export default function ValueOptions({ setValue, value }: ValueOptionsProps) { const startDateId = useId(); const endDateId = useId(); const [startDate, endDate] = Array.isArray(value) ? value : [value, null]; function setStartValue(nextStartDate: string | Date | null) { if (!nextStartDate) { setValue(endDate); return; } if (Array.isArray(value)) { setValue([nextStartDate, endDate]); } else { setValue(nextStartDate); } } function setEndValue(nextEndDate: string | Date | null) { if (!nextEndDate) { setValue(startDate || null); return; } setValue([startDate || null, nextEndDate]); } function onStartChange(event: React.ChangeEvent) { const { value: nextValue } = event.target; setStartValue(nextValue ? getDayStart(new Date(nextValue)) : null); } function onEndChange(event: React.ChangeEvent) { const { value: nextValue } = event.target; setEndValue(nextValue ? getDayEnd(new Date(nextValue)) : null); } return (
Value options
 
 
); } ================================================ FILE: test/ViewOptions.tsx ================================================ import { useId } from 'react'; type ViewOptionsProps = { disabled: boolean; renderInPortal: boolean; setDisabled: (disabled: boolean) => void; setRenderInPortal: (renderInPortal: boolean) => void; setShowLeadingZeros: (showLeadingZeros: boolean) => void; setShowNeighboringMonth: (showNeighboringMonth: boolean) => void; setShowWeekNumbers: (showWeekNumbers: boolean) => void; showLeadingZeros: boolean; showNeighboringMonth: boolean; showWeekNumbers: boolean; }; export default function ViewOptions({ disabled, renderInPortal, setDisabled, setRenderInPortal, setShowLeadingZeros, setShowNeighboringMonth, setShowWeekNumbers, showLeadingZeros, showNeighboringMonth, showWeekNumbers, }: ViewOptionsProps) { const disabledId = useId(); const showLeadingZerosId = useId(); const showWeekNumbersId = useId(); const showNeighboringMonthId = useId(); const renderInPortalId = useId(); function onDisabledChange(event: React.ChangeEvent) { const { checked } = event.target; setDisabled(checked); } function onShowLeadingZerosChange(event: React.ChangeEvent) { const { checked } = event.target; setShowLeadingZeros(checked); } function onShowWeekNumbersChange(event: React.ChangeEvent) { const { checked } = event.target; setShowWeekNumbers(checked); } function onShowNeighboringMonthChange(event: React.ChangeEvent) { const { checked } = event.target; setShowNeighboringMonth(checked); } function onRenderInPortalChange(event: React.ChangeEvent) { const { checked } = event.target; setRenderInPortal(checked); } return (
View options
); } ================================================ FILE: test/global.d.ts ================================================ declare module '*.css'; ================================================ FILE: test/index.html ================================================ react-daterange-picker test page
================================================ FILE: test/index.tsx ================================================ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import Test from './Test.js'; const root = document.getElementById('root'); if (!root) { throw new Error('Could not find root element'); } createRoot(root).render( , ); ================================================ FILE: test/package.json ================================================ { "name": "test", "version": "2.0.0", "description": "A test page for React-DateRange-Picker.", "private": true, "type": "module", "scripts": { "build": "vite build", "dev": "vite", "format": "biome format", "lint": "biome lint", "preview": "vite preview", "test": "yarn lint && yarn tsc && yarn format", "tsc": "tsc" }, "author": { "name": "Wojciech Maj", "email": "kontakt@wojtekmaj.pl" }, "license": "MIT", "dependencies": { "@wojtekmaj/date-utils": "^2.0.2", "@wojtekmaj/react-daterange-picker": "workspace:packages/react-daterange-picker", "react": "^19.2.0", "react-dom": "^19.2.0" }, "devDependencies": { "@biomejs/biome": "2.4.10", "@types/react": "^19.2.0", "@vitejs/plugin-react": "^6.0.1", "typescript": "^6.0.2", "vite": "^8.0.5" } } ================================================ FILE: test/shared/types.ts ================================================ type Range = [T, T]; export type Detail = 'century' | 'decade' | 'year' | 'month'; type LooseValuePiece = string | Date | null; export type LooseValue = LooseValuePiece | Range; ================================================ FILE: test/tsconfig.json ================================================ { "compilerOptions": { "isolatedModules": true, "jsx": "react-jsx", "module": "preserve", "moduleDetection": "force", "noEmit": true, "noUncheckedIndexedAccess": true, "skipLibCheck": true, "target": "esnext", "verbatimModuleSyntax": true } } ================================================ FILE: test/vite.config.ts ================================================ import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ base: './', plugins: [react()], });