index.esm.js 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277
  1. import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
  2. import { createContext, useContext, useState, forwardRef, useEffect, useRef, useLayoutEffect } from 'react';
  3. import { format, startOfMonth, endOfMonth, startOfDay, isSameYear, setMonth, setYear, startOfYear, differenceInCalendarMonths, addMonths, isSameMonth, isBefore, startOfISOWeek, startOfWeek, addDays, isSameDay, isAfter, subDays, differenceInCalendarDays, isDate, max, min, addWeeks, addYears, endOfISOWeek, endOfWeek, getUnixTime, getISOWeek, getWeek, getWeeksInMonth, parse } from 'date-fns';
  4. import { enUS } from 'date-fns/locale';
  5. /******************************************************************************
  6. Copyright (c) Microsoft Corporation.
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted.
  9. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  10. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  11. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  13. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  14. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  15. PERFORMANCE OF THIS SOFTWARE.
  16. ***************************************************************************** */
  17. /* global Reflect, Promise, SuppressedError, Symbol */
  18. var __assign = function() {
  19. __assign = Object.assign || function __assign(t) {
  20. for (var s, i = 1, n = arguments.length; i < n; i++) {
  21. s = arguments[i];
  22. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  23. }
  24. return t;
  25. };
  26. return __assign.apply(this, arguments);
  27. };
  28. function __rest(s, e) {
  29. var t = {};
  30. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  31. t[p] = s[p];
  32. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  33. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  34. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  35. t[p[i]] = s[p[i]];
  36. }
  37. return t;
  38. }
  39. function __spreadArray(to, from, pack) {
  40. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  41. if (ar || !(i in from)) {
  42. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  43. ar[i] = from[i];
  44. }
  45. }
  46. return to.concat(ar || Array.prototype.slice.call(from));
  47. }
  48. typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
  49. var e = new Error(message);
  50. return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
  51. };
  52. /** Returns true when the props are of type {@link DayPickerMultipleProps}. */
  53. function isDayPickerMultiple(props) {
  54. return props.mode === 'multiple';
  55. }
  56. /** Returns true when the props are of type {@link DayPickerRangeProps}. */
  57. function isDayPickerRange(props) {
  58. return props.mode === 'range';
  59. }
  60. /** Returns true when the props are of type {@link DayPickerSingleProps}. */
  61. function isDayPickerSingle(props) {
  62. return props.mode === 'single';
  63. }
  64. /**
  65. * The name of the default CSS classes.
  66. */
  67. var defaultClassNames = {
  68. root: 'rdp',
  69. multiple_months: 'rdp-multiple_months',
  70. with_weeknumber: 'rdp-with_weeknumber',
  71. vhidden: 'rdp-vhidden',
  72. button_reset: 'rdp-button_reset',
  73. button: 'rdp-button',
  74. caption: 'rdp-caption',
  75. caption_start: 'rdp-caption_start',
  76. caption_end: 'rdp-caption_end',
  77. caption_between: 'rdp-caption_between',
  78. caption_label: 'rdp-caption_label',
  79. caption_dropdowns: 'rdp-caption_dropdowns',
  80. dropdown: 'rdp-dropdown',
  81. dropdown_month: 'rdp-dropdown_month',
  82. dropdown_year: 'rdp-dropdown_year',
  83. dropdown_icon: 'rdp-dropdown_icon',
  84. months: 'rdp-months',
  85. month: 'rdp-month',
  86. table: 'rdp-table',
  87. tbody: 'rdp-tbody',
  88. tfoot: 'rdp-tfoot',
  89. head: 'rdp-head',
  90. head_row: 'rdp-head_row',
  91. head_cell: 'rdp-head_cell',
  92. nav: 'rdp-nav',
  93. nav_button: 'rdp-nav_button',
  94. nav_button_previous: 'rdp-nav_button_previous',
  95. nav_button_next: 'rdp-nav_button_next',
  96. nav_icon: 'rdp-nav_icon',
  97. row: 'rdp-row',
  98. weeknumber: 'rdp-weeknumber',
  99. cell: 'rdp-cell',
  100. day: 'rdp-day',
  101. day_today: 'rdp-day_today',
  102. day_outside: 'rdp-day_outside',
  103. day_selected: 'rdp-day_selected',
  104. day_disabled: 'rdp-day_disabled',
  105. day_hidden: 'rdp-day_hidden',
  106. day_range_start: 'rdp-day_range_start',
  107. day_range_end: 'rdp-day_range_end',
  108. day_range_middle: 'rdp-day_range_middle'
  109. };
  110. /**
  111. * The default formatter for the caption.
  112. */
  113. function formatCaption(month, options) {
  114. return format(month, 'LLLL y', options);
  115. }
  116. /**
  117. * The default formatter for the Day button.
  118. */
  119. function formatDay(day, options) {
  120. return format(day, 'd', options);
  121. }
  122. /**
  123. * The default formatter for the Month caption.
  124. */
  125. function formatMonthCaption(month, options) {
  126. return format(month, 'LLLL', options);
  127. }
  128. /**
  129. * The default formatter for the week number.
  130. */
  131. function formatWeekNumber(weekNumber) {
  132. return "".concat(weekNumber);
  133. }
  134. /**
  135. * The default formatter for the name of the weekday.
  136. */
  137. function formatWeekdayName(weekday, options) {
  138. return format(weekday, 'cccccc', options);
  139. }
  140. /**
  141. * The default formatter for the Year caption.
  142. */
  143. function formatYearCaption(year, options) {
  144. return format(year, 'yyyy', options);
  145. }
  146. var formatters = /*#__PURE__*/Object.freeze({
  147. __proto__: null,
  148. formatCaption: formatCaption,
  149. formatDay: formatDay,
  150. formatMonthCaption: formatMonthCaption,
  151. formatWeekNumber: formatWeekNumber,
  152. formatWeekdayName: formatWeekdayName,
  153. formatYearCaption: formatYearCaption
  154. });
  155. /**
  156. * The default ARIA label for the day button.
  157. */
  158. var labelDay = function (day, activeModifiers, options) {
  159. return format(day, 'do MMMM (EEEE)', options);
  160. };
  161. /**
  162. * The default ARIA label for the WeekNumber element.
  163. */
  164. var labelMonthDropdown = function () {
  165. return 'Month: ';
  166. };
  167. /**
  168. * The default ARIA label for next month button in navigation
  169. */
  170. var labelNext = function () {
  171. return 'Go to next month';
  172. };
  173. /**
  174. * The default ARIA label for previous month button in navigation
  175. */
  176. var labelPrevious = function () {
  177. return 'Go to previous month';
  178. };
  179. /**
  180. * The default ARIA label for the Weekday element.
  181. */
  182. var labelWeekday = function (day, options) {
  183. return format(day, 'cccc', options);
  184. };
  185. /**
  186. * The default ARIA label for the WeekNumber element.
  187. */
  188. var labelWeekNumber = function (n) {
  189. return "Week n. ".concat(n);
  190. };
  191. /**
  192. * The default ARIA label for the WeekNumber element.
  193. */
  194. var labelYearDropdown = function () {
  195. return 'Year: ';
  196. };
  197. var labels = /*#__PURE__*/Object.freeze({
  198. __proto__: null,
  199. labelDay: labelDay,
  200. labelMonthDropdown: labelMonthDropdown,
  201. labelNext: labelNext,
  202. labelPrevious: labelPrevious,
  203. labelWeekNumber: labelWeekNumber,
  204. labelWeekday: labelWeekday,
  205. labelYearDropdown: labelYearDropdown
  206. });
  207. /**
  208. * Returns the default values to use in the DayPickerContext, in case they are
  209. * not passed down with the DayPicker initial props.
  210. */
  211. function getDefaultContextValues() {
  212. var captionLayout = 'buttons';
  213. var classNames = defaultClassNames;
  214. var locale = enUS;
  215. var modifiersClassNames = {};
  216. var modifiers = {};
  217. var numberOfMonths = 1;
  218. var styles = {};
  219. var today = new Date();
  220. return {
  221. captionLayout: captionLayout,
  222. classNames: classNames,
  223. formatters: formatters,
  224. labels: labels,
  225. locale: locale,
  226. modifiersClassNames: modifiersClassNames,
  227. modifiers: modifiers,
  228. numberOfMonths: numberOfMonths,
  229. styles: styles,
  230. today: today,
  231. mode: 'default'
  232. };
  233. }
  234. /** Return the `fromDate` and `toDate` prop values values parsing the DayPicker props. */
  235. function parseFromToProps(props) {
  236. var fromYear = props.fromYear, toYear = props.toYear, fromMonth = props.fromMonth, toMonth = props.toMonth;
  237. var fromDate = props.fromDate, toDate = props.toDate;
  238. if (fromMonth) {
  239. fromDate = startOfMonth(fromMonth);
  240. }
  241. else if (fromYear) {
  242. fromDate = new Date(fromYear, 0, 1);
  243. }
  244. if (toMonth) {
  245. toDate = endOfMonth(toMonth);
  246. }
  247. else if (toYear) {
  248. toDate = new Date(toYear, 11, 31);
  249. }
  250. return {
  251. fromDate: fromDate ? startOfDay(fromDate) : undefined,
  252. toDate: toDate ? startOfDay(toDate) : undefined
  253. };
  254. }
  255. /**
  256. * The DayPicker context shares the props passed to DayPicker within internal
  257. * and custom components. It is used to set the default values and perform
  258. * one-time calculations required to render the days.
  259. *
  260. * Access to this context from the {@link useDayPicker} hook.
  261. */
  262. var DayPickerContext = createContext(undefined);
  263. /**
  264. * The provider for the {@link DayPickerContext}, assigning the defaults from the
  265. * initial DayPicker props.
  266. */
  267. function DayPickerProvider(props) {
  268. var _a;
  269. var initialProps = props.initialProps;
  270. var defaultContextValues = getDefaultContextValues();
  271. var _b = parseFromToProps(initialProps), fromDate = _b.fromDate, toDate = _b.toDate;
  272. var captionLayout = (_a = initialProps.captionLayout) !== null && _a !== void 0 ? _a : defaultContextValues.captionLayout;
  273. if (captionLayout !== 'buttons' && (!fromDate || !toDate)) {
  274. // When no from/to dates are set, the caption is always buttons
  275. captionLayout = 'buttons';
  276. }
  277. var onSelect;
  278. if (isDayPickerSingle(initialProps) ||
  279. isDayPickerMultiple(initialProps) ||
  280. isDayPickerRange(initialProps)) {
  281. onSelect = initialProps.onSelect;
  282. }
  283. var value = __assign(__assign(__assign({}, defaultContextValues), initialProps), { captionLayout: captionLayout, classNames: __assign(__assign({}, defaultContextValues.classNames), initialProps.classNames), components: __assign({}, initialProps.components), formatters: __assign(__assign({}, defaultContextValues.formatters), initialProps.formatters), fromDate: fromDate, labels: __assign(__assign({}, defaultContextValues.labels), initialProps.labels), mode: initialProps.mode || defaultContextValues.mode, modifiers: __assign(__assign({}, defaultContextValues.modifiers), initialProps.modifiers), modifiersClassNames: __assign(__assign({}, defaultContextValues.modifiersClassNames), initialProps.modifiersClassNames), onSelect: onSelect, styles: __assign(__assign({}, defaultContextValues.styles), initialProps.styles), toDate: toDate });
  284. return (jsx(DayPickerContext.Provider, { value: value, children: props.children }));
  285. }
  286. /**
  287. * Hook to access the {@link DayPickerContextValue}.
  288. *
  289. * Use the DayPicker context to access to the props passed to DayPicker inside
  290. * internal or custom components.
  291. */
  292. function useDayPicker() {
  293. var context = useContext(DayPickerContext);
  294. if (!context) {
  295. throw new Error("useDayPicker must be used within a DayPickerProvider.");
  296. }
  297. return context;
  298. }
  299. /** Render the caption for the displayed month. This component is used when `captionLayout="buttons"`. */
  300. function CaptionLabel(props) {
  301. var _a = useDayPicker(), locale = _a.locale, classNames = _a.classNames, styles = _a.styles, formatCaption = _a.formatters.formatCaption;
  302. return (jsx("div", { className: classNames.caption_label, style: styles.caption_label, "aria-live": "polite", role: "presentation", id: props.id, children: formatCaption(props.displayMonth, { locale: locale }) }));
  303. }
  304. /**
  305. * Render the icon in the styled drop-down.
  306. */
  307. function IconDropdown(props) {
  308. return (jsx("svg", __assign({ width: "8px", height: "8px", viewBox: "0 0 120 120", "data-testid": "iconDropdown" }, props, { children: jsx("path", { d: "M4.22182541,48.2218254 C8.44222828,44.0014225 15.2388494,43.9273804 19.5496459,47.9996989 L19.7781746,48.2218254 L60,88.443 L100.221825,48.2218254 C104.442228,44.0014225 111.238849,43.9273804 115.549646,47.9996989 L115.778175,48.2218254 C119.998577,52.4422283 120.07262,59.2388494 116.000301,63.5496459 L115.778175,63.7781746 L67.7781746,111.778175 C63.5577717,115.998577 56.7611506,116.07262 52.4503541,112.000301 L52.2218254,111.778175 L4.22182541,63.7781746 C-0.0739418023,59.4824074 -0.0739418023,52.5175926 4.22182541,48.2218254 Z", fill: "currentColor", fillRule: "nonzero" }) })));
  309. }
  310. /**
  311. * Render a styled select component – displaying a caption and a custom
  312. * drop-down icon.
  313. */
  314. function Dropdown(props) {
  315. var _a, _b;
  316. var onChange = props.onChange, value = props.value, children = props.children, caption = props.caption, className = props.className, style = props.style;
  317. var dayPicker = useDayPicker();
  318. var IconDropdownComponent = (_b = (_a = dayPicker.components) === null || _a === void 0 ? void 0 : _a.IconDropdown) !== null && _b !== void 0 ? _b : IconDropdown;
  319. return (jsxs("div", { className: className, style: style, children: [jsx("span", { className: dayPicker.classNames.vhidden, children: props['aria-label'] }), jsx("select", { name: props.name, "aria-label": props['aria-label'], className: dayPicker.classNames.dropdown, style: dayPicker.styles.dropdown, value: value, onChange: onChange, children: children }), jsxs("div", { className: dayPicker.classNames.caption_label, style: dayPicker.styles.caption_label, "aria-hidden": "true", children: [caption, jsx(IconDropdownComponent, { className: dayPicker.classNames.dropdown_icon, style: dayPicker.styles.dropdown_icon })] })] }));
  320. }
  321. /** Render the dropdown to navigate between months. */
  322. function MonthsDropdown(props) {
  323. var _a;
  324. var _b = useDayPicker(), fromDate = _b.fromDate, toDate = _b.toDate, styles = _b.styles, locale = _b.locale, formatMonthCaption = _b.formatters.formatMonthCaption, classNames = _b.classNames, components = _b.components, labelMonthDropdown = _b.labels.labelMonthDropdown;
  325. // Dropdown should appear only when both from/toDate is set
  326. if (!fromDate)
  327. return jsx(Fragment, {});
  328. if (!toDate)
  329. return jsx(Fragment, {});
  330. var dropdownMonths = [];
  331. if (isSameYear(fromDate, toDate)) {
  332. // only display the months included in the range
  333. var date = startOfMonth(fromDate);
  334. for (var month = fromDate.getMonth(); month <= toDate.getMonth(); month++) {
  335. dropdownMonths.push(setMonth(date, month));
  336. }
  337. }
  338. else {
  339. // display all the 12 months
  340. var date = startOfMonth(new Date()); // Any date should be OK, as we just need the year
  341. for (var month = 0; month <= 11; month++) {
  342. dropdownMonths.push(setMonth(date, month));
  343. }
  344. }
  345. var handleChange = function (e) {
  346. var selectedMonth = Number(e.target.value);
  347. var newMonth = setMonth(startOfMonth(props.displayMonth), selectedMonth);
  348. props.onChange(newMonth);
  349. };
  350. var DropdownComponent = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown;
  351. return (jsx(DropdownComponent, { name: "months", "aria-label": labelMonthDropdown(), className: classNames.dropdown_month, style: styles.dropdown_month, onChange: handleChange, value: props.displayMonth.getMonth(), caption: formatMonthCaption(props.displayMonth, { locale: locale }), children: dropdownMonths.map(function (m) { return (jsx("option", { value: m.getMonth(), children: formatMonthCaption(m, { locale: locale }) }, m.getMonth())); }) }));
  352. }
  353. /**
  354. * Render a dropdown to change the year. Take in account the `nav.fromDate` and
  355. * `toDate` from context.
  356. */
  357. function YearsDropdown(props) {
  358. var _a;
  359. var displayMonth = props.displayMonth;
  360. var _b = useDayPicker(), fromDate = _b.fromDate, toDate = _b.toDate, locale = _b.locale, styles = _b.styles, classNames = _b.classNames, components = _b.components, formatYearCaption = _b.formatters.formatYearCaption, labelYearDropdown = _b.labels.labelYearDropdown;
  361. var years = [];
  362. // Dropdown should appear only when both from/toDate is set
  363. if (!fromDate)
  364. return jsx(Fragment, {});
  365. if (!toDate)
  366. return jsx(Fragment, {});
  367. var fromYear = fromDate.getFullYear();
  368. var toYear = toDate.getFullYear();
  369. for (var year = fromYear; year <= toYear; year++) {
  370. years.push(setYear(startOfYear(new Date()), year));
  371. }
  372. var handleChange = function (e) {
  373. var newMonth = setYear(startOfMonth(displayMonth), Number(e.target.value));
  374. props.onChange(newMonth);
  375. };
  376. var DropdownComponent = (_a = components === null || components === void 0 ? void 0 : components.Dropdown) !== null && _a !== void 0 ? _a : Dropdown;
  377. return (jsx(DropdownComponent, { name: "years", "aria-label": labelYearDropdown(), className: classNames.dropdown_year, style: styles.dropdown_year, onChange: handleChange, value: displayMonth.getFullYear(), caption: formatYearCaption(displayMonth, { locale: locale }), children: years.map(function (year) { return (jsx("option", { value: year.getFullYear(), children: formatYearCaption(year, { locale: locale }) }, year.getFullYear())); }) }));
  378. }
  379. /**
  380. * Helper hook for using controlled/uncontrolled values from a component props.
  381. *
  382. * When the value is not controlled, pass `undefined` as `controlledValue` and
  383. * use the returned setter to update it.
  384. *
  385. * When the value is controlled, pass the controlled value as second
  386. * argument, which will be always returned as `value`.
  387. */
  388. function useControlledValue(defaultValue, controlledValue) {
  389. var _a = useState(defaultValue), uncontrolledValue = _a[0], setValue = _a[1];
  390. var value = controlledValue === undefined ? uncontrolledValue : controlledValue;
  391. return [value, setValue];
  392. }
  393. /** Return the initial month according to the given options. */
  394. function getInitialMonth(context) {
  395. var month = context.month, defaultMonth = context.defaultMonth, today = context.today;
  396. var initialMonth = month || defaultMonth || today || new Date();
  397. var toDate = context.toDate, fromDate = context.fromDate, _a = context.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;
  398. // Fix the initialMonth if is after the to-date
  399. if (toDate && differenceInCalendarMonths(toDate, initialMonth) < 0) {
  400. var offset = -1 * (numberOfMonths - 1);
  401. initialMonth = addMonths(toDate, offset);
  402. }
  403. // Fix the initialMonth if is before the from-date
  404. if (fromDate && differenceInCalendarMonths(initialMonth, fromDate) < 0) {
  405. initialMonth = fromDate;
  406. }
  407. return startOfMonth(initialMonth);
  408. }
  409. /** Controls the navigation state. */
  410. function useNavigationState() {
  411. var context = useDayPicker();
  412. var initialMonth = getInitialMonth(context);
  413. var _a = useControlledValue(initialMonth, context.month), month = _a[0], setMonth = _a[1];
  414. var goToMonth = function (date) {
  415. var _a;
  416. if (context.disableNavigation)
  417. return;
  418. var month = startOfMonth(date);
  419. setMonth(month);
  420. (_a = context.onMonthChange) === null || _a === void 0 ? void 0 : _a.call(context, month);
  421. };
  422. return [month, goToMonth];
  423. }
  424. /**
  425. * Return the months to display in the component according to the number of
  426. * months and the from/to date.
  427. */
  428. function getDisplayMonths(month, _a) {
  429. var reverseMonths = _a.reverseMonths, numberOfMonths = _a.numberOfMonths;
  430. var start = startOfMonth(month);
  431. var end = startOfMonth(addMonths(start, numberOfMonths));
  432. var monthsDiff = differenceInCalendarMonths(end, start);
  433. var months = [];
  434. for (var i = 0; i < monthsDiff; i++) {
  435. var nextMonth = addMonths(start, i);
  436. months.push(nextMonth);
  437. }
  438. if (reverseMonths)
  439. months = months.reverse();
  440. return months;
  441. }
  442. /**
  443. * Returns the next month the user can navigate to according to the given
  444. * options.
  445. *
  446. * Please note that the next month is not always the next calendar month:
  447. *
  448. * - if after the `toDate` range, is undefined;
  449. * - if the navigation is paged, is the number of months displayed ahead.
  450. *
  451. */
  452. function getNextMonth(startingMonth, options) {
  453. if (options.disableNavigation) {
  454. return undefined;
  455. }
  456. var toDate = options.toDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;
  457. var offset = pagedNavigation ? numberOfMonths : 1;
  458. var month = startOfMonth(startingMonth);
  459. if (!toDate) {
  460. return addMonths(month, offset);
  461. }
  462. var monthsDiff = differenceInCalendarMonths(toDate, startingMonth);
  463. if (monthsDiff < numberOfMonths) {
  464. return undefined;
  465. }
  466. // Jump forward as the number of months when paged navigation
  467. return addMonths(month, offset);
  468. }
  469. /**
  470. * Returns the next previous the user can navigate to, according to the given
  471. * options.
  472. *
  473. * Please note that the previous month is not always the previous calendar
  474. * month:
  475. *
  476. * - if before the `fromDate` date, is `undefined`;
  477. * - if the navigation is paged, is the number of months displayed before.
  478. *
  479. */
  480. function getPreviousMonth(startingMonth, options) {
  481. if (options.disableNavigation) {
  482. return undefined;
  483. }
  484. var fromDate = options.fromDate, pagedNavigation = options.pagedNavigation, _a = options.numberOfMonths, numberOfMonths = _a === void 0 ? 1 : _a;
  485. var offset = pagedNavigation ? numberOfMonths : 1;
  486. var month = startOfMonth(startingMonth);
  487. if (!fromDate) {
  488. return addMonths(month, -offset);
  489. }
  490. var monthsDiff = differenceInCalendarMonths(month, fromDate);
  491. if (monthsDiff <= 0) {
  492. return undefined;
  493. }
  494. // Jump back as the number of months when paged navigation
  495. return addMonths(month, -offset);
  496. }
  497. /**
  498. * The Navigation context shares details and methods to navigate the months in DayPicker.
  499. * Access this context from the {@link useNavigation} hook.
  500. */
  501. var NavigationContext = createContext(undefined);
  502. /** Provides the values for the {@link NavigationContext}. */
  503. function NavigationProvider(props) {
  504. var dayPicker = useDayPicker();
  505. var _a = useNavigationState(), currentMonth = _a[0], goToMonth = _a[1];
  506. var displayMonths = getDisplayMonths(currentMonth, dayPicker);
  507. var nextMonth = getNextMonth(currentMonth, dayPicker);
  508. var previousMonth = getPreviousMonth(currentMonth, dayPicker);
  509. var isDateDisplayed = function (date) {
  510. return displayMonths.some(function (displayMonth) {
  511. return isSameMonth(date, displayMonth);
  512. });
  513. };
  514. var goToDate = function (date, refDate) {
  515. if (isDateDisplayed(date)) {
  516. return;
  517. }
  518. if (refDate && isBefore(date, refDate)) {
  519. goToMonth(addMonths(date, 1 + dayPicker.numberOfMonths * -1));
  520. }
  521. else {
  522. goToMonth(date);
  523. }
  524. };
  525. var value = {
  526. currentMonth: currentMonth,
  527. displayMonths: displayMonths,
  528. goToMonth: goToMonth,
  529. goToDate: goToDate,
  530. previousMonth: previousMonth,
  531. nextMonth: nextMonth,
  532. isDateDisplayed: isDateDisplayed
  533. };
  534. return (jsx(NavigationContext.Provider, { value: value, children: props.children }));
  535. }
  536. /**
  537. * Hook to access the {@link NavigationContextValue}. Use this hook to navigate
  538. * between months or years in DayPicker.
  539. *
  540. * This hook is meant to be used inside internal or custom components.
  541. */
  542. function useNavigation() {
  543. var context = useContext(NavigationContext);
  544. if (!context) {
  545. throw new Error('useNavigation must be used within a NavigationProvider');
  546. }
  547. return context;
  548. }
  549. /**
  550. * Render a caption with the dropdowns to navigate between months and years.
  551. */
  552. function CaptionDropdowns(props) {
  553. var _a;
  554. var _b = useDayPicker(), classNames = _b.classNames, styles = _b.styles, components = _b.components;
  555. var goToMonth = useNavigation().goToMonth;
  556. var handleMonthChange = function (newMonth) {
  557. goToMonth(addMonths(newMonth, props.displayIndex ? -props.displayIndex : 0));
  558. };
  559. var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel;
  560. var captionLabel = (jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }));
  561. return (jsxs("div", { className: classNames.caption_dropdowns, style: styles.caption_dropdowns, children: [jsx("div", { className: classNames.vhidden, children: captionLabel }), jsx(MonthsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth }), jsx(YearsDropdown, { onChange: handleMonthChange, displayMonth: props.displayMonth })] }));
  562. }
  563. /**
  564. * Render the "previous month" button in the navigation.
  565. */
  566. function IconLeft(props) {
  567. return (jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsx("path", { d: "M69.490332,3.34314575 C72.6145263,0.218951416 77.6798462,0.218951416 80.8040405,3.34314575 C83.8617626,6.40086786 83.9268205,11.3179931 80.9992143,14.4548388 L80.8040405,14.6568542 L35.461,60 L80.8040405,105.343146 C83.8617626,108.400868 83.9268205,113.317993 80.9992143,116.454839 L80.8040405,116.656854 C77.7463184,119.714576 72.8291931,119.779634 69.6923475,116.852028 L69.490332,116.656854 L18.490332,65.6568542 C15.4326099,62.5991321 15.367552,57.6820069 18.2951583,54.5451612 L18.490332,54.3431458 L69.490332,3.34314575 Z", fill: "currentColor", fillRule: "nonzero" }) })));
  568. }
  569. /**
  570. * Render the "next month" button in the navigation.
  571. */
  572. function IconRight(props) {
  573. return (jsx("svg", __assign({ width: "16px", height: "16px", viewBox: "0 0 120 120" }, props, { children: jsx("path", { d: "M49.8040405,3.34314575 C46.6798462,0.218951416 41.6145263,0.218951416 38.490332,3.34314575 C35.4326099,6.40086786 35.367552,11.3179931 38.2951583,14.4548388 L38.490332,14.6568542 L83.8333725,60 L38.490332,105.343146 C35.4326099,108.400868 35.367552,113.317993 38.2951583,116.454839 L38.490332,116.656854 C41.5480541,119.714576 46.4651794,119.779634 49.602025,116.852028 L49.8040405,116.656854 L100.804041,65.6568542 C103.861763,62.5991321 103.926821,57.6820069 100.999214,54.5451612 L100.804041,54.3431458 L49.8040405,3.34314575 Z", fill: "currentColor" }) })));
  574. }
  575. /** Render a button HTML element applying the reset class name. */
  576. var Button = forwardRef(function (props, ref) {
  577. var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles;
  578. var classNamesArr = [classNames.button_reset, classNames.button];
  579. if (props.className) {
  580. classNamesArr.push(props.className);
  581. }
  582. var className = classNamesArr.join(' ');
  583. var style = __assign(__assign({}, styles.button_reset), styles.button);
  584. if (props.style) {
  585. Object.assign(style, props.style);
  586. }
  587. return (jsx("button", __assign({}, props, { ref: ref, type: "button", className: className, style: style })));
  588. });
  589. /** A component rendering the navigation buttons or the drop-downs. */
  590. function Navigation(props) {
  591. var _a, _b;
  592. var _c = useDayPicker(), dir = _c.dir, locale = _c.locale, classNames = _c.classNames, styles = _c.styles, _d = _c.labels, labelPrevious = _d.labelPrevious, labelNext = _d.labelNext, components = _c.components;
  593. if (!props.nextMonth && !props.previousMonth) {
  594. return jsx(Fragment, {});
  595. }
  596. var previousLabel = labelPrevious(props.previousMonth, { locale: locale });
  597. var previousClassName = [
  598. classNames.nav_button,
  599. classNames.nav_button_previous
  600. ].join(' ');
  601. var nextLabel = labelNext(props.nextMonth, { locale: locale });
  602. var nextClassName = [
  603. classNames.nav_button,
  604. classNames.nav_button_next
  605. ].join(' ');
  606. var IconRightComponent = (_a = components === null || components === void 0 ? void 0 : components.IconRight) !== null && _a !== void 0 ? _a : IconRight;
  607. var IconLeftComponent = (_b = components === null || components === void 0 ? void 0 : components.IconLeft) !== null && _b !== void 0 ? _b : IconLeft;
  608. return (jsxs("div", { className: classNames.nav, style: styles.nav, children: [!props.hidePrevious && (jsx(Button, { name: "previous-month", "aria-label": previousLabel, className: previousClassName, style: styles.nav_button_previous, disabled: !props.previousMonth, onClick: props.onPreviousClick, children: dir === 'rtl' ? (jsx(IconRightComponent, { className: classNames.nav_icon, style: styles.nav_icon })) : (jsx(IconLeftComponent, { className: classNames.nav_icon, style: styles.nav_icon })) })), !props.hideNext && (jsx(Button, { name: "next-month", "aria-label": nextLabel, className: nextClassName, style: styles.nav_button_next, disabled: !props.nextMonth, onClick: props.onNextClick, children: dir === 'rtl' ? (jsx(IconLeftComponent, { className: classNames.nav_icon, style: styles.nav_icon })) : (jsx(IconRightComponent, { className: classNames.nav_icon, style: styles.nav_icon })) }))] }));
  609. }
  610. /**
  611. * Render a caption with a button-based navigation.
  612. */
  613. function CaptionNavigation(props) {
  614. var numberOfMonths = useDayPicker().numberOfMonths;
  615. var _a = useNavigation(), previousMonth = _a.previousMonth, nextMonth = _a.nextMonth, goToMonth = _a.goToMonth, displayMonths = _a.displayMonths;
  616. var displayIndex = displayMonths.findIndex(function (month) {
  617. return isSameMonth(props.displayMonth, month);
  618. });
  619. var isFirst = displayIndex === 0;
  620. var isLast = displayIndex === displayMonths.length - 1;
  621. var hideNext = numberOfMonths > 1 && (isFirst || !isLast);
  622. var hidePrevious = numberOfMonths > 1 && (isLast || !isFirst);
  623. var handlePreviousClick = function () {
  624. if (!previousMonth)
  625. return;
  626. goToMonth(previousMonth);
  627. };
  628. var handleNextClick = function () {
  629. if (!nextMonth)
  630. return;
  631. goToMonth(nextMonth);
  632. };
  633. return (jsx(Navigation, { displayMonth: props.displayMonth, hideNext: hideNext, hidePrevious: hidePrevious, nextMonth: nextMonth, previousMonth: previousMonth, onPreviousClick: handlePreviousClick, onNextClick: handleNextClick }));
  634. }
  635. /**
  636. * Render the caption of a month. The caption has a different layout when
  637. * setting the {@link DayPickerBase.captionLayout} prop.
  638. */
  639. function Caption(props) {
  640. var _a;
  641. var _b = useDayPicker(), classNames = _b.classNames, disableNavigation = _b.disableNavigation, styles = _b.styles, captionLayout = _b.captionLayout, components = _b.components;
  642. var CaptionLabelComponent = (_a = components === null || components === void 0 ? void 0 : components.CaptionLabel) !== null && _a !== void 0 ? _a : CaptionLabel;
  643. var caption;
  644. if (disableNavigation) {
  645. caption = (jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth }));
  646. }
  647. else if (captionLayout === 'dropdown') {
  648. caption = (jsx(CaptionDropdowns, { displayMonth: props.displayMonth, id: props.id }));
  649. }
  650. else if (captionLayout === 'dropdown-buttons') {
  651. caption = (jsxs(Fragment, { children: [jsx(CaptionDropdowns, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id }), jsx(CaptionNavigation, { displayMonth: props.displayMonth, displayIndex: props.displayIndex, id: props.id })] }));
  652. }
  653. else {
  654. caption = (jsxs(Fragment, { children: [jsx(CaptionLabelComponent, { id: props.id, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsx(CaptionNavigation, { displayMonth: props.displayMonth, id: props.id })] }));
  655. }
  656. return (jsx("div", { className: classNames.caption, style: styles.caption, children: caption }));
  657. }
  658. /** Render the Footer component (empty as default).*/
  659. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  660. function Footer(props) {
  661. var _a = useDayPicker(), footer = _a.footer, styles = _a.styles, tfoot = _a.classNames.tfoot;
  662. if (!footer)
  663. return jsx(Fragment, {});
  664. return (jsx("tfoot", { className: tfoot, style: styles.tfoot, children: jsx("tr", { children: jsx("td", { colSpan: 8, children: footer }) }) }));
  665. }
  666. /**
  667. * Generate a series of 7 days, starting from the week, to use for formatting
  668. * the weekday names (Monday, Tuesday, etc.).
  669. */
  670. function getWeekdays(locale,
  671. /** The index of the first day of the week (0 - Sunday). */
  672. weekStartsOn,
  673. /** Use ISOWeek instead of locale/ */
  674. ISOWeek) {
  675. var start = ISOWeek
  676. ? startOfISOWeek(new Date())
  677. : startOfWeek(new Date(), { locale: locale, weekStartsOn: weekStartsOn });
  678. var days = [];
  679. for (var i = 0; i < 7; i++) {
  680. var day = addDays(start, i);
  681. days.push(day);
  682. }
  683. return days;
  684. }
  685. /**
  686. * Render the HeadRow component - i.e. the table head row with the weekday names.
  687. */
  688. function HeadRow() {
  689. var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles, showWeekNumber = _a.showWeekNumber, locale = _a.locale, weekStartsOn = _a.weekStartsOn, ISOWeek = _a.ISOWeek, formatWeekdayName = _a.formatters.formatWeekdayName, labelWeekday = _a.labels.labelWeekday;
  690. var weekdays = getWeekdays(locale, weekStartsOn, ISOWeek);
  691. return (jsxs("tr", { style: styles.head_row, className: classNames.head_row, children: [showWeekNumber && (jsx("td", { style: styles.head_cell, className: classNames.head_cell })), weekdays.map(function (weekday, i) { return (jsx("th", { scope: "col", className: classNames.head_cell, style: styles.head_cell, "aria-label": labelWeekday(weekday, { locale: locale }), children: formatWeekdayName(weekday, { locale: locale }) }, i)); })] }));
  692. }
  693. /** Render the table head. */
  694. function Head() {
  695. var _a;
  696. var _b = useDayPicker(), classNames = _b.classNames, styles = _b.styles, components = _b.components;
  697. var HeadRowComponent = (_a = components === null || components === void 0 ? void 0 : components.HeadRow) !== null && _a !== void 0 ? _a : HeadRow;
  698. return (jsx("thead", { style: styles.head, className: classNames.head, children: jsx(HeadRowComponent, {}) }));
  699. }
  700. /** Render the content of the day cell. */
  701. function DayContent(props) {
  702. var _a = useDayPicker(), locale = _a.locale, formatDay = _a.formatters.formatDay;
  703. return jsx(Fragment, { children: formatDay(props.date, { locale: locale }) });
  704. }
  705. /**
  706. * The SelectMultiple context shares details about the selected days when in
  707. * multiple selection mode.
  708. *
  709. * Access this context from the {@link useSelectMultiple} hook.
  710. */
  711. var SelectMultipleContext = createContext(undefined);
  712. /** Provides the values for the {@link SelectMultipleContext}. */
  713. function SelectMultipleProvider(props) {
  714. if (!isDayPickerMultiple(props.initialProps)) {
  715. var emptyContextValue = {
  716. selected: undefined,
  717. modifiers: {
  718. disabled: []
  719. }
  720. };
  721. return (jsx(SelectMultipleContext.Provider, { value: emptyContextValue, children: props.children }));
  722. }
  723. return (jsx(SelectMultipleProviderInternal, { initialProps: props.initialProps, children: props.children }));
  724. }
  725. function SelectMultipleProviderInternal(_a) {
  726. var initialProps = _a.initialProps, children = _a.children;
  727. var selected = initialProps.selected, min = initialProps.min, max = initialProps.max;
  728. var onDayClick = function (day, activeModifiers, e) {
  729. var _a, _b;
  730. (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);
  731. var isMinSelected = Boolean(activeModifiers.selected && min && (selected === null || selected === void 0 ? void 0 : selected.length) === min);
  732. if (isMinSelected) {
  733. return;
  734. }
  735. var isMaxSelected = Boolean(!activeModifiers.selected && max && (selected === null || selected === void 0 ? void 0 : selected.length) === max);
  736. if (isMaxSelected) {
  737. return;
  738. }
  739. var selectedDays = selected ? __spreadArray([], selected, true) : [];
  740. if (activeModifiers.selected) {
  741. var index = selectedDays.findIndex(function (selectedDay) {
  742. return isSameDay(day, selectedDay);
  743. });
  744. selectedDays.splice(index, 1);
  745. }
  746. else {
  747. selectedDays.push(day);
  748. }
  749. (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, selectedDays, day, activeModifiers, e);
  750. };
  751. var modifiers = {
  752. disabled: []
  753. };
  754. if (selected) {
  755. modifiers.disabled.push(function (day) {
  756. var isMaxSelected = max && selected.length > max - 1;
  757. var isSelected = selected.some(function (selectedDay) {
  758. return isSameDay(selectedDay, day);
  759. });
  760. return Boolean(isMaxSelected && !isSelected);
  761. });
  762. }
  763. var contextValue = {
  764. selected: selected,
  765. onDayClick: onDayClick,
  766. modifiers: modifiers
  767. };
  768. return (jsx(SelectMultipleContext.Provider, { value: contextValue, children: children }));
  769. }
  770. /**
  771. * Hook to access the {@link SelectMultipleContextValue}.
  772. *
  773. * This hook is meant to be used inside internal or custom components.
  774. */
  775. function useSelectMultiple() {
  776. var context = useContext(SelectMultipleContext);
  777. if (!context) {
  778. throw new Error('useSelectMultiple must be used within a SelectMultipleProvider');
  779. }
  780. return context;
  781. }
  782. /**
  783. * Add a day to an existing range.
  784. *
  785. * The returned range takes in account the `undefined` values and if the added
  786. * day is already present in the range.
  787. */
  788. function addToRange(day, range) {
  789. var _a = range || {}, from = _a.from, to = _a.to;
  790. if (from && to) {
  791. if (isSameDay(to, day) && isSameDay(from, day)) {
  792. return undefined;
  793. }
  794. if (isSameDay(to, day)) {
  795. return { from: to, to: undefined };
  796. }
  797. if (isSameDay(from, day)) {
  798. return undefined;
  799. }
  800. if (isAfter(from, day)) {
  801. return { from: day, to: to };
  802. }
  803. return { from: from, to: day };
  804. }
  805. if (to) {
  806. if (isAfter(day, to)) {
  807. return { from: to, to: day };
  808. }
  809. return { from: day, to: to };
  810. }
  811. if (from) {
  812. if (isBefore(day, from)) {
  813. return { from: day, to: from };
  814. }
  815. return { from: from, to: day };
  816. }
  817. return { from: day, to: undefined };
  818. }
  819. /**
  820. * The SelectRange context shares details about the selected days when in
  821. * range selection mode.
  822. *
  823. * Access this context from the {@link useSelectRange} hook.
  824. */
  825. var SelectRangeContext = createContext(undefined);
  826. /** Provides the values for the {@link SelectRangeProvider}. */
  827. function SelectRangeProvider(props) {
  828. if (!isDayPickerRange(props.initialProps)) {
  829. var emptyContextValue = {
  830. selected: undefined,
  831. modifiers: {
  832. range_start: [],
  833. range_end: [],
  834. range_middle: [],
  835. disabled: []
  836. }
  837. };
  838. return (jsx(SelectRangeContext.Provider, { value: emptyContextValue, children: props.children }));
  839. }
  840. return (jsx(SelectRangeProviderInternal, { initialProps: props.initialProps, children: props.children }));
  841. }
  842. function SelectRangeProviderInternal(_a) {
  843. var initialProps = _a.initialProps, children = _a.children;
  844. var selected = initialProps.selected;
  845. var _b = selected || {}, selectedFrom = _b.from, selectedTo = _b.to;
  846. var min = initialProps.min;
  847. var max = initialProps.max;
  848. var onDayClick = function (day, activeModifiers, e) {
  849. var _a, _b;
  850. (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);
  851. var newRange = addToRange(day, selected);
  852. (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, newRange, day, activeModifiers, e);
  853. };
  854. var modifiers = {
  855. range_start: [],
  856. range_end: [],
  857. range_middle: [],
  858. disabled: []
  859. };
  860. if (selectedFrom) {
  861. modifiers.range_start = [selectedFrom];
  862. if (!selectedTo) {
  863. modifiers.range_end = [selectedFrom];
  864. }
  865. else {
  866. modifiers.range_end = [selectedTo];
  867. if (!isSameDay(selectedFrom, selectedTo)) {
  868. modifiers.range_middle = [
  869. {
  870. after: selectedFrom,
  871. before: selectedTo
  872. }
  873. ];
  874. }
  875. }
  876. }
  877. else if (selectedTo) {
  878. modifiers.range_start = [selectedTo];
  879. modifiers.range_end = [selectedTo];
  880. }
  881. if (min) {
  882. if (selectedFrom && !selectedTo) {
  883. modifiers.disabled.push({
  884. after: subDays(selectedFrom, min - 1),
  885. before: addDays(selectedFrom, min - 1)
  886. });
  887. }
  888. if (selectedFrom && selectedTo) {
  889. modifiers.disabled.push({
  890. after: selectedFrom,
  891. before: addDays(selectedFrom, min - 1)
  892. });
  893. }
  894. if (!selectedFrom && selectedTo) {
  895. modifiers.disabled.push({
  896. after: subDays(selectedTo, min - 1),
  897. before: addDays(selectedTo, min - 1)
  898. });
  899. }
  900. }
  901. if (max) {
  902. if (selectedFrom && !selectedTo) {
  903. modifiers.disabled.push({
  904. before: addDays(selectedFrom, -max + 1)
  905. });
  906. modifiers.disabled.push({
  907. after: addDays(selectedFrom, max - 1)
  908. });
  909. }
  910. if (selectedFrom && selectedTo) {
  911. var selectedCount = differenceInCalendarDays(selectedTo, selectedFrom) + 1;
  912. var offset = max - selectedCount;
  913. modifiers.disabled.push({
  914. before: subDays(selectedFrom, offset)
  915. });
  916. modifiers.disabled.push({
  917. after: addDays(selectedTo, offset)
  918. });
  919. }
  920. if (!selectedFrom && selectedTo) {
  921. modifiers.disabled.push({
  922. before: addDays(selectedTo, -max + 1)
  923. });
  924. modifiers.disabled.push({
  925. after: addDays(selectedTo, max - 1)
  926. });
  927. }
  928. }
  929. return (jsx(SelectRangeContext.Provider, { value: { selected: selected, onDayClick: onDayClick, modifiers: modifiers }, children: children }));
  930. }
  931. /**
  932. * Hook to access the {@link SelectRangeContextValue}.
  933. *
  934. * This hook is meant to be used inside internal or custom components.
  935. */
  936. function useSelectRange() {
  937. var context = useContext(SelectRangeContext);
  938. if (!context) {
  939. throw new Error('useSelectRange must be used within a SelectRangeProvider');
  940. }
  941. return context;
  942. }
  943. /** Normalize to array a matcher input. */
  944. function matcherToArray(matcher) {
  945. if (Array.isArray(matcher)) {
  946. return __spreadArray([], matcher, true);
  947. }
  948. else if (matcher !== undefined) {
  949. return [matcher];
  950. }
  951. else {
  952. return [];
  953. }
  954. }
  955. /** Create CustomModifiers from dayModifiers */
  956. function getCustomModifiers(dayModifiers) {
  957. var customModifiers = {};
  958. Object.entries(dayModifiers).forEach(function (_a) {
  959. var modifier = _a[0], matcher = _a[1];
  960. customModifiers[modifier] = matcherToArray(matcher);
  961. });
  962. return customModifiers;
  963. }
  964. /** The name of the modifiers that are used internally by DayPicker. */
  965. var InternalModifier;
  966. (function (InternalModifier) {
  967. InternalModifier["Outside"] = "outside";
  968. /** Name of the modifier applied to the disabled days, using the `disabled` prop. */
  969. InternalModifier["Disabled"] = "disabled";
  970. /** Name of the modifier applied to the selected days using the `selected` prop). */
  971. InternalModifier["Selected"] = "selected";
  972. /** Name of the modifier applied to the hidden days using the `hidden` prop). */
  973. InternalModifier["Hidden"] = "hidden";
  974. /** Name of the modifier applied to the day specified using the `today` prop). */
  975. InternalModifier["Today"] = "today";
  976. /** The modifier applied to the day starting a selected range, when in range selection mode. */
  977. InternalModifier["RangeStart"] = "range_start";
  978. /** The modifier applied to the day ending a selected range, when in range selection mode. */
  979. InternalModifier["RangeEnd"] = "range_end";
  980. /** The modifier applied to the days between the start and the end of a selected range, when in range selection mode. */
  981. InternalModifier["RangeMiddle"] = "range_middle";
  982. })(InternalModifier || (InternalModifier = {}));
  983. var Selected = InternalModifier.Selected, Disabled = InternalModifier.Disabled, Hidden = InternalModifier.Hidden, Today = InternalModifier.Today, RangeEnd = InternalModifier.RangeEnd, RangeMiddle = InternalModifier.RangeMiddle, RangeStart = InternalModifier.RangeStart, Outside = InternalModifier.Outside;
  984. /** Return the {@link InternalModifiers} from the DayPicker and select contexts. */
  985. function getInternalModifiers(dayPicker, selectMultiple, selectRange) {
  986. var _a;
  987. var internalModifiers = (_a = {},
  988. _a[Selected] = matcherToArray(dayPicker.selected),
  989. _a[Disabled] = matcherToArray(dayPicker.disabled),
  990. _a[Hidden] = matcherToArray(dayPicker.hidden),
  991. _a[Today] = [dayPicker.today],
  992. _a[RangeEnd] = [],
  993. _a[RangeMiddle] = [],
  994. _a[RangeStart] = [],
  995. _a[Outside] = [],
  996. _a);
  997. if (dayPicker.fromDate) {
  998. internalModifiers[Disabled].push({ before: dayPicker.fromDate });
  999. }
  1000. if (dayPicker.toDate) {
  1001. internalModifiers[Disabled].push({ after: dayPicker.toDate });
  1002. }
  1003. if (isDayPickerMultiple(dayPicker)) {
  1004. internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectMultiple.modifiers[Disabled]);
  1005. }
  1006. else if (isDayPickerRange(dayPicker)) {
  1007. internalModifiers[Disabled] = internalModifiers[Disabled].concat(selectRange.modifiers[Disabled]);
  1008. internalModifiers[RangeStart] = selectRange.modifiers[RangeStart];
  1009. internalModifiers[RangeMiddle] = selectRange.modifiers[RangeMiddle];
  1010. internalModifiers[RangeEnd] = selectRange.modifiers[RangeEnd];
  1011. }
  1012. return internalModifiers;
  1013. }
  1014. /** The Modifiers context store the modifiers used in DayPicker. To access the value of this context, use {@link useModifiers}. */
  1015. var ModifiersContext = createContext(undefined);
  1016. /** Provide the value for the {@link ModifiersContext}. */
  1017. function ModifiersProvider(props) {
  1018. var dayPicker = useDayPicker();
  1019. var selectMultiple = useSelectMultiple();
  1020. var selectRange = useSelectRange();
  1021. var internalModifiers = getInternalModifiers(dayPicker, selectMultiple, selectRange);
  1022. var customModifiers = getCustomModifiers(dayPicker.modifiers);
  1023. var modifiers = __assign(__assign({}, internalModifiers), customModifiers);
  1024. return (jsx(ModifiersContext.Provider, { value: modifiers, children: props.children }));
  1025. }
  1026. /**
  1027. * Return the modifiers used by DayPicker.
  1028. *
  1029. * This hook is meant to be used inside internal or custom components.
  1030. * Requires to be wrapped into {@link ModifiersProvider}.
  1031. *
  1032. */
  1033. function useModifiers() {
  1034. var context = useContext(ModifiersContext);
  1035. if (!context) {
  1036. throw new Error('useModifiers must be used within a ModifiersProvider');
  1037. }
  1038. return context;
  1039. }
  1040. /** Returns true if `matcher` is of type {@link DateInterval}. */
  1041. function isDateInterval(matcher) {
  1042. return Boolean(matcher &&
  1043. typeof matcher === 'object' &&
  1044. 'before' in matcher &&
  1045. 'after' in matcher);
  1046. }
  1047. /** Returns true if `value` is a {@link DateRange} type. */
  1048. function isDateRange(value) {
  1049. return Boolean(value && typeof value === 'object' && 'from' in value);
  1050. }
  1051. /** Returns true if `value` is of type {@link DateAfter}. */
  1052. function isDateAfterType(value) {
  1053. return Boolean(value && typeof value === 'object' && 'after' in value);
  1054. }
  1055. /** Returns true if `value` is of type {@link DateBefore}. */
  1056. function isDateBeforeType(value) {
  1057. return Boolean(value && typeof value === 'object' && 'before' in value);
  1058. }
  1059. /** Returns true if `value` is a {@link DayOfWeek} type. */
  1060. function isDayOfWeekType(value) {
  1061. return Boolean(value && typeof value === 'object' && 'dayOfWeek' in value);
  1062. }
  1063. /** Return `true` whether `date` is inside `range`. */
  1064. function isDateInRange(date, range) {
  1065. var _a;
  1066. var from = range.from, to = range.to;
  1067. if (from && to) {
  1068. var isRangeInverted = differenceInCalendarDays(to, from) < 0;
  1069. if (isRangeInverted) {
  1070. _a = [to, from], from = _a[0], to = _a[1];
  1071. }
  1072. var isInRange = differenceInCalendarDays(date, from) >= 0 &&
  1073. differenceInCalendarDays(to, date) >= 0;
  1074. return isInRange;
  1075. }
  1076. if (to) {
  1077. return isSameDay(to, date);
  1078. }
  1079. if (from) {
  1080. return isSameDay(from, date);
  1081. }
  1082. return false;
  1083. }
  1084. /** Returns true if `value` is a Date type. */
  1085. function isDateType(value) {
  1086. return isDate(value);
  1087. }
  1088. /** Returns true if `value` is an array of valid dates. */
  1089. function isArrayOfDates(value) {
  1090. return Array.isArray(value) && value.every(isDate);
  1091. }
  1092. /**
  1093. * Returns whether a day matches against at least one of the given Matchers.
  1094. *
  1095. * ```
  1096. * const day = new Date(2022, 5, 19);
  1097. * const matcher1: DateRange = {
  1098. * from: new Date(2021, 12, 21),
  1099. * to: new Date(2021, 12, 30)
  1100. * }
  1101. * const matcher2: DateRange = {
  1102. * from: new Date(2022, 5, 1),
  1103. * to: new Date(2022, 5, 23)
  1104. * }
  1105. *
  1106. * const isMatch(day, [matcher1, matcher2]); // true, since day is in the matcher1 range.
  1107. * ```
  1108. * */
  1109. function isMatch(day, matchers) {
  1110. return matchers.some(function (matcher) {
  1111. if (typeof matcher === 'boolean') {
  1112. return matcher;
  1113. }
  1114. if (isDateType(matcher)) {
  1115. return isSameDay(day, matcher);
  1116. }
  1117. if (isArrayOfDates(matcher)) {
  1118. return matcher.includes(day);
  1119. }
  1120. if (isDateRange(matcher)) {
  1121. return isDateInRange(day, matcher);
  1122. }
  1123. if (isDayOfWeekType(matcher)) {
  1124. return matcher.dayOfWeek.includes(day.getDay());
  1125. }
  1126. if (isDateInterval(matcher)) {
  1127. var diffBefore = differenceInCalendarDays(matcher.before, day);
  1128. var diffAfter = differenceInCalendarDays(matcher.after, day);
  1129. var isDayBefore = diffBefore > 0;
  1130. var isDayAfter = diffAfter < 0;
  1131. var isClosedInterval = isAfter(matcher.before, matcher.after);
  1132. if (isClosedInterval) {
  1133. return isDayAfter && isDayBefore;
  1134. }
  1135. else {
  1136. return isDayBefore || isDayAfter;
  1137. }
  1138. }
  1139. if (isDateAfterType(matcher)) {
  1140. return differenceInCalendarDays(day, matcher.after) > 0;
  1141. }
  1142. if (isDateBeforeType(matcher)) {
  1143. return differenceInCalendarDays(matcher.before, day) > 0;
  1144. }
  1145. if (typeof matcher === 'function') {
  1146. return matcher(day);
  1147. }
  1148. return false;
  1149. });
  1150. }
  1151. /** Return the active modifiers for the given day. */
  1152. function getActiveModifiers(day,
  1153. /** The modifiers to match for the given date. */
  1154. modifiers,
  1155. /** The month where the day is displayed, to add the "outside" modifiers. */
  1156. displayMonth) {
  1157. var matchedModifiers = Object.keys(modifiers).reduce(function (result, key) {
  1158. var modifier = modifiers[key];
  1159. if (isMatch(day, modifier)) {
  1160. result.push(key);
  1161. }
  1162. return result;
  1163. }, []);
  1164. var activeModifiers = {};
  1165. matchedModifiers.forEach(function (modifier) { return (activeModifiers[modifier] = true); });
  1166. if (displayMonth && !isSameMonth(day, displayMonth)) {
  1167. activeModifiers.outside = true;
  1168. }
  1169. return activeModifiers;
  1170. }
  1171. /**
  1172. * Returns the day that should be the target of the focus when DayPicker is
  1173. * rendered the first time.
  1174. *
  1175. * TODO: this function doesn't consider if the day is outside the month. We
  1176. * implemented this check in `useDayRender` but it should probably go here. See
  1177. * https://github.com/gpbl/react-day-picker/pull/1576
  1178. */
  1179. function getInitialFocusTarget(displayMonths, modifiers) {
  1180. var firstDayInMonth = startOfMonth(displayMonths[0]);
  1181. var lastDayInMonth = endOfMonth(displayMonths[displayMonths.length - 1]);
  1182. // TODO: cleanup code
  1183. var firstFocusableDay;
  1184. var today;
  1185. var date = firstDayInMonth;
  1186. while (date <= lastDayInMonth) {
  1187. var activeModifiers = getActiveModifiers(date, modifiers);
  1188. var isFocusable = !activeModifiers.disabled && !activeModifiers.hidden;
  1189. if (!isFocusable) {
  1190. date = addDays(date, 1);
  1191. continue;
  1192. }
  1193. if (activeModifiers.selected) {
  1194. return date;
  1195. }
  1196. if (activeModifiers.today && !today) {
  1197. today = date;
  1198. }
  1199. if (!firstFocusableDay) {
  1200. firstFocusableDay = date;
  1201. }
  1202. date = addDays(date, 1);
  1203. }
  1204. if (today) {
  1205. return today;
  1206. }
  1207. else {
  1208. return firstFocusableDay;
  1209. }
  1210. }
  1211. var MAX_RETRY = 365;
  1212. /** Return the next date to be focused. */
  1213. function getNextFocus(focusedDay, options) {
  1214. var moveBy = options.moveBy, direction = options.direction, context = options.context, modifiers = options.modifiers, _a = options.retry, retry = _a === void 0 ? { count: 0, lastFocused: focusedDay } : _a;
  1215. var weekStartsOn = context.weekStartsOn, fromDate = context.fromDate, toDate = context.toDate, locale = context.locale;
  1216. var moveFns = {
  1217. day: addDays,
  1218. week: addWeeks,
  1219. month: addMonths,
  1220. year: addYears,
  1221. startOfWeek: function (date) {
  1222. return context.ISOWeek
  1223. ? startOfISOWeek(date)
  1224. : startOfWeek(date, { locale: locale, weekStartsOn: weekStartsOn });
  1225. },
  1226. endOfWeek: function (date) {
  1227. return context.ISOWeek
  1228. ? endOfISOWeek(date)
  1229. : endOfWeek(date, { locale: locale, weekStartsOn: weekStartsOn });
  1230. }
  1231. };
  1232. var newFocusedDay = moveFns[moveBy](focusedDay, direction === 'after' ? 1 : -1);
  1233. if (direction === 'before' && fromDate) {
  1234. newFocusedDay = max([fromDate, newFocusedDay]);
  1235. }
  1236. else if (direction === 'after' && toDate) {
  1237. newFocusedDay = min([toDate, newFocusedDay]);
  1238. }
  1239. var isFocusable = true;
  1240. if (modifiers) {
  1241. var activeModifiers = getActiveModifiers(newFocusedDay, modifiers);
  1242. isFocusable = !activeModifiers.disabled && !activeModifiers.hidden;
  1243. }
  1244. if (isFocusable) {
  1245. return newFocusedDay;
  1246. }
  1247. else {
  1248. if (retry.count > MAX_RETRY) {
  1249. return retry.lastFocused;
  1250. }
  1251. return getNextFocus(newFocusedDay, {
  1252. moveBy: moveBy,
  1253. direction: direction,
  1254. context: context,
  1255. modifiers: modifiers,
  1256. retry: __assign(__assign({}, retry), { count: retry.count + 1 })
  1257. });
  1258. }
  1259. }
  1260. /**
  1261. * The Focus context shares details about the focused day for the keyboard
  1262. *
  1263. * Access this context from the {@link useFocusContext} hook.
  1264. */
  1265. var FocusContext = createContext(undefined);
  1266. /** The provider for the {@link FocusContext}. */
  1267. function FocusProvider(props) {
  1268. var navigation = useNavigation();
  1269. var modifiers = useModifiers();
  1270. var _a = useState(), focusedDay = _a[0], setFocusedDay = _a[1];
  1271. var _b = useState(), lastFocused = _b[0], setLastFocused = _b[1];
  1272. var initialFocusTarget = getInitialFocusTarget(navigation.displayMonths, modifiers);
  1273. // TODO: cleanup and test obscure code below
  1274. var focusTarget = (focusedDay !== null && focusedDay !== void 0 ? focusedDay : (lastFocused && navigation.isDateDisplayed(lastFocused)))
  1275. ? lastFocused
  1276. : initialFocusTarget;
  1277. var blur = function () {
  1278. setLastFocused(focusedDay);
  1279. setFocusedDay(undefined);
  1280. };
  1281. var focus = function (date) {
  1282. setFocusedDay(date);
  1283. };
  1284. var context = useDayPicker();
  1285. var moveFocus = function (moveBy, direction) {
  1286. if (!focusedDay)
  1287. return;
  1288. var nextFocused = getNextFocus(focusedDay, {
  1289. moveBy: moveBy,
  1290. direction: direction,
  1291. context: context,
  1292. modifiers: modifiers
  1293. });
  1294. if (isSameDay(focusedDay, nextFocused))
  1295. return undefined;
  1296. navigation.goToDate(nextFocused, focusedDay);
  1297. focus(nextFocused);
  1298. };
  1299. var value = {
  1300. focusedDay: focusedDay,
  1301. focusTarget: focusTarget,
  1302. blur: blur,
  1303. focus: focus,
  1304. focusDayAfter: function () { return moveFocus('day', 'after'); },
  1305. focusDayBefore: function () { return moveFocus('day', 'before'); },
  1306. focusWeekAfter: function () { return moveFocus('week', 'after'); },
  1307. focusWeekBefore: function () { return moveFocus('week', 'before'); },
  1308. focusMonthBefore: function () { return moveFocus('month', 'before'); },
  1309. focusMonthAfter: function () { return moveFocus('month', 'after'); },
  1310. focusYearBefore: function () { return moveFocus('year', 'before'); },
  1311. focusYearAfter: function () { return moveFocus('year', 'after'); },
  1312. focusStartOfWeek: function () { return moveFocus('startOfWeek', 'before'); },
  1313. focusEndOfWeek: function () { return moveFocus('endOfWeek', 'after'); }
  1314. };
  1315. return (jsx(FocusContext.Provider, { value: value, children: props.children }));
  1316. }
  1317. /**
  1318. * Hook to access the {@link FocusContextValue}. Use this hook to handle the
  1319. * focus state of the elements.
  1320. *
  1321. * This hook is meant to be used inside internal or custom components.
  1322. */
  1323. function useFocusContext() {
  1324. var context = useContext(FocusContext);
  1325. if (!context) {
  1326. throw new Error('useFocusContext must be used within a FocusProvider');
  1327. }
  1328. return context;
  1329. }
  1330. /**
  1331. * Return the active modifiers for the specified day.
  1332. *
  1333. * This hook is meant to be used inside internal or custom components.
  1334. *
  1335. * @param day
  1336. * @param displayMonth
  1337. */
  1338. function useActiveModifiers(day,
  1339. /**
  1340. * The month where the date is displayed. If not the same as `date`, the day
  1341. * is an "outside day".
  1342. */
  1343. displayMonth) {
  1344. var modifiers = useModifiers();
  1345. var activeModifiers = getActiveModifiers(day, modifiers, displayMonth);
  1346. return activeModifiers;
  1347. }
  1348. /**
  1349. * The SelectSingle context shares details about the selected days when in
  1350. * single selection mode.
  1351. *
  1352. * Access this context from the {@link useSelectSingle} hook.
  1353. */
  1354. var SelectSingleContext = createContext(undefined);
  1355. /** Provides the values for the {@link SelectSingleProvider}. */
  1356. function SelectSingleProvider(props) {
  1357. if (!isDayPickerSingle(props.initialProps)) {
  1358. var emptyContextValue = {
  1359. selected: undefined
  1360. };
  1361. return (jsx(SelectSingleContext.Provider, { value: emptyContextValue, children: props.children }));
  1362. }
  1363. return (jsx(SelectSingleProviderInternal, { initialProps: props.initialProps, children: props.children }));
  1364. }
  1365. function SelectSingleProviderInternal(_a) {
  1366. var initialProps = _a.initialProps, children = _a.children;
  1367. var onDayClick = function (day, activeModifiers, e) {
  1368. var _a, _b, _c;
  1369. (_a = initialProps.onDayClick) === null || _a === void 0 ? void 0 : _a.call(initialProps, day, activeModifiers, e);
  1370. if (activeModifiers.selected && !initialProps.required) {
  1371. (_b = initialProps.onSelect) === null || _b === void 0 ? void 0 : _b.call(initialProps, undefined, day, activeModifiers, e);
  1372. return;
  1373. }
  1374. (_c = initialProps.onSelect) === null || _c === void 0 ? void 0 : _c.call(initialProps, day, day, activeModifiers, e);
  1375. };
  1376. var contextValue = {
  1377. selected: initialProps.selected,
  1378. onDayClick: onDayClick
  1379. };
  1380. return (jsx(SelectSingleContext.Provider, { value: contextValue, children: children }));
  1381. }
  1382. /**
  1383. * Hook to access the {@link SelectSingleContextValue}.
  1384. *
  1385. * This hook is meant to be used inside internal or custom components.
  1386. */
  1387. function useSelectSingle() {
  1388. var context = useContext(SelectSingleContext);
  1389. if (!context) {
  1390. throw new Error('useSelectSingle must be used within a SelectSingleProvider');
  1391. }
  1392. return context;
  1393. }
  1394. /**
  1395. * This hook returns details about the content to render in the day cell.
  1396. *
  1397. *
  1398. * When a day cell is rendered in the table, DayPicker can either:
  1399. *
  1400. * - render nothing: when the day is outside the month or has matched the
  1401. * "hidden" modifier.
  1402. * - render a button when `onDayClick` or a selection mode is set.
  1403. * - render a non-interactive element: when no selection mode is set, the day
  1404. * cell shouldn’t respond to any interaction. DayPicker should render a `div`
  1405. * or a `span`.
  1406. *
  1407. * ### Usage
  1408. *
  1409. * Use this hook to customize the behavior of the {@link Day} component. Create a
  1410. * new `Day` component using this hook and pass it to the `components` prop.
  1411. * The source of {@link Day} can be a good starting point.
  1412. *
  1413. */
  1414. function useDayEventHandlers(date, activeModifiers) {
  1415. var dayPicker = useDayPicker();
  1416. var single = useSelectSingle();
  1417. var multiple = useSelectMultiple();
  1418. var range = useSelectRange();
  1419. var _a = useFocusContext(), focusDayAfter = _a.focusDayAfter, focusDayBefore = _a.focusDayBefore, focusWeekAfter = _a.focusWeekAfter, focusWeekBefore = _a.focusWeekBefore, blur = _a.blur, focus = _a.focus, focusMonthBefore = _a.focusMonthBefore, focusMonthAfter = _a.focusMonthAfter, focusYearBefore = _a.focusYearBefore, focusYearAfter = _a.focusYearAfter, focusStartOfWeek = _a.focusStartOfWeek, focusEndOfWeek = _a.focusEndOfWeek;
  1420. var onClick = function (e) {
  1421. var _a, _b, _c, _d;
  1422. if (isDayPickerSingle(dayPicker)) {
  1423. (_a = single.onDayClick) === null || _a === void 0 ? void 0 : _a.call(single, date, activeModifiers, e);
  1424. }
  1425. else if (isDayPickerMultiple(dayPicker)) {
  1426. (_b = multiple.onDayClick) === null || _b === void 0 ? void 0 : _b.call(multiple, date, activeModifiers, e);
  1427. }
  1428. else if (isDayPickerRange(dayPicker)) {
  1429. (_c = range.onDayClick) === null || _c === void 0 ? void 0 : _c.call(range, date, activeModifiers, e);
  1430. }
  1431. else {
  1432. (_d = dayPicker.onDayClick) === null || _d === void 0 ? void 0 : _d.call(dayPicker, date, activeModifiers, e);
  1433. }
  1434. };
  1435. var onFocus = function (e) {
  1436. var _a;
  1437. focus(date);
  1438. (_a = dayPicker.onDayFocus) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1439. };
  1440. var onBlur = function (e) {
  1441. var _a;
  1442. blur();
  1443. (_a = dayPicker.onDayBlur) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1444. };
  1445. var onMouseEnter = function (e) {
  1446. var _a;
  1447. (_a = dayPicker.onDayMouseEnter) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1448. };
  1449. var onMouseLeave = function (e) {
  1450. var _a;
  1451. (_a = dayPicker.onDayMouseLeave) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1452. };
  1453. var onPointerEnter = function (e) {
  1454. var _a;
  1455. (_a = dayPicker.onDayPointerEnter) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1456. };
  1457. var onPointerLeave = function (e) {
  1458. var _a;
  1459. (_a = dayPicker.onDayPointerLeave) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1460. };
  1461. var onTouchCancel = function (e) {
  1462. var _a;
  1463. (_a = dayPicker.onDayTouchCancel) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1464. };
  1465. var onTouchEnd = function (e) {
  1466. var _a;
  1467. (_a = dayPicker.onDayTouchEnd) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1468. };
  1469. var onTouchMove = function (e) {
  1470. var _a;
  1471. (_a = dayPicker.onDayTouchMove) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1472. };
  1473. var onTouchStart = function (e) {
  1474. var _a;
  1475. (_a = dayPicker.onDayTouchStart) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1476. };
  1477. var onKeyUp = function (e) {
  1478. var _a;
  1479. (_a = dayPicker.onDayKeyUp) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1480. };
  1481. var onKeyDown = function (e) {
  1482. var _a;
  1483. switch (e.key) {
  1484. case 'ArrowLeft':
  1485. e.preventDefault();
  1486. e.stopPropagation();
  1487. dayPicker.dir === 'rtl' ? focusDayAfter() : focusDayBefore();
  1488. break;
  1489. case 'ArrowRight':
  1490. e.preventDefault();
  1491. e.stopPropagation();
  1492. dayPicker.dir === 'rtl' ? focusDayBefore() : focusDayAfter();
  1493. break;
  1494. case 'ArrowDown':
  1495. e.preventDefault();
  1496. e.stopPropagation();
  1497. focusWeekAfter();
  1498. break;
  1499. case 'ArrowUp':
  1500. e.preventDefault();
  1501. e.stopPropagation();
  1502. focusWeekBefore();
  1503. break;
  1504. case 'PageUp':
  1505. e.preventDefault();
  1506. e.stopPropagation();
  1507. e.shiftKey ? focusYearBefore() : focusMonthBefore();
  1508. break;
  1509. case 'PageDown':
  1510. e.preventDefault();
  1511. e.stopPropagation();
  1512. e.shiftKey ? focusYearAfter() : focusMonthAfter();
  1513. break;
  1514. case 'Home':
  1515. e.preventDefault();
  1516. e.stopPropagation();
  1517. focusStartOfWeek();
  1518. break;
  1519. case 'End':
  1520. e.preventDefault();
  1521. e.stopPropagation();
  1522. focusEndOfWeek();
  1523. break;
  1524. }
  1525. (_a = dayPicker.onDayKeyDown) === null || _a === void 0 ? void 0 : _a.call(dayPicker, date, activeModifiers, e);
  1526. };
  1527. var eventHandlers = {
  1528. onClick: onClick,
  1529. onFocus: onFocus,
  1530. onBlur: onBlur,
  1531. onKeyDown: onKeyDown,
  1532. onKeyUp: onKeyUp,
  1533. onMouseEnter: onMouseEnter,
  1534. onMouseLeave: onMouseLeave,
  1535. onPointerEnter: onPointerEnter,
  1536. onPointerLeave: onPointerLeave,
  1537. onTouchCancel: onTouchCancel,
  1538. onTouchEnd: onTouchEnd,
  1539. onTouchMove: onTouchMove,
  1540. onTouchStart: onTouchStart
  1541. };
  1542. return eventHandlers;
  1543. }
  1544. /**
  1545. * Return the current selected days when DayPicker is in selection mode. Days
  1546. * selected by the custom selection mode are not returned.
  1547. *
  1548. * This hook is meant to be used inside internal or custom components.
  1549. *
  1550. */
  1551. function useSelectedDays() {
  1552. var dayPicker = useDayPicker();
  1553. var single = useSelectSingle();
  1554. var multiple = useSelectMultiple();
  1555. var range = useSelectRange();
  1556. var selectedDays = isDayPickerSingle(dayPicker)
  1557. ? single.selected
  1558. : isDayPickerMultiple(dayPicker)
  1559. ? multiple.selected
  1560. : isDayPickerRange(dayPicker)
  1561. ? range.selected
  1562. : undefined;
  1563. return selectedDays;
  1564. }
  1565. function isInternalModifier(modifier) {
  1566. return Object.values(InternalModifier).includes(modifier);
  1567. }
  1568. /**
  1569. * Return the class names for the Day element, according to the given active
  1570. * modifiers.
  1571. *
  1572. * Custom class names are set via `modifiersClassNames` or `classNames`,
  1573. * where the first have the precedence.
  1574. */
  1575. function getDayClassNames(dayPicker, activeModifiers) {
  1576. var classNames = [dayPicker.classNames.day];
  1577. Object.keys(activeModifiers).forEach(function (modifier) {
  1578. var customClassName = dayPicker.modifiersClassNames[modifier];
  1579. if (customClassName) {
  1580. classNames.push(customClassName);
  1581. }
  1582. else if (isInternalModifier(modifier)) {
  1583. var internalClassName = dayPicker.classNames["day_".concat(modifier)];
  1584. if (internalClassName) {
  1585. classNames.push(internalClassName);
  1586. }
  1587. }
  1588. });
  1589. return classNames;
  1590. }
  1591. /** Return the style for the Day element, according to the given active modifiers. */
  1592. function getDayStyle(dayPicker, activeModifiers) {
  1593. var style = __assign({}, dayPicker.styles.day);
  1594. Object.keys(activeModifiers).forEach(function (modifier) {
  1595. var _a;
  1596. style = __assign(__assign({}, style), (_a = dayPicker.modifiersStyles) === null || _a === void 0 ? void 0 : _a[modifier]);
  1597. });
  1598. return style;
  1599. }
  1600. /**
  1601. * Return props and data used to render the {@link Day} component.
  1602. *
  1603. * Use this hook when creating a component to replace the built-in `Day`
  1604. * component.
  1605. */
  1606. function useDayRender(
  1607. /** The date to render. */
  1608. day,
  1609. /** The month where the date is displayed (if not the same as `date`, it means it is an "outside" day). */
  1610. displayMonth,
  1611. /** A ref to the button element that will be target of focus when rendered (if required). */
  1612. buttonRef) {
  1613. var _a;
  1614. var _b, _c;
  1615. var dayPicker = useDayPicker();
  1616. var focusContext = useFocusContext();
  1617. var activeModifiers = useActiveModifiers(day, displayMonth);
  1618. var eventHandlers = useDayEventHandlers(day, activeModifiers);
  1619. var selectedDays = useSelectedDays();
  1620. var isButton = Boolean(dayPicker.onDayClick || dayPicker.mode !== 'default');
  1621. // Focus the button if the day is focused according to the focus context
  1622. useEffect(function () {
  1623. var _a;
  1624. if (activeModifiers.outside)
  1625. return;
  1626. if (!focusContext.focusedDay)
  1627. return;
  1628. if (!isButton)
  1629. return;
  1630. if (isSameDay(focusContext.focusedDay, day)) {
  1631. (_a = buttonRef.current) === null || _a === void 0 ? void 0 : _a.focus();
  1632. }
  1633. }, [
  1634. focusContext.focusedDay,
  1635. day,
  1636. buttonRef,
  1637. isButton,
  1638. activeModifiers.outside
  1639. ]);
  1640. var className = getDayClassNames(dayPicker, activeModifiers).join(' ');
  1641. var style = getDayStyle(dayPicker, activeModifiers);
  1642. var isHidden = Boolean((activeModifiers.outside && !dayPicker.showOutsideDays) ||
  1643. activeModifiers.hidden);
  1644. var DayContentComponent = (_c = (_b = dayPicker.components) === null || _b === void 0 ? void 0 : _b.DayContent) !== null && _c !== void 0 ? _c : DayContent;
  1645. var children = (jsx(DayContentComponent, { date: day, displayMonth: displayMonth, activeModifiers: activeModifiers }));
  1646. var divProps = {
  1647. style: style,
  1648. className: className,
  1649. children: children,
  1650. role: 'gridcell'
  1651. };
  1652. var isFocusTarget = focusContext.focusTarget &&
  1653. isSameDay(focusContext.focusTarget, day) &&
  1654. !activeModifiers.outside;
  1655. var isFocused = focusContext.focusedDay && isSameDay(focusContext.focusedDay, day);
  1656. var buttonProps = __assign(__assign(__assign({}, divProps), (_a = { disabled: activeModifiers.disabled, role: 'gridcell' }, _a['aria-selected'] = activeModifiers.selected, _a.tabIndex = isFocused || isFocusTarget ? 0 : -1, _a)), eventHandlers);
  1657. var dayRender = {
  1658. isButton: isButton,
  1659. isHidden: isHidden,
  1660. activeModifiers: activeModifiers,
  1661. selectedDays: selectedDays,
  1662. buttonProps: buttonProps,
  1663. divProps: divProps
  1664. };
  1665. return dayRender;
  1666. }
  1667. /**
  1668. * The content of a day cell – as a button or span element according to its
  1669. * modifiers.
  1670. */
  1671. function Day(props) {
  1672. var buttonRef = useRef(null);
  1673. var dayRender = useDayRender(props.date, props.displayMonth, buttonRef);
  1674. if (dayRender.isHidden) {
  1675. return jsx("div", { role: "gridcell" });
  1676. }
  1677. if (!dayRender.isButton) {
  1678. return jsx("div", __assign({}, dayRender.divProps));
  1679. }
  1680. return jsx(Button, __assign({ name: "day", ref: buttonRef }, dayRender.buttonProps));
  1681. }
  1682. /**
  1683. * Render the week number element. If `onWeekNumberClick` is passed to DayPicker, it
  1684. * renders a button, otherwise a span element.
  1685. */
  1686. function WeekNumber(props) {
  1687. var weekNumber = props.number, dates = props.dates;
  1688. var _a = useDayPicker(), onWeekNumberClick = _a.onWeekNumberClick, styles = _a.styles, classNames = _a.classNames, locale = _a.locale, labelWeekNumber = _a.labels.labelWeekNumber, formatWeekNumber = _a.formatters.formatWeekNumber;
  1689. var content = formatWeekNumber(Number(weekNumber), { locale: locale });
  1690. if (!onWeekNumberClick) {
  1691. return (jsx("span", { className: classNames.weeknumber, style: styles.weeknumber, children: content }));
  1692. }
  1693. var label = labelWeekNumber(Number(weekNumber), { locale: locale });
  1694. var handleClick = function (e) {
  1695. onWeekNumberClick(weekNumber, dates, e);
  1696. };
  1697. return (jsx(Button, { name: "week-number", "aria-label": label, className: classNames.weeknumber, style: styles.weeknumber, onClick: handleClick, children: content }));
  1698. }
  1699. /** Render a row in the calendar, with the days and the week number. */
  1700. function Row(props) {
  1701. var _a, _b;
  1702. var _c = useDayPicker(), styles = _c.styles, classNames = _c.classNames, showWeekNumber = _c.showWeekNumber, components = _c.components;
  1703. var DayComponent = (_a = components === null || components === void 0 ? void 0 : components.Day) !== null && _a !== void 0 ? _a : Day;
  1704. var WeeknumberComponent = (_b = components === null || components === void 0 ? void 0 : components.WeekNumber) !== null && _b !== void 0 ? _b : WeekNumber;
  1705. var weekNumberCell;
  1706. if (showWeekNumber) {
  1707. weekNumberCell = (jsx("td", { className: classNames.cell, style: styles.cell, children: jsx(WeeknumberComponent, { number: props.weekNumber, dates: props.dates }) }));
  1708. }
  1709. return (jsxs("tr", { className: classNames.row, style: styles.row, children: [weekNumberCell, props.dates.map(function (date) { return (jsx("td", { className: classNames.cell, style: styles.cell, role: "presentation", children: jsx(DayComponent, { displayMonth: props.displayMonth, date: date }) }, getUnixTime(date))); })] }));
  1710. }
  1711. /** Return the weeks between two dates. */
  1712. function daysToMonthWeeks(fromDate, toDate, options) {
  1713. var toWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek)
  1714. ? endOfISOWeek(toDate)
  1715. : endOfWeek(toDate, options);
  1716. var fromWeek = (options === null || options === void 0 ? void 0 : options.ISOWeek)
  1717. ? startOfISOWeek(fromDate)
  1718. : startOfWeek(fromDate, options);
  1719. var nOfDays = differenceInCalendarDays(toWeek, fromWeek);
  1720. var days = [];
  1721. for (var i = 0; i <= nOfDays; i++) {
  1722. days.push(addDays(fromWeek, i));
  1723. }
  1724. var weeksInMonth = days.reduce(function (result, date) {
  1725. var weekNumber = (options === null || options === void 0 ? void 0 : options.ISOWeek)
  1726. ? getISOWeek(date)
  1727. : getWeek(date, options);
  1728. var existingWeek = result.find(function (value) { return value.weekNumber === weekNumber; });
  1729. if (existingWeek) {
  1730. existingWeek.dates.push(date);
  1731. return result;
  1732. }
  1733. result.push({
  1734. weekNumber: weekNumber,
  1735. dates: [date]
  1736. });
  1737. return result;
  1738. }, []);
  1739. return weeksInMonth;
  1740. }
  1741. /**
  1742. * Return the weeks belonging to the given month, adding the "outside days" to
  1743. * the first and last week.
  1744. */
  1745. function getMonthWeeks(month, options) {
  1746. var weeksInMonth = daysToMonthWeeks(startOfMonth(month), endOfMonth(month), options);
  1747. if (options === null || options === void 0 ? void 0 : options.useFixedWeeks) {
  1748. // Add extra weeks to the month, up to 6 weeks
  1749. var nrOfMonthWeeks = getWeeksInMonth(month, options);
  1750. if (nrOfMonthWeeks < 6) {
  1751. var lastWeek = weeksInMonth[weeksInMonth.length - 1];
  1752. var lastDate = lastWeek.dates[lastWeek.dates.length - 1];
  1753. var toDate = addWeeks(lastDate, 6 - nrOfMonthWeeks);
  1754. var extraWeeks = daysToMonthWeeks(addWeeks(lastDate, 1), toDate, options);
  1755. weeksInMonth.push.apply(weeksInMonth, extraWeeks);
  1756. }
  1757. }
  1758. return weeksInMonth;
  1759. }
  1760. /** Render the table with the calendar. */
  1761. function Table(props) {
  1762. var _a, _b, _c;
  1763. var _d = useDayPicker(), locale = _d.locale, classNames = _d.classNames, styles = _d.styles, hideHead = _d.hideHead, fixedWeeks = _d.fixedWeeks, components = _d.components, weekStartsOn = _d.weekStartsOn, firstWeekContainsDate = _d.firstWeekContainsDate, ISOWeek = _d.ISOWeek;
  1764. var weeks = getMonthWeeks(props.displayMonth, {
  1765. useFixedWeeks: Boolean(fixedWeeks),
  1766. ISOWeek: ISOWeek,
  1767. locale: locale,
  1768. weekStartsOn: weekStartsOn,
  1769. firstWeekContainsDate: firstWeekContainsDate
  1770. });
  1771. var HeadComponent = (_a = components === null || components === void 0 ? void 0 : components.Head) !== null && _a !== void 0 ? _a : Head;
  1772. var RowComponent = (_b = components === null || components === void 0 ? void 0 : components.Row) !== null && _b !== void 0 ? _b : Row;
  1773. var FooterComponent = (_c = components === null || components === void 0 ? void 0 : components.Footer) !== null && _c !== void 0 ? _c : Footer;
  1774. return (jsxs("table", { id: props.id, className: classNames.table, style: styles.table, role: "grid", "aria-labelledby": props['aria-labelledby'], children: [!hideHead && jsx(HeadComponent, {}), jsx("tbody", { className: classNames.tbody, style: styles.tbody, children: weeks.map(function (week) { return (jsx(RowComponent, { displayMonth: props.displayMonth, dates: week.dates, weekNumber: week.weekNumber }, week.weekNumber)); }) }), jsx(FooterComponent, { displayMonth: props.displayMonth })] }));
  1775. }
  1776. /*
  1777. The MIT License (MIT)
  1778. Copyright (c) 2018-present, React Training LLC
  1779. 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:
  1780. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  1781. 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.
  1782. */
  1783. /* eslint-disable prefer-const */
  1784. /* eslint-disable @typescript-eslint/ban-ts-comment */
  1785. /*
  1786. * Welcome to @reach/auto-id!
  1787. * Let's see if we can make sense of why this hook exists and its
  1788. * implementation.
  1789. *
  1790. * Some background:
  1791. * 1. Accessibility APIs rely heavily on element IDs
  1792. * 2. Requiring developers to put IDs on every element in Reach UI is both
  1793. * cumbersome and error-prone
  1794. * 3. With a component model, we can generate IDs for them!
  1795. *
  1796. * Solution 1: Generate random IDs.
  1797. *
  1798. * This works great as long as you don't server render your app. When React (in
  1799. * the client) tries to reuse the markup from the server, the IDs won't match
  1800. * and React will then recreate the entire DOM tree.
  1801. *
  1802. * Solution 2: Increment an integer
  1803. *
  1804. * This sounds great. Since we're rendering the exact same tree on the server
  1805. * and client, we can increment a counter and get a deterministic result between
  1806. * client and server. Also, JS integers can go up to nine-quadrillion. I'm
  1807. * pretty sure the tab will be closed before an app never needs
  1808. * 10 quadrillion IDs!
  1809. *
  1810. * Problem solved, right?
  1811. *
  1812. * Ah, but there's a catch! React's concurrent rendering makes this approach
  1813. * non-deterministic. While the client and server will end up with the same
  1814. * elements in the end, depending on suspense boundaries (and possibly some user
  1815. * input during the initial render) the incrementing integers won't always match
  1816. * up.
  1817. *
  1818. * Solution 3: Don't use IDs at all on the server; patch after first render.
  1819. *
  1820. * What we've done here is solution 2 with some tricks. With this approach, the
  1821. * ID returned is an empty string on the first render. This way the server and
  1822. * client have the same markup no matter how wild the concurrent rendering may
  1823. * have gotten.
  1824. *
  1825. * After the render, we patch up the components with an incremented ID. This
  1826. * causes a double render on any components with `useId`. Shouldn't be a problem
  1827. * since the components using this hook should be small, and we're only updating
  1828. * the ID attribute on the DOM, nothing big is happening.
  1829. *
  1830. * It doesn't have to be an incremented number, though--we could do generate
  1831. * random strings instead, but incrementing a number is probably the cheapest
  1832. * thing we can do.
  1833. *
  1834. * Additionally, we only do this patchup on the very first client render ever.
  1835. * Any calls to `useId` that happen dynamically in the client will be
  1836. * populated immediately with a value. So, we only get the double render after
  1837. * server hydration and never again, SO BACK OFF ALRIGHT?
  1838. */
  1839. function canUseDOM() {
  1840. return !!(typeof window !== 'undefined' &&
  1841. window.document &&
  1842. window.document.createElement);
  1843. }
  1844. /**
  1845. * React currently throws a warning when using useLayoutEffect on the server. To
  1846. * get around it, we can conditionally useEffect on the server (no-op) and
  1847. * useLayoutEffect in the browser. We occasionally need useLayoutEffect to
  1848. * ensure we don't get a render flash for certain operations, but we may also
  1849. * need affected components to render on the server. One example is when setting
  1850. * a component's descendants to retrieve their index values.
  1851. *
  1852. * Important to note that using this hook as an escape hatch will break the
  1853. * eslint dependency warnings unless you rename the import to `useLayoutEffect`.
  1854. * Use sparingly only when the effect won't effect the rendered HTML to avoid
  1855. * any server/client mismatch.
  1856. *
  1857. * If a useLayoutEffect is needed and the result would create a mismatch, it's
  1858. * likely that the component in question shouldn't be rendered on the server at
  1859. * all, so a better approach would be to lazily render those in a parent
  1860. * component after client-side hydration.
  1861. *
  1862. * https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
  1863. * https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js
  1864. *
  1865. * @param effect
  1866. * @param deps
  1867. */
  1868. var useIsomorphicLayoutEffect = canUseDOM() ? useLayoutEffect : useEffect;
  1869. var serverHandoffComplete = false;
  1870. var id = 0;
  1871. function genId() {
  1872. return "react-day-picker-".concat(++id);
  1873. }
  1874. function useId(providedId) {
  1875. // TODO: Remove error flag when updating internal deps to React 18. None of
  1876. // our tricks will play well with concurrent rendering anyway.
  1877. var _a;
  1878. // If this instance isn't part of the initial render, we don't have to do the
  1879. // double render/patch-up dance. We can just generate the ID and return it.
  1880. var initialId = providedId !== null && providedId !== void 0 ? providedId : (serverHandoffComplete ? genId() : null);
  1881. var _b = useState(initialId), id = _b[0], setId = _b[1];
  1882. useIsomorphicLayoutEffect(function () {
  1883. if (id === null) {
  1884. // Patch the ID after render. We do this in `useLayoutEffect` to avoid any
  1885. // rendering flicker, though it'll make the first render slower (unlikely
  1886. // to matter, but you're welcome to measure your app and let us know if
  1887. // it's a problem).
  1888. setId(genId());
  1889. }
  1890. // eslint-disable-next-line react-hooks/exhaustive-deps
  1891. }, []);
  1892. useEffect(function () {
  1893. if (serverHandoffComplete === false) {
  1894. // Flag all future uses of `useId` to skip the update dance. This is in
  1895. // `useEffect` because it goes after `useLayoutEffect`, ensuring we don't
  1896. // accidentally bail out of the patch-up dance prematurely.
  1897. serverHandoffComplete = true;
  1898. }
  1899. }, []);
  1900. return (_a = providedId !== null && providedId !== void 0 ? providedId : id) !== null && _a !== void 0 ? _a : undefined;
  1901. }
  1902. /** Render a month. */
  1903. function Month(props) {
  1904. var _a;
  1905. var _b;
  1906. var dayPicker = useDayPicker();
  1907. var dir = dayPicker.dir, classNames = dayPicker.classNames, styles = dayPicker.styles, components = dayPicker.components;
  1908. var displayMonths = useNavigation().displayMonths;
  1909. var captionId = useId(dayPicker.id ? "".concat(dayPicker.id, "-").concat(props.displayIndex) : undefined);
  1910. var tableId = dayPicker.id
  1911. ? "".concat(dayPicker.id, "-grid-").concat(props.displayIndex)
  1912. : undefined;
  1913. var className = [classNames.month];
  1914. var style = styles.month;
  1915. var isStart = props.displayIndex === 0;
  1916. var isEnd = props.displayIndex === displayMonths.length - 1;
  1917. var isCenter = !isStart && !isEnd;
  1918. if (dir === 'rtl') {
  1919. _a = [isStart, isEnd], isEnd = _a[0], isStart = _a[1];
  1920. }
  1921. if (isStart) {
  1922. className.push(classNames.caption_start);
  1923. style = __assign(__assign({}, style), styles.caption_start);
  1924. }
  1925. if (isEnd) {
  1926. className.push(classNames.caption_end);
  1927. style = __assign(__assign({}, style), styles.caption_end);
  1928. }
  1929. if (isCenter) {
  1930. className.push(classNames.caption_between);
  1931. style = __assign(__assign({}, style), styles.caption_between);
  1932. }
  1933. var CaptionComponent = (_b = components === null || components === void 0 ? void 0 : components.Caption) !== null && _b !== void 0 ? _b : Caption;
  1934. return (jsxs("div", { className: className.join(' '), style: style, children: [jsx(CaptionComponent, { id: captionId, displayMonth: props.displayMonth, displayIndex: props.displayIndex }), jsx(Table, { id: tableId, "aria-labelledby": captionId, displayMonth: props.displayMonth })] }, props.displayIndex));
  1935. }
  1936. /**
  1937. * Render the wrapper for the month grids.
  1938. */
  1939. function Months(props) {
  1940. var _a = useDayPicker(), classNames = _a.classNames, styles = _a.styles;
  1941. return (jsx("div", { className: classNames.months, style: styles.months, children: props.children }));
  1942. }
  1943. /** Render the container with the months according to the number of months to display. */
  1944. function Root(_a) {
  1945. var _b, _c;
  1946. var initialProps = _a.initialProps;
  1947. var dayPicker = useDayPicker();
  1948. var focusContext = useFocusContext();
  1949. var navigation = useNavigation();
  1950. var _d = useState(false), hasInitialFocus = _d[0], setHasInitialFocus = _d[1];
  1951. // Focus the focus target when initialFocus is passed in
  1952. useEffect(function () {
  1953. if (!dayPicker.initialFocus)
  1954. return;
  1955. if (!focusContext.focusTarget)
  1956. return;
  1957. if (hasInitialFocus)
  1958. return;
  1959. focusContext.focus(focusContext.focusTarget);
  1960. setHasInitialFocus(true);
  1961. }, [
  1962. dayPicker.initialFocus,
  1963. hasInitialFocus,
  1964. focusContext.focus,
  1965. focusContext.focusTarget,
  1966. focusContext
  1967. ]);
  1968. // Apply classnames according to props
  1969. var classNames = [dayPicker.classNames.root, dayPicker.className];
  1970. if (dayPicker.numberOfMonths > 1) {
  1971. classNames.push(dayPicker.classNames.multiple_months);
  1972. }
  1973. if (dayPicker.showWeekNumber) {
  1974. classNames.push(dayPicker.classNames.with_weeknumber);
  1975. }
  1976. var style = __assign(__assign({}, dayPicker.styles.root), dayPicker.style);
  1977. var dataAttributes = Object.keys(initialProps)
  1978. .filter(function (key) { return key.startsWith('data-'); })
  1979. .reduce(function (attrs, key) {
  1980. var _a;
  1981. return __assign(__assign({}, attrs), (_a = {}, _a[key] = initialProps[key], _a));
  1982. }, {});
  1983. var MonthsComponent = (_c = (_b = initialProps.components) === null || _b === void 0 ? void 0 : _b.Months) !== null && _c !== void 0 ? _c : Months;
  1984. return (jsx("div", __assign({ className: classNames.join(' '), style: style, dir: dayPicker.dir, id: dayPicker.id, nonce: initialProps.nonce, title: initialProps.title, lang: initialProps.lang }, dataAttributes, { children: jsx(MonthsComponent, { children: navigation.displayMonths.map(function (month, i) { return (jsx(Month, { displayIndex: i, displayMonth: month }, i)); }) }) })));
  1985. }
  1986. /** Provide the value for all the context providers. */
  1987. function RootProvider(props) {
  1988. var children = props.children, initialProps = __rest(props, ["children"]);
  1989. return (jsx(DayPickerProvider, { initialProps: initialProps, children: jsx(NavigationProvider, { children: jsx(SelectSingleProvider, { initialProps: initialProps, children: jsx(SelectMultipleProvider, { initialProps: initialProps, children: jsx(SelectRangeProvider, { initialProps: initialProps, children: jsx(ModifiersProvider, { children: jsx(FocusProvider, { children: children }) }) }) }) }) }) }));
  1990. }
  1991. /**
  1992. * DayPicker render a date picker component to let users pick dates from a
  1993. * calendar. See http://react-day-picker.js.org for updated documentation and
  1994. * examples.
  1995. *
  1996. * ### Customization
  1997. *
  1998. * DayPicker offers different customization props. For example,
  1999. *
  2000. * - show multiple months using `numberOfMonths`
  2001. * - display a dropdown to navigate the months via `captionLayout`
  2002. * - display the week numbers with `showWeekNumbers`
  2003. * - disable or hide days with `disabled` or `hidden`
  2004. *
  2005. * ### Controlling the months
  2006. *
  2007. * Change the initially displayed month using the `defaultMonth` prop. The
  2008. * displayed months are controlled by DayPicker and stored in its internal
  2009. * state. To control the months yourself, use `month` instead of `defaultMonth`
  2010. * and use the `onMonthChange` event to set it.
  2011. *
  2012. * To limit the months the user can navigate to, use
  2013. * `fromDate`/`fromMonth`/`fromYear` or `toDate`/`toMonth`/`toYear`.
  2014. *
  2015. * ### Selection modes
  2016. *
  2017. * DayPicker supports different selection mode that can be toggled using the
  2018. * `mode` prop:
  2019. *
  2020. * - `mode="single"`: only one day can be selected. Use `required` to make the
  2021. * selection required. Use the `onSelect` event handler to get the selected
  2022. * days.
  2023. * - `mode="multiple"`: users can select one or more days. Limit the amount of
  2024. * days that can be selected with the `min` or the `max` props.
  2025. * - `mode="range"`: users can select a range of days. Limit the amount of days
  2026. * in the range with the `min` or the `max` props.
  2027. * - `mode="default"` (default): the built-in selections are disabled. Implement
  2028. * your own selection mode with `onDayClick`.
  2029. *
  2030. * The selection modes should cover the most common use cases. In case you
  2031. * need a more refined way of selecting days, use `mode="default"`. Use the
  2032. * `selected` props and add the day event handlers to add/remove days from the
  2033. * selection.
  2034. *
  2035. * ### Modifiers
  2036. *
  2037. * A _modifier_ represents different styles or states for the days displayed in
  2038. * the calendar (like "selected" or "disabled"). Define custom modifiers using
  2039. * the `modifiers` prop.
  2040. *
  2041. * ### Formatters and custom component
  2042. *
  2043. * You can customize how the content is displayed in the date picker by using
  2044. * either the formatters or replacing the internal components.
  2045. *
  2046. * For the most common cases you want to use the `formatters` prop to change how
  2047. * the content is formatted in the calendar. Use the `components` prop to
  2048. * replace the internal components, like the navigation icons.
  2049. *
  2050. * ### Styling
  2051. *
  2052. * DayPicker comes with a default, basic style in `react-day-picker/style` – use
  2053. * it as template for your own style.
  2054. *
  2055. * If you are using CSS modules, pass the imported styles object the
  2056. * `classNames` props.
  2057. *
  2058. * You can also style the elements via inline styles using the `styles` prop.
  2059. *
  2060. * ### Form fields
  2061. *
  2062. * If you need to bind the date picker to a form field, you can use the
  2063. * `useInput` hooks for a basic behavior. See the `useInput` source as an
  2064. * example to bind the date picker with form fields.
  2065. *
  2066. * ### Localization
  2067. *
  2068. * To localize DayPicker, import the locale from `date-fns` package and use the
  2069. * `locale` prop.
  2070. *
  2071. * For example, to use Spanish locale:
  2072. *
  2073. * ```
  2074. * import { es } from 'date-fns/locale';
  2075. * <DayPicker locale={es} />
  2076. * ```
  2077. */
  2078. function DayPicker(props) {
  2079. return (jsx(RootProvider, __assign({}, props, { children: jsx(Root, { initialProps: props }) })));
  2080. }
  2081. /** @private */
  2082. function isValidDate(day) {
  2083. return !isNaN(day.getTime());
  2084. }
  2085. /** Return props and setters for binding an input field to DayPicker. */
  2086. function useInput(options) {
  2087. if (options === void 0) { options = {}; }
  2088. var _a = options.locale, locale = _a === void 0 ? enUS : _a, required = options.required, _b = options.format, format$1 = _b === void 0 ? 'PP' : _b, defaultSelected = options.defaultSelected, _c = options.today, today = _c === void 0 ? new Date() : _c;
  2089. var _d = parseFromToProps(options), fromDate = _d.fromDate, toDate = _d.toDate;
  2090. // Shortcut to the DateFns functions
  2091. var parseValue = function (value) { return parse(value, format$1, today, { locale: locale }); };
  2092. // Initialize states
  2093. var _e = useState(defaultSelected !== null && defaultSelected !== void 0 ? defaultSelected : today), month = _e[0], setMonth = _e[1];
  2094. var _f = useState(defaultSelected), selectedDay = _f[0], setSelectedDay = _f[1];
  2095. var defaultInputValue = defaultSelected
  2096. ? format(defaultSelected, format$1, { locale: locale })
  2097. : '';
  2098. var _g = useState(defaultInputValue), inputValue = _g[0], setInputValue = _g[1];
  2099. var reset = function () {
  2100. setSelectedDay(defaultSelected);
  2101. setMonth(defaultSelected !== null && defaultSelected !== void 0 ? defaultSelected : today);
  2102. setInputValue(defaultInputValue !== null && defaultInputValue !== void 0 ? defaultInputValue : '');
  2103. };
  2104. var setSelected = function (date) {
  2105. setSelectedDay(date);
  2106. setMonth(date !== null && date !== void 0 ? date : today);
  2107. setInputValue(date ? format(date, format$1, { locale: locale }) : '');
  2108. };
  2109. var handleDayClick = function (day, _a) {
  2110. var selected = _a.selected;
  2111. if (!required && selected) {
  2112. setSelectedDay(undefined);
  2113. setInputValue('');
  2114. return;
  2115. }
  2116. setSelectedDay(day);
  2117. setInputValue(day ? format(day, format$1, { locale: locale }) : '');
  2118. };
  2119. var handleMonthChange = function (month) {
  2120. setMonth(month);
  2121. };
  2122. // When changing the input field, save its value in state and check if the
  2123. // string is a valid date. If it is a valid day, set it as selected and update
  2124. // the calendar’s month.
  2125. var handleChange = function (e) {
  2126. setInputValue(e.target.value);
  2127. var day = parseValue(e.target.value);
  2128. var isBefore = fromDate && differenceInCalendarDays(fromDate, day) > 0;
  2129. var isAfter = toDate && differenceInCalendarDays(day, toDate) > 0;
  2130. if (!isValidDate(day) || isBefore || isAfter) {
  2131. setSelectedDay(undefined);
  2132. return;
  2133. }
  2134. setSelectedDay(day);
  2135. setMonth(day);
  2136. };
  2137. // Special case for _required_ fields: on blur, if the value of the input is not
  2138. // a valid date, reset the calendar and the input value.
  2139. var handleBlur = function (e) {
  2140. var day = parseValue(e.target.value);
  2141. if (!isValidDate(day)) {
  2142. reset();
  2143. }
  2144. };
  2145. // When focusing, make sure DayPicker visualizes the month of the date in the
  2146. // input field.
  2147. var handleFocus = function (e) {
  2148. if (!e.target.value) {
  2149. reset();
  2150. return;
  2151. }
  2152. var day = parseValue(e.target.value);
  2153. if (isValidDate(day)) {
  2154. setMonth(day);
  2155. }
  2156. };
  2157. var dayPickerProps = {
  2158. month: month,
  2159. onDayClick: handleDayClick,
  2160. onMonthChange: handleMonthChange,
  2161. selected: selectedDay,
  2162. locale: locale,
  2163. fromDate: fromDate,
  2164. toDate: toDate,
  2165. today: today
  2166. };
  2167. var inputProps = {
  2168. onBlur: handleBlur,
  2169. onChange: handleChange,
  2170. onFocus: handleFocus,
  2171. value: inputValue,
  2172. placeholder: format(new Date(), format$1, { locale: locale })
  2173. };
  2174. return { dayPickerProps: dayPickerProps, inputProps: inputProps, reset: reset, setSelected: setSelected };
  2175. }
  2176. /** Returns true when the props are of type {@link DayPickerDefaultProps}. */
  2177. function isDayPickerDefault(props) {
  2178. return props.mode === undefined || props.mode === 'default';
  2179. }
  2180. export { Button, Caption, CaptionDropdowns, CaptionLabel, CaptionNavigation, Day, DayContent, DayPicker, DayPickerContext, DayPickerProvider, Dropdown, FocusContext, FocusProvider, Footer, Head, HeadRow, IconDropdown, IconLeft, IconRight, InternalModifier, Months, NavigationContext, NavigationProvider, RootProvider, Row, SelectMultipleContext, SelectMultipleProvider, SelectMultipleProviderInternal, SelectRangeContext, SelectRangeProvider, SelectRangeProviderInternal, SelectSingleContext, SelectSingleProvider, SelectSingleProviderInternal, WeekNumber, addToRange, isDateAfterType, isDateBeforeType, isDateInterval, isDateRange, isDayOfWeekType, isDayPickerDefault, isDayPickerMultiple, isDayPickerRange, isDayPickerSingle, isMatch, useActiveModifiers, useDayPicker, useDayRender, useFocusContext, useInput, useNavigation, useSelectMultiple, useSelectRange, useSelectSingle };
  2181. //# sourceMappingURL=index.esm.js.map