@fremtind/jokul 0.23.3 → 0.23.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/build-stats.html +1 -1
- package/build/cjs/components/datepicker/DatePicker.js +1 -1
- package/build/cjs/components/datepicker/DatePicker.js.map +1 -1
- package/build/cjs/components/datepicker/internal/useCalendar.js +1 -1
- package/build/cjs/components/datepicker/internal/useCalendar.js.map +1 -1
- package/build/cjs/components/datepicker/internal/utils.js +1 -1
- package/build/cjs/components/datepicker/internal/utils.js.map +1 -1
- package/build/es/components/datepicker/DatePicker.js +1 -1
- package/build/es/components/datepicker/DatePicker.js.map +1 -1
- package/build/es/components/datepicker/internal/useCalendar.js +1 -1
- package/build/es/components/datepicker/internal/useCalendar.js.map +1 -1
- package/build/es/components/datepicker/internal/utils.js +1 -1
- package/build/es/components/datepicker/internal/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/components/button/styles/button.css +2 -2
- package/src/components/button/styles/button.min.css +1 -1
- package/src/components/checkbox/styles/checkbox.css +4 -4
- package/src/components/checkbox/styles/checkbox.min.css +1 -1
- package/src/components/feedback/styles/feedback.css +2 -2
- package/src/components/feedback/styles/feedback.min.css +1 -1
- package/src/components/input-group/styles/input-group.css +2 -2
- package/src/components/input-group/styles/input-group.min.css +1 -1
- package/src/components/loader/styles/loader.css +6 -6
- package/src/components/loader/styles/loader.min.css +1 -1
- package/src/components/loader/styles/skeleton-loader.css +5 -5
- package/src/components/loader/styles/skeleton-loader.min.css +1 -1
- package/src/components/message/styles/message.css +2 -2
- package/src/components/message/styles/message.min.css +1 -1
- package/src/components/progress-bar/styles/progress-bar.css +2 -2
- package/src/components/progress-bar/styles/progress-bar.min.css +1 -1
- package/src/components/radio-button/styles/radio-button.css +2 -2
- package/src/components/radio-button/styles/radio-button.min.css +1 -1
- package/src/components/system-message/styles/system-message.css +2 -2
- package/src/components/system-message/styles/system-message.min.css +1 -1
- package/src/components/toast/styles/toast.css +4 -4
- package/src/components/toast/styles/toast.min.css +1 -1
- package/src/styles/styles.css +33 -33
- package/src/styles/styles.min.css +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),r=require("../../../clsx-E3yX_9sL.cjs"),n=require("date-fns
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),r=require("../../../clsx-E3yX_9sL.cjs"),n=require("date-fns"),o=require("react"),i=require("react-dom");require("../icon/Icon.js"),require("../icon/icons/animated/ArrowVerticalAnimated.js"),require("../icon/icons/animated/ArrowHorizontalAnimated.js"),require("../icon/icons/animated/PlusRemoveAnimated.js"),require("../icon/icons/ArrowDownIcon.js"),require("../icon/icons/ArrowLeftIcon.js"),require("../icon/icons/ArrowNorthEastIcon.js"),require("../icon/icons/ArrowRightIcon.js"),require("../icon/icons/ArrowUpIcon.js");const t=require("../icon/icons/CalendarIcon.js");require("../icon/icons/CheckIcon.js"),require("../icon/icons/ChevronDownIcon.js"),require("../icon/icons/ChevronLeftIcon.js"),require("../icon/icons/ChevronRightIcon.js"),require("../icon/icons/ChevronUpIcon.js"),require("../icon/icons/CloseIcon.js"),require("../icon/icons/CopyIcon.js"),require("../icon/icons/DotsIcon.js"),require("../icon/icons/DragIcon.js"),require("../icon/icons/ErrorIcon.js"),require("../icon/icons/GreenCheckIcon.js"),require("../icon/icons/HamburgerIcon.js"),require("../icon/icons/InfoIcon.js"),require("../icon/icons/LinkIcon.js"),require("../icon/icons/PlusIcon.js"),require("../icon/icons/QuestionIcon.js"),require("../icon/icons/RedCrossIcon.js"),require("../icon/icons/SearchIcon.js"),require("../icon/icons/SuccessIcon.js"),require("../icon/icons/WarningIcon.js"),require("../icon/icons/MinusIcon.js"),require("../icon/icons/ThumbDownIcon.js"),require("../icon/icons/ThumbUpIcon.js"),require("../icon/icons/TrashCanIcon.js"),require("../icon/icons/PenIcon.js");const s=require("../icon-button/IconButton.js");require("../../hooks/useScreen/useScreen.js"),require("../../hooks/useId/useId.js"),require("../tooltip/Tooltip.js"),require("../tooltip/TooltipContent.js"),require("../tooltip/TooltipTrigger.js");const a=require("../input-group/InputGroup.js"),c=require("../popover/Popover.js");require("../text-input/BaseTextArea.js");const u=require("../text-input/BaseTextInput.js");require("../text-input/TextArea.js"),require("../text-input/TextInput.js");const l=require("./internal/Calendar.js"),d=require("./internal/utils.js"),p=require("./utils.js"),j=require("./validation.js"),q=o.forwardRef(((q,I)=>{const{"data-testautoid":h,id:b,className:f="",label:k="Velg dato",labelProps:v,defaultValue:m,defaultShow:C=!1,value:g,disableBeforeDate:D,disableAfterDate:x,yearsToShow:y,name:w,helpLabel:T,errorLabel:S,invalid:L,density:P,days:A,months:R,monthLabel:B,yearLabel:E,placeholder:O="dd.mm.åååå",width:_="11.25rem",onChange:N,onBlur:U,onFocus:V,onKeyDown:W,action:F,showCalendarLabel:G="Åpne kalender",hideCalendarLabel:H="Lukk kalender",supportLabelProps:K,tooltipProps:M,...z}=q;"production"!==process.env.NODE_ENV&&g&&m&&console.warn("DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.");const Q=p.parseDateString(D),J=Q?n.startOfDay(Q):void 0,X=p.parseDateString(x),Y=X?n.startOfDay(X):void 0,[Z,$]=o.useState(d.getInitialDate(g,m,J,Y)),[ee,re]=o.useState(null),[ne,oe]=o.useState(C),ie=o.useRef(null),te=o.useRef(null),se=o.useRef(null),ae=o.useRef(null),ce=o.useCallback((e=>{ae.current=e,I&&("function"==typeof I?I(e):I.current=e)}),[ae,I]),ue=o.useCallback((e=>{V&&te.current&&(te.current.contains(e.relatedTarget)||V(e,Z,{error:ee,value:e.target.value}))}),[V,Z,ee]),le=o.useCallback((e=>{U&&U(e,Z,{error:ee,value:e.target.value})}),[U,Z,ee]),de=o.useCallback((e=>{"Escape"===e.key&&(oe(!1),e.preventDefault(),e.stopPropagation()),null!=F&&F.onKeyDown&&F.onKeyDown(e)}),[oe,F]),pe=o.useCallback((e=>{let r=null,n=null;if(e.target.value){const o=p.parseDateString(e.target.value);o?J&&!j.isWithinLowerBound(o,J)?n="OUTSIDE_LOWER_BOUND":Y&&!j.isWithinUpperBound(o,Y)?n="OUTSIDE_UPPER_BOUND":oe(!1):n="WRONG_FORMAT",r=o||null}re(n),$(r),N&&N(e,r,{error:n,value:e.target.value})}),[N,re,$,oe,J,Y]),je=o.useCallback((e=>{i.flushSync((()=>{oe(!ne)}));const r=ie.current,n=r&&r.querySelector('[aria-pressed="true"]');n&&n.focus(),null!=F&&F.onClick&&F.onClick(e)}),[oe,ne,F,ie]),qe=o.useCallback((({date:e})=>{if(oe(!1),$(e),ae.current){const r=ae.current;r.value=p.formatInput(e);const n=document.createEvent("HTMLEvents");n.initEvent("input",!0,!1),r.dispatchEvent(n),r.focus(),N&&N(n,e,{error:null,value:r.value})}}),[oe,$,N]),Ie=o.useCallback((e=>{e.preventDefault(),oe(!1),se.current&&se.current.focus()}),[oe]);return e.jsx(a.InputGroup,{id:b,className:r.clsx("jkl-datepicker",f,{"jkl-datepicker--open":ne}),...z,ref:te,label:k,labelProps:v,density:P,helpLabel:T,errorLabel:S,supportLabelProps:K,tooltipProps:M,render:r=>e.jsx(u.BaseTextInput,{ref:ce,"data-testid":"jkl-datepicker__input","data-testautoid":h,className:"jkl-datepicker__input",name:w,defaultValue:m,density:P,value:g,type:"text",placeholder:O,width:_,onFocus:ue,onBlur:le,onChange:pe,actionButton:e.jsxs(c,{positionReference:ae,open:ne,onOpenChange:()=>oe(!ne),offset:8,children:[e.jsx(c.Trigger,{...F,"data-testid":"jkl-datepicker__trigger",className:"jkl-text-input-action-button",title:ne?H:G,tabIndex:0,onClick:je,onKeyDown:de,asChild:!0,children:e.jsx(s.IconButton,{children:e.jsx(t.CalendarIcon,{})})}),e.jsx(c.Content,{initialFocus:-1,padding:24,children:e.jsx(l.Calendar,{ref:ie,density:P,date:Z,minDate:J,maxDate:Y,days:A,months:R,monthLabel:B,yearLabel:E,yearsToShow:y,onDateSelected:qe,onTabOutside:Ie})})]}),...r})})}));q.displayName="DatePicker",exports.DatePicker=q;
|
|
2
2
|
//# sourceMappingURL=DatePicker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker.js","sources":["../../../../src/components/datepicker/DatePicker.tsx"],"sourcesContent":["import clsx from \"clsx\";\nimport startOfDay from \"date-fns/startOfDay\";\nimport React, {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n forwardRef,\n useCallback,\n useRef,\n useState,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { CalendarIcon } from \"../icon\";\nimport { IconButton } from \"../icon-button\";\nimport { InputGroup } from \"../input-group\";\nimport { Popover } from \"../popover\";\nimport { BaseTextInput } from \"../text-input\";\nimport { Calendar } from \"./internal/Calendar\";\nimport { getInitialDate, DateInfo } from \"./internal/utils\";\nimport { DatePickerProps, DateValidationError } from \"./types\";\nimport { formatInput, parseDateString } from \"./utils\";\nimport { isWithinLowerBound, isWithinUpperBound } from \"./validation\";\n\nexport const DatePicker = forwardRef<HTMLInputElement, DatePickerProps>((props, forwardedInputRef) => {\n const {\n \"data-testautoid\": testAutoId,\n id,\n className = \"\",\n label = \"Velg dato\",\n labelProps,\n defaultValue,\n defaultShow = false,\n value,\n disableBeforeDate: disableBefore,\n disableAfterDate: disableAfter,\n yearsToShow,\n name,\n helpLabel,\n errorLabel,\n invalid,\n density,\n days,\n months,\n monthLabel,\n yearLabel,\n placeholder = \"dd.mm.åååå\",\n width = \"11.25rem\",\n onChange,\n onBlur,\n onFocus,\n onKeyDown,\n action,\n showCalendarLabel = \"Åpne kalender\",\n hideCalendarLabel = \"Lukk kalender\",\n supportLabelProps,\n tooltipProps,\n ...rest\n } = props;\n\n if (process.env.NODE_ENV !== \"production\" && value && defaultValue) {\n console.warn(\n \"DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.\",\n );\n }\n /// Input state\n\n const disableBeforeDate = parseDateString(disableBefore);\n const minDate = disableBeforeDate ? startOfDay(disableBeforeDate) : undefined;\n const disableAfterDate = parseDateString(disableAfter);\n const maxDate = disableAfterDate ? startOfDay(disableAfterDate) : undefined;\n\n const [date, setDate] = useState(getInitialDate(value, defaultValue, minDate, maxDate));\n const [error, setError] = useState<DateValidationError | null>(null);\n\n /// Calendar state\n\n const [showCalendar, setShowCalendar] = useState(defaultShow);\n\n const calendarRef = useRef<HTMLDivElement>(null);\n const datepickerRef = useRef<HTMLDivElement>(null);\n\n /// Input events\n\n const iconButtonRef = useRef<HTMLButtonElement | null>(null);\n const inputRef = useRef<HTMLInputElement | null>(null);\n\n // Hjelper for å gjøre det enklere å både forwarde refen men også bruke den selv internt\n const unifiedInputRef = useCallback(\n (instance: HTMLInputElement | null) => {\n inputRef.current = instance;\n if (forwardedInputRef) {\n if (typeof forwardedInputRef === \"function\") {\n forwardedInputRef(instance);\n } else {\n forwardedInputRef.current = instance;\n }\n }\n },\n [inputRef, forwardedInputRef],\n );\n\n const handleFocus = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (!onFocus || !datepickerRef.current) {\n return;\n }\n\n const nextFocusIsInside = datepickerRef.current.contains(e.relatedTarget as Node);\n if (!nextFocusIsInside) {\n onFocus(e, date, { error, value: e.target.value });\n }\n },\n [onFocus, date, error],\n );\n\n const handleBlur = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (onBlur) {\n onBlur(e, date, { error, value: e.target.value });\n }\n },\n [onBlur, date, error],\n );\n\n const handleKeyDownAction = useCallback(\n (e: React.KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === \"Escape\") {\n setShowCalendar(false);\n e.preventDefault();\n e.stopPropagation();\n }\n\n if (action?.onKeyDown) {\n action.onKeyDown(e);\n }\n },\n [setShowCalendar, action],\n );\n\n const handleChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n let nextDate: Date | null = null;\n let nextError: DateValidationError | null = null;\n\n if (e.target.value) {\n const val = parseDateString(e.target.value);\n if (!val) {\n nextError = \"WRONG_FORMAT\";\n } else if (minDate && !isWithinLowerBound(val, minDate)) {\n nextError = \"OUTSIDE_LOWER_BOUND\";\n } else if (maxDate && !isWithinUpperBound(val, maxDate)) {\n nextError = \"OUTSIDE_UPPER_BOUND\";\n } else {\n setShowCalendar(false);\n }\n nextDate = val || null;\n }\n\n setError(nextError);\n setDate(nextDate);\n\n if (onChange) {\n onChange(e, nextDate, { error: nextError, value: e.target.value });\n }\n },\n [onChange, setError, setDate, setShowCalendar, minDate, maxDate],\n );\n\n /// Calendar events\n\n const clickCalendar = useCallback(\n (e: MouseEvent<HTMLButtonElement>) => {\n flushSync(() => {\n setShowCalendar(!showCalendar);\n });\n\n const calendarEl = calendarRef.current;\n const button = calendarEl && (calendarEl.querySelector('[aria-pressed=\"true\"]') as HTMLButtonElement);\n button && button.focus();\n\n if (action?.onClick) {\n action.onClick(e);\n }\n },\n [setShowCalendar, showCalendar, action, calendarRef],\n );\n\n const handleClickCalendarDay = useCallback(\n ({ date }: DateInfo) => {\n setShowCalendar(false);\n setDate(date);\n\n if (inputRef.current) {\n const node = inputRef.current;\n\n node.value = formatInput(date);\n\n // Simulér et change-event så APIet blir så likt som mulig en endring av inputfeltet\n const event = document.createEvent(\"HTMLEvents\");\n event.initEvent(\"input\", true, false);\n node.dispatchEvent(event);\n\n node.focus();\n\n if (onChange) {\n // Det er ikke helt sant at dette er et React.SyntheticEvent, men it's fine – probably?\n // Den har tingene man kan forvente, men hvis du gjør serdeles fancy ting med events\n // så kan det hende du må utvide denne for å dekke behovet ditt.\n onChange(event as unknown as ChangeEvent<HTMLInputElement>, date, {\n error: null,\n value: node.value,\n });\n }\n }\n },\n [setShowCalendar, setDate, onChange],\n );\n\n const handleTabOutsideCalendar = useCallback(\n (e: KeyboardEvent) => {\n e.preventDefault();\n setShowCalendar(false);\n iconButtonRef.current && iconButtonRef.current.focus();\n },\n [setShowCalendar],\n );\n\n return (\n <InputGroup\n id={id}\n className={clsx(\"jkl-datepicker\", className, {\n \"jkl-datepicker--open\": showCalendar,\n })}\n {...rest}\n ref={datepickerRef}\n label={label}\n labelProps={labelProps}\n density={density}\n helpLabel={helpLabel}\n errorLabel={errorLabel}\n supportLabelProps={supportLabelProps}\n tooltipProps={tooltipProps}\n render={(inputProps) => (\n <BaseTextInput\n ref={unifiedInputRef}\n data-testid=\"jkl-datepicker__input\"\n data-testautoid={testAutoId}\n className=\"jkl-datepicker__input\"\n name={name}\n defaultValue={defaultValue}\n density={density}\n value={value}\n type=\"text\"\n placeholder={placeholder}\n width={width}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onChange={handleChange}\n actionButton={\n <Popover\n positionReference={inputRef}\n open={showCalendar}\n onOpenChange={() => setShowCalendar(!showCalendar)}\n offset={8}\n >\n <Popover.Trigger\n {...action}\n data-testid=\"jkl-datepicker__trigger\"\n className=\"jkl-text-input-action-button\"\n title={showCalendar ? hideCalendarLabel : showCalendarLabel}\n tabIndex={0}\n onClick={clickCalendar}\n onKeyDown={handleKeyDownAction}\n asChild\n >\n <IconButton>\n <CalendarIcon />\n </IconButton>\n </Popover.Trigger>\n <Popover.Content initialFocus={-1} padding={24}>\n <Calendar\n ref={calendarRef}\n density={density}\n date={date}\n minDate={minDate}\n maxDate={maxDate}\n days={days}\n months={months}\n monthLabel={monthLabel}\n yearLabel={yearLabel}\n yearsToShow={yearsToShow}\n onDateSelected={handleClickCalendarDay}\n onTabOutside={handleTabOutsideCalendar}\n />\n </Popover.Content>\n </Popover>\n }\n {...inputProps}\n />\n )}\n />\n );\n});\n\nDatePicker.displayName = \"DatePicker\";\n"],"names":["DatePicker","forwardRef","props","forwardedInputRef","testAutoId","id","className","label","labelProps","defaultValue","defaultShow","value","disableBeforeDate","disableBefore","disableAfterDate","disableAfter","yearsToShow","name","helpLabel","errorLabel","invalid","density","days","months","monthLabel","yearLabel","placeholder","width","onChange","onBlur","onFocus","onKeyDown","action","showCalendarLabel","hideCalendarLabel","supportLabelProps","tooltipProps","rest","process","env","NODE_ENV","console","warn","parseDateString","minDate","startOfDay","maxDate","date","setDate","useState","getInitialDate","error","setError","showCalendar","setShowCalendar","calendarRef","useRef","datepickerRef","iconButtonRef","inputRef","unifiedInputRef","useCallback","instance","current","handleFocus","e","contains","relatedTarget","target","handleBlur","handleKeyDownAction","key","preventDefault","stopPropagation","handleChange","nextDate","nextError","val","isWithinLowerBound","isWithinUpperBound","clickCalendar","flushSync","calendarEl","button","querySelector","focus","onClick","handleClickCalendarDay","node","formatInput","event","document","createEvent","initEvent","dispatchEvent","handleTabOutsideCalendar","jsx","InputGroup","clsx","ref","render","inputProps","BaseTextInput","type","actionButton","jsxs","Popover","positionReference","open","onOpenChange","offset","children","Trigger","title","tabIndex","asChild","IconButton","CalendarIcon","Content","initialFocus","padding","Calendar","onDateSelected","onTabOutside","displayName"],"mappings":"0wEAwBaA,EAAaC,EAAAA,YAA8C,CAACC,EAAOC,KACtE,MACF,kBAAmBC,EACnBC,GAAAA,EACAC,UAAAA,EAAY,GACZC,MAAAA,EAAQ,YACRC,WAAAA,EACAC,aAAAA,EACAC,YAAAA,GAAc,EACdC,MAAAA,EACAC,kBAAmBC,EACnBC,iBAAkBC,EAClBC,YAAAA,EACAC,KAAAA,EACAC,UAAAA,EACAC,WAAAA,EACAC,QAAAA,EACAC,QAAAA,EACAC,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAC,YAAAA,EAAc,aACdC,MAAAA,EAAQ,WACRC,SAAAA,EACAC,OAAAA,EACAC,QAAAA,EACAC,UAAAA,EACAC,OAAAA,EACAC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EACAC,aAAAA,KACGC,GACHnC,EAEyB,eAAzBoC,QAAQC,IAAIC,UAA6B7B,GAASF,GAC1CgC,QAAAC,KACJ,sIAKF,MAAA9B,EAAo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,WAAAA,EACAa,QAAAA,EACAH,UAAAA,EACAC,WAAAA,EACAgB,kBAAAA,EACAC,aAAAA,EACAgE,OAASC,GACLL,EAAAA,IAACM,EAAAA,cAAA,CACGH,IAAKvC,GACL,cAAY,wBACZ,kBAAiBxD,EACjBE,UAAU,wBACVW,KAAAA,EACAR,aAAAA,EACAY,QAAAA,EACAV,MAAAA,EACA4F,KAAK,OACL7E,YAAAA,EACAC,MAAAA,EACAG,QAASkC,GACTnC,OAAQwC,GACRzC,SAAU8C,GACV8B,aACIC,EAAAA,KAACC,EAAA,CACGC,kBAAmBhD,GACnBiD,KAAMvD,GACNwD,aAAc,IAAMvD,IAAiBD,IACrCyD,OAAQ,EAERC,SAAA,CAAAf,EAAAA,IAACU,EAAQM,QAAR,IACOhF,EACJ,cAAY,0BACZ1B,UAAU,+BACV2G,MAAO5D,GAAenB,EAAoBD,EAC1CiF,SAAU,EACV5B,QAASN,GACTjD,UAAWuC,GACX6C,SAAO,EAEPJ,SAACf,EAAAA,IAAAoB,EAAAA,WAAA,CACGL,SAACf,EAAAA,IAAAqB,EAAAA,aAAA,CAAa,aAGrBX,EAAQY,QAAR,CAAgBC,cAAc,EAAIC,QAAS,GACxCT,SAAAf,EAAAA,IAACyB,EAAAA,SAAA,CACGtB,IAAK5C,GACLlC,QAAAA,EACA0B,KAAAA,EACAH,QAAAA,EACAE,QAAAA,EACAxB,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAT,YAAAA,EACA0G,eAAgBnC,GAChBoC,aAAc5B,aAK1BM,KACR,IAMhBrG,EAAW4H,YAAc"}
|
|
1
|
+
{"version":3,"file":"DatePicker.js","sources":["../../../../src/components/datepicker/DatePicker.tsx"],"sourcesContent":["import clsx from \"clsx\";\nimport { startOfDay } from \"date-fns\";\nimport React, {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n forwardRef,\n useCallback,\n useRef,\n useState,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { CalendarIcon } from \"../icon\";\nimport { IconButton } from \"../icon-button\";\nimport { InputGroup } from \"../input-group\";\nimport { Popover } from \"../popover\";\nimport { BaseTextInput } from \"../text-input\";\nimport { Calendar } from \"./internal/Calendar\";\nimport { getInitialDate, DateInfo } from \"./internal/utils\";\nimport { DatePickerProps, DateValidationError } from \"./types\";\nimport { formatInput, parseDateString } from \"./utils\";\nimport { isWithinLowerBound, isWithinUpperBound } from \"./validation\";\n\nexport const DatePicker = forwardRef<HTMLInputElement, DatePickerProps>((props, forwardedInputRef) => {\n const {\n \"data-testautoid\": testAutoId,\n id,\n className = \"\",\n label = \"Velg dato\",\n labelProps,\n defaultValue,\n defaultShow = false,\n value,\n disableBeforeDate: disableBefore,\n disableAfterDate: disableAfter,\n yearsToShow,\n name,\n helpLabel,\n errorLabel,\n invalid,\n density,\n days,\n months,\n monthLabel,\n yearLabel,\n placeholder = \"dd.mm.åååå\",\n width = \"11.25rem\",\n onChange,\n onBlur,\n onFocus,\n onKeyDown,\n action,\n showCalendarLabel = \"Åpne kalender\",\n hideCalendarLabel = \"Lukk kalender\",\n supportLabelProps,\n tooltipProps,\n ...rest\n } = props;\n\n if (process.env.NODE_ENV !== \"production\" && value && defaultValue) {\n console.warn(\n \"DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.\",\n );\n }\n /// Input state\n\n const disableBeforeDate = parseDateString(disableBefore);\n const minDate = disableBeforeDate ? startOfDay(disableBeforeDate) : undefined;\n const disableAfterDate = parseDateString(disableAfter);\n const maxDate = disableAfterDate ? startOfDay(disableAfterDate) : undefined;\n\n const [date, setDate] = useState(getInitialDate(value, defaultValue, minDate, maxDate));\n const [error, setError] = useState<DateValidationError | null>(null);\n\n /// Calendar state\n\n const [showCalendar, setShowCalendar] = useState(defaultShow);\n\n const calendarRef = useRef<HTMLDivElement>(null);\n const datepickerRef = useRef<HTMLDivElement>(null);\n\n /// Input events\n\n const iconButtonRef = useRef<HTMLButtonElement | null>(null);\n const inputRef = useRef<HTMLInputElement | null>(null);\n\n // Hjelper for å gjøre det enklere å både forwarde refen men også bruke den selv internt\n const unifiedInputRef = useCallback(\n (instance: HTMLInputElement | null) => {\n inputRef.current = instance;\n if (forwardedInputRef) {\n if (typeof forwardedInputRef === \"function\") {\n forwardedInputRef(instance);\n } else {\n forwardedInputRef.current = instance;\n }\n }\n },\n [inputRef, forwardedInputRef],\n );\n\n const handleFocus = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (!onFocus || !datepickerRef.current) {\n return;\n }\n\n const nextFocusIsInside = datepickerRef.current.contains(e.relatedTarget as Node);\n if (!nextFocusIsInside) {\n onFocus(e, date, { error, value: e.target.value });\n }\n },\n [onFocus, date, error],\n );\n\n const handleBlur = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (onBlur) {\n onBlur(e, date, { error, value: e.target.value });\n }\n },\n [onBlur, date, error],\n );\n\n const handleKeyDownAction = useCallback(\n (e: React.KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === \"Escape\") {\n setShowCalendar(false);\n e.preventDefault();\n e.stopPropagation();\n }\n\n if (action?.onKeyDown) {\n action.onKeyDown(e);\n }\n },\n [setShowCalendar, action],\n );\n\n const handleChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n let nextDate: Date | null = null;\n let nextError: DateValidationError | null = null;\n\n if (e.target.value) {\n const val = parseDateString(e.target.value);\n if (!val) {\n nextError = \"WRONG_FORMAT\";\n } else if (minDate && !isWithinLowerBound(val, minDate)) {\n nextError = \"OUTSIDE_LOWER_BOUND\";\n } else if (maxDate && !isWithinUpperBound(val, maxDate)) {\n nextError = \"OUTSIDE_UPPER_BOUND\";\n } else {\n setShowCalendar(false);\n }\n nextDate = val || null;\n }\n\n setError(nextError);\n setDate(nextDate);\n\n if (onChange) {\n onChange(e, nextDate, { error: nextError, value: e.target.value });\n }\n },\n [onChange, setError, setDate, setShowCalendar, minDate, maxDate],\n );\n\n /// Calendar events\n\n const clickCalendar = useCallback(\n (e: MouseEvent<HTMLButtonElement>) => {\n flushSync(() => {\n setShowCalendar(!showCalendar);\n });\n\n const calendarEl = calendarRef.current;\n const button = calendarEl && (calendarEl.querySelector('[aria-pressed=\"true\"]') as HTMLButtonElement);\n button && button.focus();\n\n if (action?.onClick) {\n action.onClick(e);\n }\n },\n [setShowCalendar, showCalendar, action, calendarRef],\n );\n\n const handleClickCalendarDay = useCallback(\n ({ date }: DateInfo) => {\n setShowCalendar(false);\n setDate(date);\n\n if (inputRef.current) {\n const node = inputRef.current;\n\n node.value = formatInput(date);\n\n // Simulér et change-event så APIet blir så likt som mulig en endring av inputfeltet\n const event = document.createEvent(\"HTMLEvents\");\n event.initEvent(\"input\", true, false);\n node.dispatchEvent(event);\n\n node.focus();\n\n if (onChange) {\n // Det er ikke helt sant at dette er et React.SyntheticEvent, men it's fine – probably?\n // Den har tingene man kan forvente, men hvis du gjør serdeles fancy ting med events\n // så kan det hende du må utvide denne for å dekke behovet ditt.\n onChange(event as unknown as ChangeEvent<HTMLInputElement>, date, {\n error: null,\n value: node.value,\n });\n }\n }\n },\n [setShowCalendar, setDate, onChange],\n );\n\n const handleTabOutsideCalendar = useCallback(\n (e: KeyboardEvent) => {\n e.preventDefault();\n setShowCalendar(false);\n iconButtonRef.current && iconButtonRef.current.focus();\n },\n [setShowCalendar],\n );\n\n return (\n <InputGroup\n id={id}\n className={clsx(\"jkl-datepicker\", className, {\n \"jkl-datepicker--open\": showCalendar,\n })}\n {...rest}\n ref={datepickerRef}\n label={label}\n labelProps={labelProps}\n density={density}\n helpLabel={helpLabel}\n errorLabel={errorLabel}\n supportLabelProps={supportLabelProps}\n tooltipProps={tooltipProps}\n render={(inputProps) => (\n <BaseTextInput\n ref={unifiedInputRef}\n data-testid=\"jkl-datepicker__input\"\n data-testautoid={testAutoId}\n className=\"jkl-datepicker__input\"\n name={name}\n defaultValue={defaultValue}\n density={density}\n value={value}\n type=\"text\"\n placeholder={placeholder}\n width={width}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onChange={handleChange}\n actionButton={\n <Popover\n positionReference={inputRef}\n open={showCalendar}\n onOpenChange={() => setShowCalendar(!showCalendar)}\n offset={8}\n >\n <Popover.Trigger\n {...action}\n data-testid=\"jkl-datepicker__trigger\"\n className=\"jkl-text-input-action-button\"\n title={showCalendar ? hideCalendarLabel : showCalendarLabel}\n tabIndex={0}\n onClick={clickCalendar}\n onKeyDown={handleKeyDownAction}\n asChild\n >\n <IconButton>\n <CalendarIcon />\n </IconButton>\n </Popover.Trigger>\n <Popover.Content initialFocus={-1} padding={24}>\n <Calendar\n ref={calendarRef}\n density={density}\n date={date}\n minDate={minDate}\n maxDate={maxDate}\n days={days}\n months={months}\n monthLabel={monthLabel}\n yearLabel={yearLabel}\n yearsToShow={yearsToShow}\n onDateSelected={handleClickCalendarDay}\n onTabOutside={handleTabOutsideCalendar}\n />\n </Popover.Content>\n </Popover>\n }\n {...inputProps}\n />\n )}\n />\n );\n});\n\nDatePicker.displayName = \"DatePicker\";\n"],"names":["DatePicker","forwardRef","props","forwardedInputRef","testAutoId","id","className","label","labelProps","defaultValue","defaultShow","value","disableBeforeDate","disableBefore","disableAfterDate","disableAfter","yearsToShow","name","helpLabel","errorLabel","invalid","density","days","months","monthLabel","yearLabel","placeholder","width","onChange","onBlur","onFocus","onKeyDown","action","showCalendarLabel","hideCalendarLabel","supportLabelProps","tooltipProps","rest","process","env","NODE_ENV","console","warn","parseDateString","minDate","startOfDay","maxDate","date","setDate","useState","getInitialDate","error","setError","showCalendar","setShowCalendar","calendarRef","useRef","datepickerRef","iconButtonRef","inputRef","unifiedInputRef","useCallback","instance","current","handleFocus","e","contains","relatedTarget","target","handleBlur","handleKeyDownAction","key","preventDefault","stopPropagation","handleChange","nextDate","nextError","val","isWithinLowerBound","isWithinUpperBound","clickCalendar","flushSync","calendarEl","button","querySelector","focus","onClick","handleClickCalendarDay","node","formatInput","event","document","createEvent","initEvent","dispatchEvent","handleTabOutsideCalendar","jsx","InputGroup","clsx","ref","render","inputProps","BaseTextInput","type","actionButton","jsxs","Popover","positionReference","open","onOpenChange","offset","children","Trigger","title","tabIndex","asChild","IconButton","CalendarIcon","Content","initialFocus","padding","Calendar","onDateSelected","onTabOutside","displayName"],"mappings":"+vEAwBaA,EAAaC,EAAAA,YAA8C,CAACC,EAAOC,KACtE,MACF,kBAAmBC,EACnBC,GAAAA,EACAC,UAAAA,EAAY,GACZC,MAAAA,EAAQ,YACRC,WAAAA,EACAC,aAAAA,EACAC,YAAAA,GAAc,EACdC,MAAAA,EACAC,kBAAmBC,EACnBC,iBAAkBC,EAClBC,YAAAA,EACAC,KAAAA,EACAC,UAAAA,EACAC,WAAAA,EACAC,QAAAA,EACAC,QAAAA,EACAC,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAC,YAAAA,EAAc,aACdC,MAAAA,EAAQ,WACRC,SAAAA,EACAC,OAAAA,EACAC,QAAAA,EACAC,UAAAA,EACAC,OAAAA,EACAC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EACAC,aAAAA,KACGC,GACHnC,EAEyB,eAAzBoC,QAAQC,IAAIC,UAA6B7B,GAASF,GAC1CgC,QAAAC,KACJ,sIAKF,MAAA9B,EAAoB+B,kBAAgB9B,GACpC+B,EAAUhC,EAAoBiC,EAAAA,WAAWjC,QAAqB,EAC9DE,EAAmB6B,kBAAgB5B,GACnC+B,EAAUhC,EAAmB+B,EAAAA,WAAW/B,QAAoB,GAE3DiC,EAAMC,GAAWC,WAASC,EAAAA,eAAevC,EAAOF,EAAcmC,EAASE,KACvEK,GAAOC,IAAYH,WAAqC,OAIxDI,GAAcC,IAAmBL,WAASvC,GAE3C6C,GAAcC,SAAuB,MACrCC,GAAgBD,SAAuB,MAIvCE,GAAgBF,SAAiC,MACjDG,GAAWH,SAAgC,MAG3CI,GAAkBC,EAAAA,aACnBC,IACGH,GAASI,QAAUD,EACf3D,IACiC,mB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BD,IACrCyD,OAAQ,EAERC,SAAA,CAAAf,EAAAA,IAACU,EAAQM,QAAR,IACOhF,EACJ,cAAY,0BACZ1B,UAAU,+BACV2G,MAAO5D,GAAenB,EAAoBD,EAC1CiF,SAAU,EACV5B,QAASN,GACTjD,UAAWuC,GACX6C,SAAO,EAEPJ,SAACf,EAAAA,IAAAoB,EAAAA,WAAA,CACGL,SAACf,EAAAA,IAAAqB,EAAAA,aAAA,CAAa,aAGrBX,EAAQY,QAAR,CAAgBC,cAAc,EAAIC,QAAS,GACxCT,SAAAf,EAAAA,IAACyB,EAAAA,SAAA,CACGtB,IAAK5C,GACLlC,QAAAA,EACA0B,KAAAA,EACAH,QAAAA,EACAE,QAAAA,EACAxB,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAT,YAAAA,EACA0G,eAAgBnC,GAChBoC,aAAc5B,aAK1BM,KACR,IAMhBrG,EAAW4H,YAAc"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("date-fns
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("date-fns"),t=require("react"),a=require("./utils.js");function n(e){return void 0!==e}function s(e,{onClick:t,dateObj:n}){return{onClick:a.composeEventHandlers(t,(t=>{e(n,t)})),disabled:!n.selectable,"aria-pressed":n.selected,role:"button"}}function o({minDate:e,offsetMonth:t,handleOffsetChanged:n},{onClick:s,offset:o=1,calendars:r}){const d=`Gå tilbake ${o} måned${1===o?"":"er"}`;return{onClick:a.composeEventHandlers(s,(()=>{n(t-a.subtractMonth({calendars:r,offset:o,minDate:e}))})),disabled:a.isBackDisabled({calendars:r,minDate:e}),"aria-label":d,title:d}}function r({maxDate:e,offsetMonth:t,handleOffsetChanged:n},{onClick:s,offset:o=1,calendars:r}){const d=`Gå frem ${o} måned${1===o?"":"er"}`;return{onClick:a.composeEventHandlers(s,(()=>{n(t+a.addMonth({calendars:r,offset:o,maxDate:e}))})),disabled:a.isForwardDisabled({calendars:r,maxDate:e}),"aria-label":d,title:d}}exports.useCalendar=function({date:d=e.startOfDay(new Date),maxDate:l,minDate:i,monthsToDisplay:f=1,firstDayOfWeek:c=0,showOutsideDays:u=!0,offset:D,onDateSelected:h,onOffsetChanged:m,selected:b}){const[C,O]=t.useState(0),g=function(e,t){return n(e)?e:t}(D,C);function p(e){n(D)||O(e),m(e)}return{calendars:a.getCalendars({date:d,selected:b,monthsToDisplay:f,minDate:i,maxDate:l,offset:g,firstDayOfWeek:c,showOutsideDays:u}),getDateProps:s.bind(null,h),getBackProps:o.bind(null,{minDate:i,offsetMonth:g,handleOffsetChanged:p}),getForwardProps:r.bind(null,{maxDate:l,offsetMonth:g,handleOffsetChanged:p}),handleOffsetChanged:p}};
|
|
2
2
|
//# sourceMappingURL=useCalendar.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCalendar.js","sources":["../../../../../src/components/datepicker/internal/useCalendar.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport startOfDay from \"date-fns
|
|
1
|
+
{"version":3,"file":"useCalendar.js","sources":["../../../../../src/components/datepicker/internal/useCalendar.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport { startOfDay } from \"date-fns\";\nimport React, { useState } from \"react\";\nimport {\n composeEventHandlers,\n subtractMonth,\n addMonth,\n isBackDisabled,\n isForwardDisabled,\n getCalendars,\n DateInfo,\n CalendarMonth,\n} from \"./utils\";\n\nfunction isOffsetControlled(propOffset: number | undefined): boolean {\n return propOffset !== undefined;\n}\n\nfunction getOffset(prop: number, state: number): number {\n return isOffsetControlled(prop) ? prop : state;\n}\n\ntype BoundGetDateProps = (dateInfo: DateInfo, event: React.MouseEvent) => void;\n\ntype GetDateProps = {\n onClick?: React.MouseEventHandler;\n dateObj: DateInfo;\n};\n\ntype GetDatePropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-pressed\": boolean;\n role: \"button\";\n};\n\nfunction getDateProps(onDateSelected: BoundGetDateProps, { onClick, dateObj }: GetDateProps): GetDatePropsResult {\n return {\n onClick: composeEventHandlers(onClick, (event) => {\n onDateSelected(dateObj, event);\n }),\n disabled: !dateObj.selectable,\n \"aria-pressed\": dateObj.selected,\n role: \"button\",\n };\n}\n\ntype BoundGetBackProps = {\n handleOffsetChanged: (newOffset: number) => void;\n offsetMonth: number;\n minDate?: Date;\n};\n\ntype GetBackProps = {\n onClick?: React.MouseEventHandler;\n offset?: number;\n calendars: CalendarMonth[];\n};\n\ntype GetBackPropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-label\": string;\n title: string;\n};\n\nfunction getBackProps(\n { minDate, offsetMonth, handleOffsetChanged }: BoundGetBackProps,\n { onClick, offset = 1, calendars }: GetBackProps,\n): GetBackPropsResult {\n const label = `Gå tilbake ${offset} måned${offset === 1 ? \"\" : \"er\"}`;\n return {\n onClick: composeEventHandlers(onClick, () => {\n handleOffsetChanged(offsetMonth - subtractMonth({ calendars, offset, minDate }));\n }),\n disabled: isBackDisabled({ calendars, minDate }),\n \"aria-label\": label,\n title: label,\n };\n}\n\ntype BoundGetForwardProps = {\n handleOffsetChanged: (newOffset: number) => void;\n offsetMonth: number;\n maxDate?: Date;\n};\n\ntype GetForwardProps = {\n onClick?: React.MouseEventHandler;\n offset?: number;\n calendars: CalendarMonth[];\n};\n\ntype GetForwardPropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-label\": string;\n title: string;\n};\n\nfunction getForwardProps(\n { maxDate, offsetMonth, handleOffsetChanged }: BoundGetForwardProps,\n { onClick, offset = 1, calendars }: GetForwardProps,\n): GetForwardPropsResult {\n const label = `Gå frem ${offset} måned${offset === 1 ? \"\" : \"er\"}`;\n return {\n onClick: composeEventHandlers(onClick, () => {\n handleOffsetChanged(offsetMonth + addMonth({ calendars, offset, maxDate }));\n }),\n disabled: isForwardDisabled({ calendars, maxDate }),\n \"aria-label\": label,\n title: label,\n };\n}\n\nexport interface UseCalendarProps {\n date?: Date;\n maxDate?: Date;\n minDate?: Date;\n monthsToDisplay?: number;\n firstDayOfWeek?: number;\n showOutsideDays?: boolean;\n offset: number;\n onDateSelected: (dateObj: DateInfo, event: React.MouseEvent) => void;\n onOffsetChanged: (newOffset: number) => void;\n selected?: Date | Date[];\n}\n\nexport type GetDatePropsFunc = (props: GetDateProps) => GetDatePropsResult;\nexport type GetBackPropsFunc = (props: GetBackProps) => GetBackPropsResult;\nexport type GetForwardPropsFunc = (props: GetForwardProps) => GetForwardPropsResult;\nexport type HandleOffsetFunc = (newOffset: number) => void;\n\nexport type UseCalendarResult = {\n calendars: CalendarMonth[];\n getDateProps: GetDatePropsFunc;\n getBackProps: GetBackPropsFunc;\n getForwardProps: GetForwardPropsFunc;\n handleOffsetChanged: HandleOffsetFunc;\n};\n\nexport function useCalendar({\n date = startOfDay(new Date()),\n maxDate,\n minDate,\n monthsToDisplay = 1,\n firstDayOfWeek = 0,\n showOutsideDays = true,\n offset,\n onDateSelected,\n onOffsetChanged,\n selected,\n}: UseCalendarProps): UseCalendarResult {\n const [stateOffset, setStateOffset] = useState(0);\n const offsetMonth = getOffset(offset, stateOffset);\n\n function handleOffsetChanged(newOffset: number) {\n if (!isOffsetControlled(offset)) {\n setStateOffset(newOffset);\n }\n onOffsetChanged(newOffset);\n }\n\n const calendars = getCalendars({\n date,\n selected,\n monthsToDisplay,\n minDate,\n maxDate,\n offset: offsetMonth,\n firstDayOfWeek,\n showOutsideDays,\n });\n return {\n calendars,\n getDateProps: getDateProps.bind(null, onDateSelected),\n getBackProps: getBackProps.bind(null, {\n minDate,\n offsetMonth,\n handleOffsetChanged,\n }),\n getForwardProps: getForwardProps.bind(null, {\n maxDate,\n offsetMonth,\n handleOffsetChanged,\n }),\n handleOffsetChanged,\n };\n}\n"],"names":["isOffsetControlled","propOffset","getDateProps","onDateSelected","onClick","dateObj","composeEventHandlers","event","disabled","selectable","selected","role","getBackProps","minDate","offsetMonth","handleOffsetChanged","offset","calendars","label","subtractMonth","isBackDisabled","title","getForwardProps","maxDate","addMonth","isForwardDisabled","date","startOfDay","Date","monthsToDisplay","firstDayOfWeek","showOutsideDays","onOffsetChanged","stateOffset","setStateOffset","useState","prop","state","getOffset","newOffset","getCalendars","bind"],"mappings":"uJAoCA,SAASA,EAAmBC,GACxB,YAAsB,IAAfA,CACX,CAoBA,SAASC,EAAaC,GAAqCC,QAAAA,EAASC,QAAAA,IACzD,MAAA,CACHD,QAASE,EAAAA,qBAAqBF,GAAUG,IACpCJ,EAAeE,EAASE,EAAK,IAEjCC,UAAWH,EAAQI,WACnB,eAAgBJ,EAAQK,SACxBC,KAAM,SAEd,CAqBA,SAASC,GACHC,QAAAA,EAASC,YAAAA,EAAaC,oBAAAA,IACtBX,QAAAA,EAASY,OAAAA,EAAS,EAAGC,UAAAA,IAEvB,MAAMC,EAAQ,cAAcF,UAA0B,IAAXA,EAAe,GAAK,OACxD,MAAA,CACHZ,QAASE,EAAAA,qBAAqBF,GAAS,KACnCW,EAAoBD,EAAcK,gBAAc,CAAEF,UAAAA,EAAWD,OAAAA,EAAQH,QAAAA,IAAU,IAEnFL,SAAUY,EAAAA,eAAe,CAAEH,UAAAA,EAAWJ,QAAAA,IACtC,aAAcK,EACdG,MAAOH,EAEf,CAqBA,SAASI,GACHC,QAAAA,EAAST,YAAAA,EAAaC,oBAAAA,IACtBX,QAAAA,EAASY,OAAAA,EAAS,EAAGC,UAAAA,IAEvB,MAAMC,EAAQ,WAAWF,UAA0B,IAAXA,EAAe,GAAK,OACrD,MAAA,CACHZ,QAASE,EAAAA,qBAAqBF,GAAS,KACnCW,EAAoBD,EAAcU,WAAS,CAAEP,UAAAA,EAAWD,OAAAA,EAAQO,QAAAA,IAAU,IAE9Ef,SAAUiB,EAAAA,kBAAkB,CAAER,UAAAA,EAAWM,QAAAA,IACzC,aAAcL,EACdG,MAAOH,EAEf,qBA4BO,UACHQ,KAAAA,EAAOC,EAAAA,WAAe,IAAAC,MACtBL,QAAAA,EACAV,QAAAA,EACAgB,gBAAAA,EAAkB,EAClBC,eAAAA,EAAiB,EACjBC,gBAAAA,GAAkB,EAClBf,OAAAA,EACAb,eAAAA,EACA6B,gBAAAA,EACAtB,SAAAA,IAEA,MAAOuB,EAAaC,GAAkBC,WAAS,GACzCrB,EAxIV,SAAmBsB,EAAcC,GACtB,OAAArC,EAAmBoC,GAAQA,EAAOC,CAC7C,CAsIwBC,CAAUtB,EAAQiB,GAEtC,SAASlB,EAAoBwB,GACpBvC,EAAmBgB,IACpBkB,EAAeK,GAEnBP,EAAgBO,EACpB,CAYO,MAAA,CACHtB,UAXcuB,EAAAA,aAAa,CAC3Bd,KAAAA,EACAhB,SAAAA,EACAmB,gBAAAA,EACAhB,QAAAA,EACAU,QAAAA,EACAP,OAAQF,EACRgB,eAAAA,EACAC,gBAAAA,IAIA7B,aAAcA,EAAauC,KAAK,KAAMtC,GACtCS,aAAcA,EAAa6B,KAAK,KAAM,CAClC5B,QAAAA,EACAC,YAAAA,EACAC,oBAAAA,IAEJO,gBAAiBA,EAAgBmB,KAAK,KAAM,CACxClB,QAAAA,EACAT,YAAAA,EACAC,oBAAAA,IAEJA,oBAAAA,EAER"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("date-fns
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("date-fns"),e=require("../utils.js");function n({month:e,year:n,selectedDates:r,minDate:o,maxDate:l,firstDayOfWeek:i,showOutsideDays:f}){const u=function(t,e){const n=new Date(e,t,1);return t=n.getMonth(),e=n.getFullYear(),{daysInMonth:32-new Date(e,t,32).getDate(),month:t,year:e}}(e,n),D=u.daysInMonth;e=u.month,n=u.year;const c=[];for(let i=1;i<=D;i++){const f=new Date(n,e,i),u={date:f,selected:a(r,f),selectable:s(o,l,f),today:t.isToday(f),prevMonth:!1,nextMonth:!1};c.push(u)}const d=new Date(n,e,1),h=new Date(n,e,D),y=function({firstDayOfMonth:e,minDate:n,maxDate:r,selectedDates:o,firstDayOfWeek:l,showOutsideDays:i}){const f=[];let u=(e.getDay()+7-l)%7;if(i){const l=t.addDays(e,-1),i=l.getDate(),D=l.getMonth(),c=l.getFullYear();let d=0;for(;d<u;){const t=new Date(c,D,i-d),e={date:t,selected:a(o,t),selectable:s(n,r,t),today:!1,prevMonth:!0,nextMonth:!1};f.unshift(e),d++}}else for(;u>0;)f.unshift(""),u--;return f}({firstDayOfMonth:d,minDate:o,maxDate:l,selectedDates:r,firstDayOfWeek:i,showOutsideDays:f}),g=function({lastDayOfMonth:e,minDate:n,maxDate:r,selectedDates:o,firstDayOfWeek:l,showOutsideDays:i}){const f=[];let u=(e.getDay()+7-l)%7;if(i){const l=t.addDays(e,1),i=l.getMonth(),D=l.getFullYear();let c=0;for(;c<6-u;){const t=new Date(D,i,1+c),e={date:t,selected:a(o,t),selectable:s(n,r,t),today:!1,prevMonth:!1,nextMonth:!0};f.push(e),c++}}else for(;u<6;)f.push(""),u++;return f}({lastDayOfMonth:h,minDate:o,maxDate:l,selectedDates:r,firstDayOfWeek:i,showOutsideDays:f});c.unshift(...y),c.push(...g);const m=function(t){const e=Math.ceil(t.length/7),n=[];for(let a=0;a<e;a++){n[a]=[];for(let e=0;e<7;e++)n[a].push(t[7*a+e])}return n}(c);return{firstDayOfMonth:d,lastDayOfMonth:h,month:e,year:n,weeks:m}}function a(e,n){return!!e&&(e=Array.isArray(e)?e:[e]).some((e=>e instanceof Date&&t.startOfDay(e).getTime()===t.startOfDay(n).getTime()))}function s(e,n,a){return!(e&&t.isBefore(a,e)||n&&t.isBefore(n,a))}function r(t,e){return t.getDate()===e.getDate()&&t.getMonth()===e.getMonth()&&t.getFullYear()===e.getFullYear()}function o(t,e,n){return!!(n&&t>n||e&&t<e)}exports.DEFAULT_YEARS_TO_SHOW=3,exports.addMonth=function({calendars:e,offset:n,maxDate:a}){if(n>1&&a){const{lastDayOfMonth:s}=e[e.length-1],r=t.differenceInCalendarMonths(a,s);r<n&&(n=r)}return n},exports.composeEventHandlers=function(...t){return e=>t.some((t=>(t&&t(e),e.defaultPrevented)))},exports.dateHasChanged=function(t,e){return!t||!r(t,e)},exports.dateIsOutsideRange=o,exports.getCalendars=function({date:e,selected:a,monthsToDisplay:s,offset:r,minDate:o,maxDate:l,firstDayOfWeek:i,showOutsideDays:f}){const u=[],D=function(e,n,a){let s=t.startOfDay(e);if(n){const e=t.startOfDay(n);t.isBefore(s,e)&&(s=e)}if(a){const e=t.startOfDay(a);t.isBefore(e,s)&&(s=e)}return s}(e,o,l);for(let t=0;t<s;t++){const e=n({month:D.getMonth()+t+r,year:D.getFullYear(),selectedDates:a,minDate:o,maxDate:l,firstDayOfWeek:i,showOutsideDays:f});u.push(e)}return u},exports.getInitialDate=function(t,n,a,s){const r=e.parseDateString(t),l=e.parseDateString(n);return r?o(r,a,s)?null:r:l?o(l,a,s)?null:l:null},exports.getInitialDateShown=function(t,e,n,a){let s=t||e||new Date;return n&&(s=n>s?n:s),a&&(s=a<s?a:s),s},exports.getMonthSelectOptions=function(t,e,n,a){const s=(null==n?void 0:n.getFullYear())||t,r=void 0===(null==n?void 0:n.getMonth())?0:n.getMonth(),o=(null==a?void 0:a.getFullYear())||t,l=void 0===(null==a?void 0:a.getMonth())?11:a.getMonth();let i=0,f=11;return s===t&&(i=r),o===t&&(f=l),e.map(((t,e)=>({value:e.toString(),label:t}))).filter((({value:t})=>parseInt(t)>=i&&parseInt(t)<=f))},exports.getYearSelectOptions=function(t,e,n,a){if(e&&e.getFullYear()>t)return[e.getFullYear().toString()];if(n&&n.getFullYear()<t)return[n.getFullYear().toString()];let s,r,o=!1;"all"===a?(o=!0,s=3,r=3):(s="number"==typeof a?a:a.previous,r="number"==typeof a?a:a.coming);let l=t-s;if(e){const t=o?e.getFullYear():l;l=Math.max(e.getFullYear(),t)}let i=t+r;if(n){const t=o?n.getFullYear():i;i=Math.min(n.getFullYear(),t)}const f=Math.max(i-l+1,1);return[...Array(f).keys()].map((t=>t+l)).map((t=>t.toString()))},exports.isBackDisabled=function({calendars:e,minDate:n}){if(!n)return!1;const{firstDayOfMonth:a}=e[0],s=t.addDays(a,-1);return!!t.isBefore(s,n)},exports.isForwardDisabled=function({calendars:e,maxDate:n}){if(!n)return!1;const{lastDayOfMonth:a}=e[e.length-1],s=t.addDays(a,1);return!!t.isBefore(n,s)},exports.isSameDay=r,exports.subtractMonth=function({calendars:e,offset:n,minDate:a}){if(n>1&&a){const{firstDayOfMonth:s}=e[0],r=t.differenceInCalendarMonths(s,a);r<n&&(n=r)}return n};
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../../src/components/datepicker/internal/utils.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport addDays from \"date-fns/addDays\";\nimport differenceInCalendarMonths from \"date-fns/differenceInCalendarMonths\";\nimport isBefore from \"date-fns/isBefore\";\nimport isToday from \"date-fns/isToday\";\nimport startOfDay from \"date-fns/startOfDay\";\nimport React from \"react\";\nimport type { ValuePair } from \"../../../utilities\";\nimport type { YearsToShow } from \"../types\";\nimport { parseDateString } from \"../utils\";\n\nexport function composeEventHandlers(...fns: Array<React.MouseEventHandler | undefined>) {\n return (event: React.MouseEvent) =>\n fns.some((fn) => {\n fn && fn(event);\n return event.defaultPrevented;\n });\n}\n\n/**\n * Takes a calendars array and figures out the number of months to subtract\n * based on the current offset and the minDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Number} param.offset The num of months to be subtracted\n * @param {Date} param.minDate The earliest date we are allow to subtract back to\n * @returns {Number} The number of months to subtract\n */\nexport function subtractMonth({\n calendars,\n offset,\n minDate,\n}: {\n calendars: CalendarMonth[];\n offset: number;\n minDate?: Date;\n}): number {\n if (offset > 1 && minDate) {\n const { firstDayOfMonth } = calendars[0];\n const diffInMonths = differenceInCalendarMonths(firstDayOfMonth, minDate);\n if (diffInMonths < offset) {\n offset = diffInMonths;\n }\n }\n return offset;\n}\n\nexport const DEFAULT_YEARS_TO_SHOW = 3;\n\n/**\n * Generates an array of year strings for a year selector component, with min and max dates taken into account.\n *\n * @param {number} currentYear - The current year to center the list around\n * @param {Date | undefined} [minDate] - The minimum date to include in the list of years\n * @param {Date | undefined} [maxDate] - The maximum date to include in the list of years\n *\n * @returns {string[]} - An array of year strings, starting from the earliest year specified by minDate or currentYear - 3, and ending at the latest year specified by maxDate or currentYear + 3\n */\nexport function getYearSelectOptions(\n currentYear: number,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n yearsToShow: YearsToShow,\n): string[] {\n if (minDate && minDate.getFullYear() > currentYear) {\n return [minDate.getFullYear().toString()];\n }\n\n if (maxDate && maxDate.getFullYear() < currentYear) {\n return [maxDate.getFullYear().toString()];\n }\n\n let showAllYears = false;\n let previousYearsToShow: number;\n let comingYearsToShow: number;\n\n if (yearsToShow === \"all\") {\n showAllYears = true;\n previousYearsToShow = DEFAULT_YEARS_TO_SHOW;\n comingYearsToShow = DEFAULT_YEARS_TO_SHOW;\n } else {\n previousYearsToShow = typeof yearsToShow === \"number\" ? yearsToShow : yearsToShow.previous;\n comingYearsToShow = typeof yearsToShow === \"number\" ? yearsToShow : yearsToShow.coming;\n }\n\n let startYear = currentYear - previousYearsToShow;\n if (minDate) {\n const earliestStartYear = showAllYears ? minDate.getFullYear() : startYear;\n startYear = Math.max(minDate.getFullYear(), earliestStartYear);\n }\n\n let endYear = currentYear + comingYearsToShow;\n if (maxDate) {\n const latestEndYear = showAllYears ? maxDate.getFullYear() : endYear;\n endYear = Math.min(maxDate.getFullYear(), latestEndYear);\n }\n\n // Sørg for å alltid vise minst ett år\n const numYears = Math.max(endYear - startYear + 1, 1);\n\n const range = [...Array(numYears).keys()].map((x) => x + startYear);\n const stringRange = range.map((item) => item.toString());\n\n return stringRange;\n}\n\n/**\n * Returns an array of months that are allowed for selection in the current year based on the minimum and maximum dates.\n * @param {number} currentYear The current year\n * @param {string[]} monthNames An array of strings representing the month names\n * @param {Date | undefined} minDate The minimum date that is allowed for selection\n * @param {Date | undefined} maxDate The maximum date that is allowed for selection\n * @returns {ValuePair[]} An array of ValuePairs representing the months that are allowed for selection in the current year\n */\nexport function getMonthSelectOptions(\n currentYear: number,\n monthNames: string[],\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): ValuePair[] {\n const minDateYear = minDate?.getFullYear() || currentYear;\n const minDateMonth = minDate?.getMonth() === undefined ? 0 : minDate.getMonth();\n const maxDateYear = maxDate?.getFullYear() || currentYear;\n const maxDateMonth = maxDate?.getMonth() === undefined ? 11 : maxDate.getMonth();\n\n let startMonth = 0;\n let endMonth = 11;\n\n if (minDateYear === currentYear) {\n startMonth = minDateMonth;\n }\n if (maxDateYear === currentYear) {\n endMonth = maxDateMonth;\n }\n\n const filteredMonths = monthNames\n .map((month, index) => ({\n value: index.toString(),\n label: month,\n }))\n .filter(({ value }) => parseInt(value) >= startMonth && parseInt(value) <= endMonth);\n\n return filteredMonths;\n}\n\n/**s\n * Takes a calendars array and figures out the number of months to add\n * based on the current offset and the maxDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Number} param.offset The num of months to be added\n * @param {Date} param.maxDate The furthest date we are allow to add forward to\n * @returns {Number} The number of months to add\n */\nexport function addMonth({\n calendars,\n offset,\n maxDate,\n}: {\n calendars: CalendarMonth[];\n offset: number;\n maxDate?: Date;\n}): number {\n if (offset > 1 && maxDate) {\n const { lastDayOfMonth } = calendars[calendars.length - 1];\n const diffInMonths = differenceInCalendarMonths(maxDate, lastDayOfMonth);\n if (diffInMonths < offset) {\n offset = diffInMonths;\n }\n }\n return offset;\n}\n\n/**\n * Takes a calendars array and figures out if the back button should be\n * disabled based on the minDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Date} param.minDate The earliest date available\n * @returns {Boolean} Whether the back button should be disabled.\n */\nexport function isBackDisabled({ calendars, minDate }: { calendars: CalendarMonth[]; minDate?: Date }): boolean {\n if (!minDate) {\n return false;\n }\n const { firstDayOfMonth } = calendars[0];\n const firstDayOfMonthMinusOne = addDays(firstDayOfMonth, -1);\n if (isBefore(firstDayOfMonthMinusOne, minDate)) {\n return true;\n }\n return false;\n}\n\n/**\n * Takes a calendars array and figures out if the forward button should be\n * disabled based on the maxDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Date} param.maxDate The furthest date available\n * @returns {Boolean} Whether the forward button should be disabled.\n */\nexport function isForwardDisabled({ calendars, maxDate }: { calendars: CalendarMonth[]; maxDate?: Date }): boolean {\n if (!maxDate) {\n return false;\n }\n const { lastDayOfMonth } = calendars[calendars.length - 1];\n const lastDayOfMonthPlusOne = addDays(lastDayOfMonth, 1);\n if (isBefore(maxDate, lastDayOfMonthPlusOne)) {\n return true;\n }\n return false;\n}\n\ntype GetCalendarProps = {\n /** The date to start the calendar at */\n date: Date;\n /** Date or dates currently selected. */\n selected?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** The number of months to return in the calendar view */\n monthsToDisplay: number;\n /** The number of months to offset based off the param.date given */\n offset: number;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Figures out the months data needed based off the number of monthsToDisplay\n * and other options provided.\n * @param {Object} param The param object\n * @param {Date} param.date The date to start the calendar at\n * @param {Array.<Date>} param.selected An array of dates currently selected\n * @param {Number} param.monthsToDisplay The number of months to return in the calendar view\n * @param {Number} param.offset The number of months to offset based off the param.date given\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Object>} An array of objects with month data\n */\nexport function getCalendars({\n date,\n selected,\n monthsToDisplay,\n offset,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n}: GetCalendarProps): CalendarMonth[] {\n const months: CalendarMonth[] = [];\n const startDate = getStartDate(date, minDate, maxDate);\n for (let i = 0; i < monthsToDisplay; i++) {\n const calendarDates = getMonths({\n month: startDate.getMonth() + i + offset,\n year: startDate.getFullYear(),\n selectedDates: selected,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n });\n months.push(calendarDates);\n }\n return months;\n}\n\n/**\n * Figures out the actual start date based on\n * the min and max dates available.\n * @param {Date} date The we want to start the calendar at\n * @param {Date} minDate The earliest date available to start at\n * @param {Date} maxDate The latest date available to start at\n * @returns {Date} The actual start date\n */\nfunction getStartDate(date: Date, minDate?: Date, maxDate?: Date): Date {\n let startDate = startOfDay(date);\n if (minDate) {\n const minDateNormalized = startOfDay(minDate);\n if (isBefore(startDate, minDateNormalized)) {\n startDate = minDateNormalized;\n }\n }\n if (maxDate) {\n const maxDateNormalized = startOfDay(maxDate);\n if (isBefore(maxDateNormalized, startDate)) {\n startDate = maxDateNormalized;\n }\n }\n return startDate;\n}\n\ntype GetMonthsProps = {\n /** The month to grab data for */\n month: number;\n /** The year to grab data for */\n year: number;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\nexport type CalendarMonth = {\n firstDayOfMonth: Date;\n lastDayOfMonth: Date;\n month: number;\n year: number;\n weeks: CalendarWeek[];\n};\n\nexport type CalendarWeek = CalendarDay[];\n\nexport type CalendarDay = DateInfo | string;\n\n/**\n * Figures what week/day data to return for the given month\n * and year. Adds flags to day data if found in the given selectedDates,\n * if is selectable inside the given min and max dates, or is today.\n * @param {Object} param The param object\n * @param {Number} param.month The month to grab data for\n * @param {Number} param.year The year to grab data for\n * @param {Array.<Date>} sparam.electedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Object} The data for the selected month/year\n */\nfunction getMonths({\n month,\n year,\n selectedDates,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n}: GetMonthsProps): CalendarMonth {\n // Get the normalized month and year, along with days in the month.\n const daysMonthYear = getNumDaysMonthYear(month, year);\n const daysInMonth = daysMonthYear.daysInMonth;\n month = daysMonthYear.month;\n year = daysMonthYear.year;\n\n // Fill out the dates for the month.\n const dates = [];\n for (let day = 1; day <= daysInMonth; day++) {\n const date = new Date(year, month, day);\n const dateObj = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: isToday(date),\n prevMonth: false,\n nextMonth: false,\n };\n dates.push(dateObj);\n }\n\n const firstDayOfMonth = new Date(year, month, 1);\n const lastDayOfMonth = new Date(year, month, daysInMonth);\n\n const frontWeekBuffer = fillFrontWeek({\n firstDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n });\n\n const backWeekBuffer = fillBackWeek({\n lastDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n });\n\n dates.unshift(...frontWeekBuffer);\n dates.push(...backWeekBuffer);\n\n // Get the filled out weeks for the\n // given dates.\n const weeks = getWeeks(dates);\n // return the calendar data.\n return {\n firstDayOfMonth,\n lastDayOfMonth,\n month,\n year,\n weeks,\n };\n}\n\ntype FillFrontWeekProps = {\n firstDayOfMonth: Date;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Fill front week with either empty buffer or dates from previous month,\n * depending on showOutsideDays flag\n * @param {Object} param The param object\n * @param {Array.<Date>} param.selectedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Date} param.firstDayOfMonth First day of the month\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Date>} Buffer to fill front week\n */\nfunction fillFrontWeek({\n firstDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n}: FillFrontWeekProps): CalendarWeek {\n const dates: CalendarWeek = [];\n let firstDay = (firstDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7;\n\n if (showOutsideDays) {\n const lastDayOfPrevMonth = addDays(firstDayOfMonth, -1);\n const prevDate = lastDayOfPrevMonth.getDate();\n const prevDateMonth = lastDayOfPrevMonth.getMonth();\n const prevDateYear = lastDayOfPrevMonth.getFullYear();\n\n // Fill out front week for days from\n // preceding month with dates from previous month.\n let counter = 0;\n while (counter < firstDay) {\n const date = new Date(prevDateYear, prevDateMonth, prevDate - counter);\n const dateObj: DateInfo = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: false,\n prevMonth: true,\n nextMonth: false,\n };\n dates.unshift(dateObj);\n counter++;\n }\n } else {\n // Fill out front week for days from\n // preceding month with buffer.\n while (firstDay > 0) {\n dates.unshift(\"\");\n firstDay--;\n }\n }\n\n return dates;\n}\n\nexport type DateInfo = {\n date: Date;\n selected: boolean;\n selectable: boolean;\n today: boolean;\n prevMonth: boolean;\n nextMonth: boolean;\n};\n\ntype FillBackWeekProps = {\n lastDayOfMonth: Date;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Fill back weeks with either empty buffer or dates from next month,\n * depending on showOutsideDays flag\n * @param {Object} param The param object\n * @param {Array.<Date>} param.selectedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Date} param.lastDayOfMonth Last day of the month\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Date>} Buffer to fill back week\n */\nfunction fillBackWeek({\n lastDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n}: FillBackWeekProps): CalendarWeek {\n const dates: CalendarWeek = [];\n let lastDay = (lastDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7;\n\n if (showOutsideDays) {\n const firstDayOfNextMonth = addDays(lastDayOfMonth, 1);\n const nextDateMonth = firstDayOfNextMonth.getMonth();\n const nextDateYear = firstDayOfNextMonth.getFullYear();\n\n // Fill out back week for days from\n // following month with dates from next month.\n let counter = 0;\n while (counter < 6 - lastDay) {\n const date = new Date(nextDateYear, nextDateMonth, 1 + counter);\n const dateObj: DateInfo = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: false,\n prevMonth: false,\n nextMonth: true,\n };\n dates.push(dateObj);\n counter++;\n }\n } else {\n // Fill out back week for days from\n // following month with buffer.\n while (lastDay < 6) {\n dates.push(\"\");\n lastDay++;\n }\n }\n\n return dates;\n}\n\n/**\n * Normalizes month (could be overflow) and year pairs and returns the\n * normalized month and year along with the number of days in the month.\n * @param {Number} month The month to normalize\n * @param {Number} year The year to normalize\n * @returns {Object} The normalized month and year along with the number of days in the month\n */\nfunction getNumDaysMonthYear(month: number, year: number): { daysInMonth: number; month: number; year: number } {\n // If a parameter you specify is outside of the expected range for Month or Day,\n // JS Date attempts to update the date information in the Date object accordingly!\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate\n\n // Let Date handle the overflow of the month,\n // which should return the normalized month and year.\n const normalizedMonthYear = new Date(year, month, 1);\n month = normalizedMonthYear.getMonth();\n year = normalizedMonthYear.getFullYear();\n // Overflow the date to the next month, then subtract the difference\n // to get the number of days in the previous month.\n // This will also account for leap years!\n const daysInMonth = 32 - new Date(year, month, 32).getDate();\n return { daysInMonth, month, year };\n}\n\n/**\n * Takes an array of dates, and turns them into a multi dimensional\n * array with 7 entries for each week.\n * @param {Array.<Object>} dates An array of dates\n * @returns {Array} The weeks as a multi dimensional array\n */\nfunction getWeeks(dates: CalendarWeek): Array<CalendarWeek> {\n const weeksLength = Math.ceil(dates.length / 7);\n const weeks: Array<CalendarWeek> = [];\n for (let i = 0; i < weeksLength; i++) {\n weeks[i] = [];\n for (let x = 0; x < 7; x++) {\n weeks[i].push(dates[i * 7 + x]);\n }\n }\n return weeks;\n}\n\n/**\n * Normalizes dates to the beginning of the day,\n * then checks to see if the day given is found\n * in the selectedDates.\n * @param {Array.<Date>} selectedDates An array of dates currently selected\n * @param {Date} date The date to search with against selectedDates\n * @returns {Boolean} Whether day is found in selectedDates\n */\nfunction isSelected(selectedDates: Date | Date[] | undefined, date: Date): boolean {\n if (!selectedDates) {\n return false;\n }\n selectedDates = Array.isArray(selectedDates) ? selectedDates : [selectedDates];\n return selectedDates.some((selectedDate) => {\n if (selectedDate instanceof Date && startOfDay(selectedDate).getTime() === startOfDay(date).getTime()) {\n return true;\n }\n return false;\n });\n}\n\n/**\n * Checks to see if the date given is\n * between the min and max dates.\n * @param {Date} minDate The earliest date available\n * @param {Date} maxDate The furthest date available\n * @param {Date} date The date to compare with\n * @returns {Boolean} Whether the date is between min and max date\n */\nfunction isSelectable(minDate: Date | undefined, maxDate: Date | undefined, date: Date): boolean {\n if ((minDate && isBefore(date, minDate)) || (maxDate && isBefore(maxDate, date))) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if two Date objects represent the same day\n *\n * @param date1 first Date to compare\n * @param date2 second Date to compare\n */\nexport function isSameDay(date1: Date, date2: Date): boolean {\n return (\n date1.getDate() === date2.getDate() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getFullYear() === date2.getFullYear()\n );\n}\n\n/**\n * Check if the date has changed from the previous date\n *\n * @param date First date to compare\n * @param newDate Second date to compare\n */\nexport function dateHasChanged(date: Date | undefined, newDate: Date): boolean {\n return !date || !isSameDay(date, newDate);\n}\n\n/**\n * Check if a given date is outside a given range\n *\n * @param date Input date\n * @param rangeStart Dates before this date should be disabled\n * @param rangeEnd Dates after this date should be disabled\n */\nexport function dateIsOutsideRange(date: Date, rangeStart: Date | undefined, rangeEnd: Date | undefined): boolean {\n return Boolean((rangeEnd && date > rangeEnd) || (rangeStart && date < rangeStart));\n}\n\n/**\n * Get the correct initial date for initiating the datepicker reducer store\n *\n * @param value Value from props\n * @param initialDate Initial date from porps\n * @param disableDate Function for checking whether the date should be disabled\n */\nexport function getInitialDate(\n value: string | undefined,\n defaultValue: string | undefined,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): Date | null {\n const valueAsDate = parseDateString(value);\n const defaultValueAsDate = parseDateString(defaultValue);\n if (valueAsDate) {\n return !dateIsOutsideRange(valueAsDate, minDate, maxDate) ? valueAsDate : null;\n }\n if (defaultValueAsDate) {\n return !dateIsOutsideRange(defaultValueAsDate, minDate, maxDate) ? defaultValueAsDate : null;\n }\n return null;\n}\n\n/**\n * Get the initial date to show in the calendar\n *\n * @param date The date set in the DatePicker (from props)\n * @param defaultSelected The defaultSelected prop from DatePicker\n * @param minDate The earliest selectable date, from props\n * @param maxDate The latest selectable date, from props\n * @returns The date to show in the calendar\n */\nexport function getInitialDateShown(\n date: Date | null,\n defaultSelected: Date | undefined,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): Date {\n let initialDate = date || defaultSelected || new Date();\n\n if (minDate) {\n initialDate = minDate > initialDate ? minDate : initialDate;\n }\n\n if (maxDate) {\n initialDate = maxDate < initialDate ? maxDate : initialDate;\n }\n\n return initialDate;\n}\n"],"names":["getMonths","month","year","selectedDates","minDate","maxDate","firstDayOfWeek","showOutsideDays","daysMonthYear","normalizedMonthYear","Date","getMonth","getFullYear","daysInMonth","getDate","getNumDaysMonthYear","dates","day","date","dateObj","selected","isSelected","selectable","isSelectable","today","isToday","prevMonth","nextMonth","push","firstDayOfMonth","lastDayOfMonth","frontWeekBuffer","firstDay","getDay","lastDayOfPrevMonth","addDays","prevDate","prevDateMonth","prevDateYear","counter","unshift","fillFrontWeek","backWeekBuffer","lastDay","firstDayOfNextMonth","nextDateMonth","nextDateYear","fillBackWeek","weeks","weeksLength","Math","ceil","length","i","x","getWeeks","Array","isArray","some","selectedDate","startOfDay","getTime","isBefore","isSameDay","date1","date2","dateIsOutsideRange","rangeStart","rangeEnd","calendars","offset","diffInMonths","differenceInCalendarMonths","fns","event","fn","defaultPrevented","newDate","monthsToDisplay","months","startDate","minDateNormalized","maxDateNormalized","getStartDate","calendarDates","value","defaultValue","valueAsDate","parseDateString","defaultValueAsDate","defaultSelected","initialDate","currentYear","monthNames","minDateYear","minDateMonth","maxDateYear","maxDateMonth","startMonth","endMonth","map","index","toString","label","filter","parseInt","yearsToShow","previousYearsToShow","comingYearsToShow","showAllYears","previous","coming","startYear","earliestStartYear","max","endYear","latestEndYear","min","numYears","keys","item","firstDayOfMonthMinusOne","lastDayOfMonthPlusOne"],"mappings":"4RA4WA,SAASA,GACLC,MAAAA,EACAC,KAAAA,EACAC,cAAAA,EACAC,QAAAA,EACAC,QAAAA,EACAC,eAAAA,EACAC,gBAAAA,IAGM,MAAAC,EAsNV,SAA6BP,EAAeC,GAQxC,MAAMO,EAAsB,IAAIC,KAAKR,EAAMD,EAAO,GAClD,OAAAA,EAAQQ,EAAoBE,WAC5BT,EAAOO,EAAoBG,cAKpB,CAAEC,YADW,GAAK,IAAIH,KAAKR,EAAMD,EAAO,IAAIa,UAC7Bb,MAAAA,EAAOC,KAAAA,EACjC,CAtO0Ba,CAAoBd,EAAOC,GAC3CW,EAAcL,EAAcK,YAClCZ,EAAQO,EAAcP,MACtBC,EAAOM,EAAcN,KAGrB,MAAMc,EAAQ,GACd,IAASC,IAAAA,EAAM,EAAGA,GAAOJ,EAAaI,I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CACvB,MAAQyB,gBAAAA,GAAoBwC,EAAU,GAChCE,EAAeC,EAA2B3C,EAAiBzB,GAC7DmE,EAAeD,IACNA,EAAAC,EAEjB,CACO,OAAAD,CACX"}
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../../src/components/datepicker/internal/utils.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { addDays, differenceInCalendarMonths, isBefore, isToday, startOfDay } from \"date-fns\";\nimport React from \"react\";\nimport type { ValuePair } from \"../../../utilities\";\nimport type { YearsToShow } from \"../types\";\nimport { parseDateString } from \"../utils\";\n\nexport function composeEventHandlers(...fns: Array<React.MouseEventHandler | undefined>) {\n return (event: React.MouseEvent) =>\n fns.some((fn) => {\n fn && fn(event);\n return event.defaultPrevented;\n });\n}\n\n/**\n * Takes a calendars array and figures out the number of months to subtract\n * based on the current offset and the minDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Number} param.offset The num of months to be subtracted\n * @param {Date} param.minDate The earliest date we are allow to subtract back to\n * @returns {Number} The number of months to subtract\n */\nexport function subtractMonth({\n calendars,\n offset,\n minDate,\n}: {\n calendars: CalendarMonth[];\n offset: number;\n minDate?: Date;\n}): number {\n if (offset > 1 && minDate) {\n const { firstDayOfMonth } = calendars[0];\n const diffInMonths = differenceInCalendarMonths(firstDayOfMonth, minDate);\n if (diffInMonths < offset) {\n offset = diffInMonths;\n }\n }\n return offset;\n}\n\nexport const DEFAULT_YEARS_TO_SHOW = 3;\n\n/**\n * Generates an array of year strings for a year selector component, with min and max dates taken into account.\n *\n * @param {number} currentYear - The current year to center the list around\n * @param {Date | undefined} [minDate] - The minimum date to include in the list of years\n * @param {Date | undefined} [maxDate] - The maximum date to include in the list of years\n *\n * @returns {string[]} - An array of year strings, starting from the earliest year specified by minDate or currentYear - 3, and ending at the latest year specified by maxDate or currentYear + 3\n */\nexport function getYearSelectOptions(\n currentYear: number,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n yearsToShow: YearsToShow,\n): string[] {\n if (minDate && minDate.getFullYear() > currentYear) {\n return [minDate.getFullYear().toString()];\n }\n\n if (maxDate && maxDate.getFullYear() < currentYear) {\n return [maxDate.getFullYear().toString()];\n }\n\n let showAllYears = false;\n let previousYearsToShow: number;\n let comingYearsToShow: number;\n\n if (yearsToShow === \"all\") {\n showAllYears = true;\n previousYearsToShow = DEFAULT_YEARS_TO_SHOW;\n comingYearsToShow = DEFAULT_YEARS_TO_SHOW;\n } else {\n previousYearsToShow = typeof yearsToShow === \"number\" ? yearsToShow : yearsToShow.previous;\n comingYearsToShow = typeof yearsToShow === \"number\" ? yearsToShow : yearsToShow.coming;\n }\n\n let startYear = currentYear - previousYearsToShow;\n if (minDate) {\n const earliestStartYear = showAllYears ? minDate.getFullYear() : startYear;\n startYear = Math.max(minDate.getFullYear(), earliestStartYear);\n }\n\n let endYear = currentYear + comingYearsToShow;\n if (maxDate) {\n const latestEndYear = showAllYears ? maxDate.getFullYear() : endYear;\n endYear = Math.min(maxDate.getFullYear(), latestEndYear);\n }\n\n // Sørg for å alltid vise minst ett år\n const numYears = Math.max(endYear - startYear + 1, 1);\n\n const range = [...Array(numYears).keys()].map((x) => x + startYear);\n const stringRange = range.map((item) => item.toString());\n\n return stringRange;\n}\n\n/**\n * Returns an array of months that are allowed for selection in the current year based on the minimum and maximum dates.\n * @param {number} currentYear The current year\n * @param {string[]} monthNames An array of strings representing the month names\n * @param {Date | undefined} minDate The minimum date that is allowed for selection\n * @param {Date | undefined} maxDate The maximum date that is allowed for selection\n * @returns {ValuePair[]} An array of ValuePairs representing the months that are allowed for selection in the current year\n */\nexport function getMonthSelectOptions(\n currentYear: number,\n monthNames: string[],\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): ValuePair[] {\n const minDateYear = minDate?.getFullYear() || currentYear;\n const minDateMonth = minDate?.getMonth() === undefined ? 0 : minDate.getMonth();\n const maxDateYear = maxDate?.getFullYear() || currentYear;\n const maxDateMonth = maxDate?.getMonth() === undefined ? 11 : maxDate.getMonth();\n\n let startMonth = 0;\n let endMonth = 11;\n\n if (minDateYear === currentYear) {\n startMonth = minDateMonth;\n }\n if (maxDateYear === currentYear) {\n endMonth = maxDateMonth;\n }\n\n const filteredMonths = monthNames\n .map((month, index) => ({\n value: index.toString(),\n label: month,\n }))\n .filter(({ value }) => parseInt(value) >= startMonth && parseInt(value) <= endMonth);\n\n return filteredMonths;\n}\n\n/**s\n * Takes a calendars array and figures out the number of months to add\n * based on the current offset and the maxDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Number} param.offset The num of months to be added\n * @param {Date} param.maxDate The furthest date we are allow to add forward to\n * @returns {Number} The number of months to add\n */\nexport function addMonth({\n calendars,\n offset,\n maxDate,\n}: {\n calendars: CalendarMonth[];\n offset: number;\n maxDate?: Date;\n}): number {\n if (offset > 1 && maxDate) {\n const { lastDayOfMonth } = calendars[calendars.length - 1];\n const diffInMonths = differenceInCalendarMonths(maxDate, lastDayOfMonth);\n if (diffInMonths < offset) {\n offset = diffInMonths;\n }\n }\n return offset;\n}\n\n/**\n * Takes a calendars array and figures out if the back button should be\n * disabled based on the minDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Date} param.minDate The earliest date available\n * @returns {Boolean} Whether the back button should be disabled.\n */\nexport function isBackDisabled({ calendars, minDate }: { calendars: CalendarMonth[]; minDate?: Date }): boolean {\n if (!minDate) {\n return false;\n }\n const { firstDayOfMonth } = calendars[0];\n const firstDayOfMonthMinusOne = addDays(firstDayOfMonth, -1);\n if (isBefore(firstDayOfMonthMinusOne, minDate)) {\n return true;\n }\n return false;\n}\n\n/**\n * Takes a calendars array and figures out if the forward button should be\n * disabled based on the maxDate allowed.\n * @param {Object} param The param object\n * @param {Array} param.calendars The calendars array created by the getCalendars function\n * @param {Date} param.maxDate The furthest date available\n * @returns {Boolean} Whether the forward button should be disabled.\n */\nexport function isForwardDisabled({ calendars, maxDate }: { calendars: CalendarMonth[]; maxDate?: Date }): boolean {\n if (!maxDate) {\n return false;\n }\n const { lastDayOfMonth } = calendars[calendars.length - 1];\n const lastDayOfMonthPlusOne = addDays(lastDayOfMonth, 1);\n if (isBefore(maxDate, lastDayOfMonthPlusOne)) {\n return true;\n }\n return false;\n}\n\ntype GetCalendarProps = {\n /** The date to start the calendar at */\n date: Date;\n /** Date or dates currently selected. */\n selected?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** The number of months to return in the calendar view */\n monthsToDisplay: number;\n /** The number of months to offset based off the param.date given */\n offset: number;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Figures out the months data needed based off the number of monthsToDisplay\n * and other options provided.\n * @param {Object} param The param object\n * @param {Date} param.date The date to start the calendar at\n * @param {Array.<Date>} param.selected An array of dates currently selected\n * @param {Number} param.monthsToDisplay The number of months to return in the calendar view\n * @param {Number} param.offset The number of months to offset based off the param.date given\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Object>} An array of objects with month data\n */\nexport function getCalendars({\n date,\n selected,\n monthsToDisplay,\n offset,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n}: GetCalendarProps): CalendarMonth[] {\n const months: CalendarMonth[] = [];\n const startDate = getStartDate(date, minDate, maxDate);\n for (let i = 0; i < monthsToDisplay; i++) {\n const calendarDates = getMonths({\n month: startDate.getMonth() + i + offset,\n year: startDate.getFullYear(),\n selectedDates: selected,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n });\n months.push(calendarDates);\n }\n return months;\n}\n\n/**\n * Figures out the actual start date based on\n * the min and max dates available.\n * @param {Date} date The we want to start the calendar at\n * @param {Date} minDate The earliest date available to start at\n * @param {Date} maxDate The latest date available to start at\n * @returns {Date} The actual start date\n */\nfunction getStartDate(date: Date, minDate?: Date, maxDate?: Date): Date {\n let startDate = startOfDay(date);\n if (minDate) {\n const minDateNormalized = startOfDay(minDate);\n if (isBefore(startDate, minDateNormalized)) {\n startDate = minDateNormalized;\n }\n }\n if (maxDate) {\n const maxDateNormalized = startOfDay(maxDate);\n if (isBefore(maxDateNormalized, startDate)) {\n startDate = maxDateNormalized;\n }\n }\n return startDate;\n}\n\ntype GetMonthsProps = {\n /** The month to grab data for */\n month: number;\n /** The year to grab data for */\n year: number;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\nexport type CalendarMonth = {\n firstDayOfMonth: Date;\n lastDayOfMonth: Date;\n month: number;\n year: number;\n weeks: CalendarWeek[];\n};\n\nexport type CalendarWeek = CalendarDay[];\n\nexport type CalendarDay = DateInfo | string;\n\n/**\n * Figures what week/day data to return for the given month\n * and year. Adds flags to day data if found in the given selectedDates,\n * if is selectable inside the given min and max dates, or is today.\n * @param {Object} param The param object\n * @param {Number} param.month The month to grab data for\n * @param {Number} param.year The year to grab data for\n * @param {Array.<Date>} sparam.electedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Object} The data for the selected month/year\n */\nfunction getMonths({\n month,\n year,\n selectedDates,\n minDate,\n maxDate,\n firstDayOfWeek,\n showOutsideDays,\n}: GetMonthsProps): CalendarMonth {\n // Get the normalized month and year, along with days in the month.\n const daysMonthYear = getNumDaysMonthYear(month, year);\n const daysInMonth = daysMonthYear.daysInMonth;\n month = daysMonthYear.month;\n year = daysMonthYear.year;\n\n // Fill out the dates for the month.\n const dates = [];\n for (let day = 1; day <= daysInMonth; day++) {\n const date = new Date(year, month, day);\n const dateObj = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: isToday(date),\n prevMonth: false,\n nextMonth: false,\n };\n dates.push(dateObj);\n }\n\n const firstDayOfMonth = new Date(year, month, 1);\n const lastDayOfMonth = new Date(year, month, daysInMonth);\n\n const frontWeekBuffer = fillFrontWeek({\n firstDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n });\n\n const backWeekBuffer = fillBackWeek({\n lastDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n });\n\n dates.unshift(...frontWeekBuffer);\n dates.push(...backWeekBuffer);\n\n // Get the filled out weeks for the\n // given dates.\n const weeks = getWeeks(dates);\n // return the calendar data.\n return {\n firstDayOfMonth,\n lastDayOfMonth,\n month,\n year,\n weeks,\n };\n}\n\ntype FillFrontWeekProps = {\n firstDayOfMonth: Date;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Fill front week with either empty buffer or dates from previous month,\n * depending on showOutsideDays flag\n * @param {Object} param The param object\n * @param {Array.<Date>} param.selectedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Date} param.firstDayOfMonth First day of the month\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Date>} Buffer to fill front week\n */\nfunction fillFrontWeek({\n firstDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n}: FillFrontWeekProps): CalendarWeek {\n const dates: CalendarWeek = [];\n let firstDay = (firstDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7;\n\n if (showOutsideDays) {\n const lastDayOfPrevMonth = addDays(firstDayOfMonth, -1);\n const prevDate = lastDayOfPrevMonth.getDate();\n const prevDateMonth = lastDayOfPrevMonth.getMonth();\n const prevDateYear = lastDayOfPrevMonth.getFullYear();\n\n // Fill out front week for days from\n // preceding month with dates from previous month.\n let counter = 0;\n while (counter < firstDay) {\n const date = new Date(prevDateYear, prevDateMonth, prevDate - counter);\n const dateObj: DateInfo = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: false,\n prevMonth: true,\n nextMonth: false,\n };\n dates.unshift(dateObj);\n counter++;\n }\n } else {\n // Fill out front week for days from\n // preceding month with buffer.\n while (firstDay > 0) {\n dates.unshift(\"\");\n firstDay--;\n }\n }\n\n return dates;\n}\n\nexport type DateInfo = {\n date: Date;\n selected: boolean;\n selectable: boolean;\n today: boolean;\n prevMonth: boolean;\n nextMonth: boolean;\n};\n\ntype FillBackWeekProps = {\n lastDayOfMonth: Date;\n /** Date or dates currently selected. */\n selectedDates?: Date | Date[];\n /** The earliest date available */\n minDate?: Date;\n /** The earliest date available */\n maxDate?: Date;\n /** First day of week, 0-6 (Sunday to Saturday) */\n firstDayOfWeek: number;\n /** Flag to fill front and back weeks with dates from adjacent months */\n showOutsideDays: boolean;\n};\n\n/**\n * Fill back weeks with either empty buffer or dates from next month,\n * depending on showOutsideDays flag\n * @param {Object} param The param object\n * @param {Array.<Date>} param.selectedDates An array of dates currently selected\n * @param {Date} param.minDate The earliest date available\n * @param {Date} param.maxDate The furthest date available\n * @param {Date} param.lastDayOfMonth Last day of the month\n * @param {Number} param.firstDayOfWeek First day of week, 0-6 (Sunday to Saturday)\n * @param {Bool} param.showOutsideDays Flag to fill front and back weeks with dates from adjacent months\n * @returns {Array.<Date>} Buffer to fill back week\n */\nfunction fillBackWeek({\n lastDayOfMonth,\n minDate,\n maxDate,\n selectedDates,\n firstDayOfWeek,\n showOutsideDays,\n}: FillBackWeekProps): CalendarWeek {\n const dates: CalendarWeek = [];\n let lastDay = (lastDayOfMonth.getDay() + 7 - firstDayOfWeek) % 7;\n\n if (showOutsideDays) {\n const firstDayOfNextMonth = addDays(lastDayOfMonth, 1);\n const nextDateMonth = firstDayOfNextMonth.getMonth();\n const nextDateYear = firstDayOfNextMonth.getFullYear();\n\n // Fill out back week for days from\n // following month with dates from next month.\n let counter = 0;\n while (counter < 6 - lastDay) {\n const date = new Date(nextDateYear, nextDateMonth, 1 + counter);\n const dateObj: DateInfo = {\n date,\n selected: isSelected(selectedDates, date),\n selectable: isSelectable(minDate, maxDate, date),\n today: false,\n prevMonth: false,\n nextMonth: true,\n };\n dates.push(dateObj);\n counter++;\n }\n } else {\n // Fill out back week for days from\n // following month with buffer.\n while (lastDay < 6) {\n dates.push(\"\");\n lastDay++;\n }\n }\n\n return dates;\n}\n\n/**\n * Normalizes month (could be overflow) and year pairs and returns the\n * normalized month and year along with the number of days in the month.\n * @param {Number} month The month to normalize\n * @param {Number} year The year to normalize\n * @returns {Object} The normalized month and year along with the number of days in the month\n */\nfunction getNumDaysMonthYear(month: number, year: number): { daysInMonth: number; month: number; year: number } {\n // If a parameter you specify is outside of the expected range for Month or Day,\n // JS Date attempts to update the date information in the Date object accordingly!\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate\n\n // Let Date handle the overflow of the month,\n // which should return the normalized month and year.\n const normalizedMonthYear = new Date(year, month, 1);\n month = normalizedMonthYear.getMonth();\n year = normalizedMonthYear.getFullYear();\n // Overflow the date to the next month, then subtract the difference\n // to get the number of days in the previous month.\n // This will also account for leap years!\n const daysInMonth = 32 - new Date(year, month, 32).getDate();\n return { daysInMonth, month, year };\n}\n\n/**\n * Takes an array of dates, and turns them into a multi dimensional\n * array with 7 entries for each week.\n * @param {Array.<Object>} dates An array of dates\n * @returns {Array} The weeks as a multi dimensional array\n */\nfunction getWeeks(dates: CalendarWeek): Array<CalendarWeek> {\n const weeksLength = Math.ceil(dates.length / 7);\n const weeks: Array<CalendarWeek> = [];\n for (let i = 0; i < weeksLength; i++) {\n weeks[i] = [];\n for (let x = 0; x < 7; x++) {\n weeks[i].push(dates[i * 7 + x]);\n }\n }\n return weeks;\n}\n\n/**\n * Normalizes dates to the beginning of the day,\n * then checks to see if the day given is found\n * in the selectedDates.\n * @param {Array.<Date>} selectedDates An array of dates currently selected\n * @param {Date} date The date to search with against selectedDates\n * @returns {Boolean} Whether day is found in selectedDates\n */\nfunction isSelected(selectedDates: Date | Date[] | undefined, date: Date): boolean {\n if (!selectedDates) {\n return false;\n }\n selectedDates = Array.isArray(selectedDates) ? selectedDates : [selectedDates];\n return selectedDates.some((selectedDate) => {\n if (selectedDate instanceof Date && startOfDay(selectedDate).getTime() === startOfDay(date).getTime()) {\n return true;\n }\n return false;\n });\n}\n\n/**\n * Checks to see if the date given is\n * between the min and max dates.\n * @param {Date} minDate The earliest date available\n * @param {Date} maxDate The furthest date available\n * @param {Date} date The date to compare with\n * @returns {Boolean} Whether the date is between min and max date\n */\nfunction isSelectable(minDate: Date | undefined, maxDate: Date | undefined, date: Date): boolean {\n if ((minDate && isBefore(date, minDate)) || (maxDate && isBefore(maxDate, date))) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if two Date objects represent the same day\n *\n * @param date1 first Date to compare\n * @param date2 second Date to compare\n */\nexport function isSameDay(date1: Date, date2: Date): boolean {\n return (\n date1.getDate() === date2.getDate() &&\n date1.getMonth() === date2.getMonth() &&\n date1.getFullYear() === date2.getFullYear()\n );\n}\n\n/**\n * Check if the date has changed from the previous date\n *\n * @param date First date to compare\n * @param newDate Second date to compare\n */\nexport function dateHasChanged(date: Date | undefined, newDate: Date): boolean {\n return !date || !isSameDay(date, newDate);\n}\n\n/**\n * Check if a given date is outside a given range\n *\n * @param date Input date\n * @param rangeStart Dates before this date should be disabled\n * @param rangeEnd Dates after this date should be disabled\n */\nexport function dateIsOutsideRange(date: Date, rangeStart: Date | undefined, rangeEnd: Date | undefined): boolean {\n return Boolean((rangeEnd && date > rangeEnd) || (rangeStart && date < rangeStart));\n}\n\n/**\n * Get the correct initial date for initiating the datepicker reducer store\n *\n * @param value Value from props\n * @param initialDate Initial date from porps\n * @param disableDate Function for checking whether the date should be disabled\n */\nexport function getInitialDate(\n value: string | undefined,\n defaultValue: string | undefined,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): Date | null {\n const valueAsDate = parseDateString(value);\n const defaultValueAsDate = parseDateString(defaultValue);\n if (valueAsDate) {\n return !dateIsOutsideRange(valueAsDate, minDate, maxDate) ? valueAsDate : null;\n }\n if (defaultValueAsDate) {\n return !dateIsOutsideRange(defaultValueAsDate, minDate, maxDate) ? defaultValueAsDate : null;\n }\n return null;\n}\n\n/**\n * Get the initial date to show in the calendar\n *\n * @param date The date set in the DatePicker (from props)\n * @param defaultSelected The defaultSelected prop from DatePicker\n * @param minDate The earliest selectable date, from props\n * @param maxDate The latest selectable date, from props\n * @returns The date to show in the calendar\n */\nexport function getInitialDateShown(\n date: Date | null,\n defaultSelected: Date | undefined,\n minDate: Date | undefined,\n maxDate: Date | undefined,\n): Date {\n let initialDate = date || defaultSelected || new Date();\n\n if (minDate) {\n initialDate = minDate > initialDate ? minDate : initialDate;\n }\n\n if (maxDate) {\n initialDate = maxDate < initialDate ? maxDate : initialDate;\n }\n\n return initialDate;\n}\n"],"names":["getMonths","month","year","selectedDates","minDate","maxDate","firstDayOfWeek","showOutsideDays","daysMonthYear","normalizedMonthYear","Date","getMonth","getFullYear","daysInMonth","getDate","getNumDaysMonthYear","dates","day","date","dateObj","selected","isSelected","selectable","isSelectable","today","isToday","prevMonth","nextMonth","push","firstDayOfMonth","lastDayOfMonth","frontWeekBuffer","firstDay","getDay","lastDayOfPrevMonth","addDays","prevDate","prevDateMonth","prevDateYear","counter","unshift","fillFrontWeek","backWeekBuffer","lastDay","firstDayOfNextMonth","nextDateMonth","nextDateYear","fillBackWeek","weeks","weeksLength","Math","ceil","length","i","x","getWeeks","Array","isArray","some","selectedDate","startOfDay","getTime","isBefore","isSameDay","date1","date2","dateIsOutsideRange","rangeStart","rangeEnd","calendars","offset","diffInMonths","differenceInCalendarMonths","fns","event","fn","defaultPrevented","newDate","monthsToDisplay","months","startDate","minDateNormalized","maxDateNormalized","getStartDate","calendarDates","value","defaultValue","valueAsDate","parseDateString","defaultValueAsDate","defaultSelected","initialDate","currentYear","monthNames","minDateYear","minDateMonth","maxDateYear","maxDateMonth","startMonth","endMonth","map","index","toString","label","filter","parseInt","yearsToShow","previousYearsToShow","comingYearsToShow","showAllYears","previous","coming","startYear","earliestStartYear","max","endYear","latestEndYear","min","numYears","keys","item","firstDayOfMonthMinusOne","lastDayOfMonthPlusOne"],"mappings":"qIAwWA,SAASA,GACLC,MAAAA,EACAC,KAAAA,EACAC,cAAAA,EACAC,QAAAA,EACAC,QAAAA,EACAC,eAAAA,EACAC,gBAAAA,IAGM,MAAAC,EAsNV,SAA6BP,EAAeC,GAQxC,MAAMO,EAAsB,IAAIC,KAAKR,EAAMD,EAAO,GAClD,OAAAA,EAAQQ,EAAoBE,WAC5BT,EAAOO,EAAoBG,cAKpB,CAAEC,YADW,GAAK,IAAIH,KAAKR,EAAMD,EAAO,IAAIa,UAC7Bb,MAAAA,EAAOC,KAAAA,EACjC,CAtO0Ba,CAAoBd,EAAOC,GAC3CW,EAAcL,EAAcK,YAClCZ,EAAQO,EAAcP,MACtBC,EAAOM,EAAcN,KAGrB,MAAMc,EAAQ,GACd,QAASC,EAAM,EAAGA,GAAOJ,EAAaI,IAAO,CACzC,MAAMC,EAAO,IAAIR,KAAKR,EAAMD,EAAOgB,GAC7BE,EAAU,CACZD,KAAAA,EACAE,SAAUC,EAAWlB,EAAee,GACpCI,WAAYC,EAAanB,EAASC,EAASa,GAC3CM,MAAOC,UAAQP,GACfQ,WAAW,EACXC,WAAW,GAEfX,EAAMY,KAAKT,EACf,CAEA,MAAMU,EAAkB,IAAInB,KAAKR,EAAMD,EAAO,GACxC6B,EAAiB,IAAIpB,KAAKR,EAAMD,EAAOY,GAEvCkB,EA4DV,UACIF,gBAAAA,EACAzB,QAAAA,EACAC,QAAAA,EACAF,cAAAA,EACAG,eAAAA,EACAC,gBAAAA,IAEA,MAAMS,EAAsB,GAC5B,IAAIgB,GAAYH,EAAgBI,SAAW,EAAI3B,GAAkB,EAEjE,GAAIC,EAAiB,CACX,MAAA2B,EAAqBC,EAAQA,QAAAN,GAAiB,GAC9CO,EAAWF,EAAmBp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G,EAAgBP,EAAexG,EAAQO,cAAgBuG,EAC7DA,EAAUjE,KAAKmE,IAAIhH,EAAQO,cAAewG,EAC9C,CAGA,MAAME,EAAWpE,KAAKgE,IAAIC,EAAUH,EAAY,EAAG,GAK5C,MAHO,IAAIxD,MAAM8D,GAAUC,QAAQnB,KAAK9C,GAAMA,EAAI0D,IAC/BZ,KAAKoB,GAASA,EAAKlB,YAGjD,yBA6EO,UAA0BjC,UAAAA,EAAWjE,QAAAA,IACxC,IAAKA,EACM,OAAA,EAEX,MAAQyB,gBAAAA,GAAoBwC,EAAU,GAChCoD,EAA0BtF,EAAQA,QAAAN,GAAiB,GACrD,QAAAiC,EAAAA,SAAS2D,EAAyBrH,EAI1C,4BAUO,UAA6BiE,UAAAA,EAAWhE,QAAAA,IAC3C,IAAKA,EACM,OAAA,EAEX,MAAQyB,eAAAA,GAAmBuC,EAAUA,EAAUjB,OAAS,GAClDsE,EAAwBvF,EAAAA,QAAQL,EAAgB,GAClD,QAAAgC,EAAAA,SAASzD,EAASqH,EAI1B,4CAvLO,UACHrD,UAAAA,EACAC,OAAAA,EACAlE,QAAAA,IAMI,GAAAkE,EAAS,GAAKlE,EAAS,CACvB,MAAQyB,gBAAAA,GAAoBwC,EAAU,GAChCE,EAAeC,EAAAA,2BAA2B3C,EAAiBzB,GAC7DmE,EAAeD,IACNA,EAAAC,EAEjB,CACO,OAAAD,CACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as o,jsxs as n}from"react/jsx-runtime";import{c as e}from"../../../clsx-BeLtu-UY.js";import t
|
|
1
|
+
import{jsx as o,jsxs as n}from"react/jsx-runtime";import{c as e}from"../../../clsx-BeLtu-UY.js";import{startOfDay as t}from"date-fns";import{forwardRef as r,useState as i,useRef as s,useCallback as a}from"react";import{flushSync as c}from"react-dom";import"../icon/Icon.js";import"../icon/icons/animated/ArrowVerticalAnimated.js";import"../icon/icons/animated/ArrowHorizontalAnimated.js";import"../icon/icons/animated/PlusRemoveAnimated.js";import"../icon/icons/ArrowDownIcon.js";import"../icon/icons/ArrowLeftIcon.js";import"../icon/icons/ArrowNorthEastIcon.js";import"../icon/icons/ArrowRightIcon.js";import"../icon/icons/ArrowUpIcon.js";import{CalendarIcon as l}from"../icon/icons/CalendarIcon.js";import"../icon/icons/CheckIcon.js";import"../icon/icons/ChevronDownIcon.js";import"../icon/icons/ChevronLeftIcon.js";import"../icon/icons/ChevronRightIcon.js";import"../icon/icons/ChevronUpIcon.js";import"../icon/icons/CloseIcon.js";import"../icon/icons/CopyIcon.js";import"../icon/icons/DotsIcon.js";import"../icon/icons/DragIcon.js";import"../icon/icons/ErrorIcon.js";import"../icon/icons/GreenCheckIcon.js";import"../icon/icons/HamburgerIcon.js";import"../icon/icons/InfoIcon.js";import"../icon/icons/LinkIcon.js";import"../icon/icons/PlusIcon.js";import"../icon/icons/QuestionIcon.js";import"../icon/icons/RedCrossIcon.js";import"../icon/icons/SearchIcon.js";import"../icon/icons/SuccessIcon.js";import"../icon/icons/WarningIcon.js";import"../icon/icons/MinusIcon.js";import"../icon/icons/ThumbDownIcon.js";import"../icon/icons/ThumbUpIcon.js";import"../icon/icons/TrashCanIcon.js";import"../icon/icons/PenIcon.js";import{IconButton as p}from"../icon-button/IconButton.js";import"../../hooks/useScreen/useScreen.js";import"../../hooks/useId/useId.js";import"../tooltip/Tooltip.js";import"../tooltip/TooltipContent.js";import"../tooltip/TooltipTrigger.js";import{InputGroup as u}from"../input-group/InputGroup.js";import m from"../popover/Popover.js";import"../text-input/BaseTextArea.js";import{BaseTextInput as d}from"../text-input/BaseTextInput.js";import"../text-input/TextArea.js";import"../text-input/TextInput.js";import{Calendar as j}from"./internal/Calendar.js";import{getInitialDate as I}from"./internal/utils.js";import{parseDateString as f,formatInput as h}from"./utils.js";import{isWithinLowerBound as v,isWithinUpperBound as k}from"./validation.js";const b=r(((r,b)=>{const{"data-testautoid":g,id:D,className:C="",label:w="Velg dato",labelProps:y,defaultValue:T,defaultShow:L=!1,value:x,disableBeforeDate:P,disableAfterDate:A,yearsToShow:S,name:B,helpLabel:E,errorLabel:_,invalid:N,density:O,days:R,months:U,monthLabel:V,yearLabel:W,placeholder:F="dd.mm.åååå",width:G="11.25rem",onChange:H,onBlur:K,onFocus:M,onKeyDown:q,action:z,showCalendarLabel:Q="Åpne kalender",hideCalendarLabel:J="Lukk kalender",supportLabelProps:X,tooltipProps:Y,...Z}=r;"production"!==process.env.NODE_ENV&&x&&T&&console.warn("DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.");const $=f(P),oo=$?t($):void 0,no=f(A),eo=no?t(no):void 0,[to,ro]=i(I(x,T,oo,eo)),[io,so]=i(null),[ao,co]=i(L),lo=s(null),po=s(null),uo=s(null),mo=s(null),jo=a((o=>{mo.current=o,b&&("function"==typeof b?b(o):b.current=o)}),[mo,b]),Io=a((o=>{M&&po.current&&(po.current.contains(o.relatedTarget)||M(o,to,{error:io,value:o.target.value}))}),[M,to,io]),fo=a((o=>{K&&K(o,to,{error:io,value:o.target.value})}),[K,to,io]),ho=a((o=>{"Escape"===o.key&&(co(!1),o.preventDefault(),o.stopPropagation()),null!=z&&z.onKeyDown&&z.onKeyDown(o)}),[co,z]),vo=a((o=>{let n=null,e=null;if(o.target.value){const t=f(o.target.value);t?oo&&!v(t,oo)?e="OUTSIDE_LOWER_BOUND":eo&&!k(t,eo)?e="OUTSIDE_UPPER_BOUND":co(!1):e="WRONG_FORMAT",n=t||null}so(e),ro(n),H&&H(o,n,{error:e,value:o.target.value})}),[H,so,ro,co,oo,eo]),ko=a((o=>{c((()=>{co(!ao)}));const n=lo.current,e=n&&n.querySelector('[aria-pressed="true"]');e&&e.focus(),null!=z&&z.onClick&&z.onClick(o)}),[co,ao,z,lo]),bo=a((({date:o})=>{if(co(!1),ro(o),mo.current){const n=mo.current;n.value=h(o);const e=document.createEvent("HTMLEvents");e.initEvent("input",!0,!1),n.dispatchEvent(e),n.focus(),H&&H(e,o,{error:null,value:n.value})}}),[co,ro,H]),go=a((o=>{o.preventDefault(),co(!1),uo.current&&uo.current.focus()}),[co]);return o(u,{id:D,className:e("jkl-datepicker",C,{"jkl-datepicker--open":ao}),...Z,ref:po,label:w,labelProps:y,density:O,helpLabel:E,errorLabel:_,supportLabelProps:X,tooltipProps:Y,render:e=>o(d,{ref:jo,"data-testid":"jkl-datepicker__input","data-testautoid":g,className:"jkl-datepicker__input",name:B,defaultValue:T,density:O,value:x,type:"text",placeholder:F,width:G,onFocus:Io,onBlur:fo,onChange:vo,actionButton:n(m,{positionReference:mo,open:ao,onOpenChange:()=>co(!ao),offset:8,children:[o(m.Trigger,{...z,"data-testid":"jkl-datepicker__trigger",className:"jkl-text-input-action-button",title:ao?J:Q,tabIndex:0,onClick:ko,onKeyDown:ho,asChild:!0,children:o(p,{children:o(l,{})})}),o(m.Content,{initialFocus:-1,padding:24,children:o(j,{ref:lo,density:O,date:to,minDate:oo,maxDate:eo,days:R,months:U,monthLabel:V,yearLabel:W,yearsToShow:S,onDateSelected:bo,onTabOutside:go})})]}),...e})})}));b.displayName="DatePicker";export{b as DatePicker};
|
|
2
2
|
//# sourceMappingURL=DatePicker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker.js","sources":["../../../../src/components/datepicker/DatePicker.tsx"],"sourcesContent":["import clsx from \"clsx\";\nimport startOfDay from \"date-fns/startOfDay\";\nimport React, {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n forwardRef,\n useCallback,\n useRef,\n useState,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { CalendarIcon } from \"../icon\";\nimport { IconButton } from \"../icon-button\";\nimport { InputGroup } from \"../input-group\";\nimport { Popover } from \"../popover\";\nimport { BaseTextInput } from \"../text-input\";\nimport { Calendar } from \"./internal/Calendar\";\nimport { getInitialDate, DateInfo } from \"./internal/utils\";\nimport { DatePickerProps, DateValidationError } from \"./types\";\nimport { formatInput, parseDateString } from \"./utils\";\nimport { isWithinLowerBound, isWithinUpperBound } from \"./validation\";\n\nexport const DatePicker = forwardRef<HTMLInputElement, DatePickerProps>((props, forwardedInputRef) => {\n const {\n \"data-testautoid\": testAutoId,\n id,\n className = \"\",\n label = \"Velg dato\",\n labelProps,\n defaultValue,\n defaultShow = false,\n value,\n disableBeforeDate: disableBefore,\n disableAfterDate: disableAfter,\n yearsToShow,\n name,\n helpLabel,\n errorLabel,\n invalid,\n density,\n days,\n months,\n monthLabel,\n yearLabel,\n placeholder = \"dd.mm.åååå\",\n width = \"11.25rem\",\n onChange,\n onBlur,\n onFocus,\n onKeyDown,\n action,\n showCalendarLabel = \"Åpne kalender\",\n hideCalendarLabel = \"Lukk kalender\",\n supportLabelProps,\n tooltipProps,\n ...rest\n } = props;\n\n if (process.env.NODE_ENV !== \"production\" && value && defaultValue) {\n console.warn(\n \"DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.\",\n );\n }\n /// Input state\n\n const disableBeforeDate = parseDateString(disableBefore);\n const minDate = disableBeforeDate ? startOfDay(disableBeforeDate) : undefined;\n const disableAfterDate = parseDateString(disableAfter);\n const maxDate = disableAfterDate ? startOfDay(disableAfterDate) : undefined;\n\n const [date, setDate] = useState(getInitialDate(value, defaultValue, minDate, maxDate));\n const [error, setError] = useState<DateValidationError | null>(null);\n\n /// Calendar state\n\n const [showCalendar, setShowCalendar] = useState(defaultShow);\n\n const calendarRef = useRef<HTMLDivElement>(null);\n const datepickerRef = useRef<HTMLDivElement>(null);\n\n /// Input events\n\n const iconButtonRef = useRef<HTMLButtonElement | null>(null);\n const inputRef = useRef<HTMLInputElement | null>(null);\n\n // Hjelper for å gjøre det enklere å både forwarde refen men også bruke den selv internt\n const unifiedInputRef = useCallback(\n (instance: HTMLInputElement | null) => {\n inputRef.current = instance;\n if (forwardedInputRef) {\n if (typeof forwardedInputRef === \"function\") {\n forwardedInputRef(instance);\n } else {\n forwardedInputRef.current = instance;\n }\n }\n },\n [inputRef, forwardedInputRef],\n );\n\n const handleFocus = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (!onFocus || !datepickerRef.current) {\n return;\n }\n\n const nextFocusIsInside = datepickerRef.current.contains(e.relatedTarget as Node);\n if (!nextFocusIsInside) {\n onFocus(e, date, { error, value: e.target.value });\n }\n },\n [onFocus, date, error],\n );\n\n const handleBlur = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (onBlur) {\n onBlur(e, date, { error, value: e.target.value });\n }\n },\n [onBlur, date, error],\n );\n\n const handleKeyDownAction = useCallback(\n (e: React.KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === \"Escape\") {\n setShowCalendar(false);\n e.preventDefault();\n e.stopPropagation();\n }\n\n if (action?.onKeyDown) {\n action.onKeyDown(e);\n }\n },\n [setShowCalendar, action],\n );\n\n const handleChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n let nextDate: Date | null = null;\n let nextError: DateValidationError | null = null;\n\n if (e.target.value) {\n const val = parseDateString(e.target.value);\n if (!val) {\n nextError = \"WRONG_FORMAT\";\n } else if (minDate && !isWithinLowerBound(val, minDate)) {\n nextError = \"OUTSIDE_LOWER_BOUND\";\n } else if (maxDate && !isWithinUpperBound(val, maxDate)) {\n nextError = \"OUTSIDE_UPPER_BOUND\";\n } else {\n setShowCalendar(false);\n }\n nextDate = val || null;\n }\n\n setError(nextError);\n setDate(nextDate);\n\n if (onChange) {\n onChange(e, nextDate, { error: nextError, value: e.target.value });\n }\n },\n [onChange, setError, setDate, setShowCalendar, minDate, maxDate],\n );\n\n /// Calendar events\n\n const clickCalendar = useCallback(\n (e: MouseEvent<HTMLButtonElement>) => {\n flushSync(() => {\n setShowCalendar(!showCalendar);\n });\n\n const calendarEl = calendarRef.current;\n const button = calendarEl && (calendarEl.querySelector('[aria-pressed=\"true\"]') as HTMLButtonElement);\n button && button.focus();\n\n if (action?.onClick) {\n action.onClick(e);\n }\n },\n [setShowCalendar, showCalendar, action, calendarRef],\n );\n\n const handleClickCalendarDay = useCallback(\n ({ date }: DateInfo) => {\n setShowCalendar(false);\n setDate(date);\n\n if (inputRef.current) {\n const node = inputRef.current;\n\n node.value = formatInput(date);\n\n // Simulér et change-event så APIet blir så likt som mulig en endring av inputfeltet\n const event = document.createEvent(\"HTMLEvents\");\n event.initEvent(\"input\", true, false);\n node.dispatchEvent(event);\n\n node.focus();\n\n if (onChange) {\n // Det er ikke helt sant at dette er et React.SyntheticEvent, men it's fine – probably?\n // Den har tingene man kan forvente, men hvis du gjør serdeles fancy ting med events\n // så kan det hende du må utvide denne for å dekke behovet ditt.\n onChange(event as unknown as ChangeEvent<HTMLInputElement>, date, {\n error: null,\n value: node.value,\n });\n }\n }\n },\n [setShowCalendar, setDate, onChange],\n );\n\n const handleTabOutsideCalendar = useCallback(\n (e: KeyboardEvent) => {\n e.preventDefault();\n setShowCalendar(false);\n iconButtonRef.current && iconButtonRef.current.focus();\n },\n [setShowCalendar],\n );\n\n return (\n <InputGroup\n id={id}\n className={clsx(\"jkl-datepicker\", className, {\n \"jkl-datepicker--open\": showCalendar,\n })}\n {...rest}\n ref={datepickerRef}\n label={label}\n labelProps={labelProps}\n density={density}\n helpLabel={helpLabel}\n errorLabel={errorLabel}\n supportLabelProps={supportLabelProps}\n tooltipProps={tooltipProps}\n render={(inputProps) => (\n <BaseTextInput\n ref={unifiedInputRef}\n data-testid=\"jkl-datepicker__input\"\n data-testautoid={testAutoId}\n className=\"jkl-datepicker__input\"\n name={name}\n defaultValue={defaultValue}\n density={density}\n value={value}\n type=\"text\"\n placeholder={placeholder}\n width={width}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onChange={handleChange}\n actionButton={\n <Popover\n positionReference={inputRef}\n open={showCalendar}\n onOpenChange={() => setShowCalendar(!showCalendar)}\n offset={8}\n >\n <Popover.Trigger\n {...action}\n data-testid=\"jkl-datepicker__trigger\"\n className=\"jkl-text-input-action-button\"\n title={showCalendar ? hideCalendarLabel : showCalendarLabel}\n tabIndex={0}\n onClick={clickCalendar}\n onKeyDown={handleKeyDownAction}\n asChild\n >\n <IconButton>\n <CalendarIcon />\n </IconButton>\n </Popover.Trigger>\n <Popover.Content initialFocus={-1} padding={24}>\n <Calendar\n ref={calendarRef}\n density={density}\n date={date}\n minDate={minDate}\n maxDate={maxDate}\n days={days}\n months={months}\n monthLabel={monthLabel}\n yearLabel={yearLabel}\n yearsToShow={yearsToShow}\n onDateSelected={handleClickCalendarDay}\n onTabOutside={handleTabOutsideCalendar}\n />\n </Popover.Content>\n </Popover>\n }\n {...inputProps}\n />\n )}\n />\n );\n});\n\nDatePicker.displayName = \"DatePicker\";\n"],"names":["DatePicker","forwardRef","props","forwardedInputRef","testAutoId","id","className","label","labelProps","defaultValue","defaultShow","value","disableBeforeDate","disableBefore","disableAfterDate","disableAfter","yearsToShow","name","helpLabel","errorLabel","invalid","density","days","months","monthLabel","yearLabel","placeholder","width","onChange","onBlur","onFocus","onKeyDown","action","showCalendarLabel","hideCalendarLabel","supportLabelProps","tooltipProps","rest","process","env","NODE_ENV","console","warn","parseDateString","minDate","startOfDay","maxDate","date","setDate","useState","getInitialDate","error","setError","showCalendar","setShowCalendar","calendarRef","useRef","datepickerRef","iconButtonRef","inputRef","unifiedInputRef","useCallback","instance","current","handleFocus","e","contains","relatedTarget","target","handleBlur","handleKeyDownAction","key","preventDefault","stopPropagation","handleChange","nextDate","nextError","val","isWithinLowerBound","isWithinUpperBound","clickCalendar","flushSync","calendarEl","button","querySelector","focus","onClick","handleClickCalendarDay","node","formatInput","event","document","createEvent","initEvent","dispatchEvent","handleTabOutsideCalendar","jsx","InputGroup","clsx","ref","render","inputProps","BaseTextInput","type","actionButton","jsxs","Popover","positionReference","open","onOpenChange","offset","children","Trigger","title","tabIndex","asChild","IconButton","CalendarIcon","Content","initialFocus","padding","Calendar","onDateSelected","onTabOutside","displayName"],"mappings":"4zEAwBO,MAAMA,EAAaC,GAA8C,CAACC,EAAOC,KACtE,MACF,kBAA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AA,GACAxB,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAT,YAAAA,EACA0G,eAAgBnC,GAChBoC,aAAc5B,aAK1BM,KACR,IAMhBrG,EAAW4H,YAAc"}
|
|
1
|
+
{"version":3,"file":"DatePicker.js","sources":["../../../../src/components/datepicker/DatePicker.tsx"],"sourcesContent":["import clsx from \"clsx\";\nimport { startOfDay } from \"date-fns\";\nimport React, {\n ChangeEvent,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n forwardRef,\n useCallback,\n useRef,\n useState,\n} from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { CalendarIcon } from \"../icon\";\nimport { IconButton } from \"../icon-button\";\nimport { InputGroup } from \"../input-group\";\nimport { Popover } from \"../popover\";\nimport { BaseTextInput } from \"../text-input\";\nimport { Calendar } from \"./internal/Calendar\";\nimport { getInitialDate, DateInfo } from \"./internal/utils\";\nimport { DatePickerProps, DateValidationError } from \"./types\";\nimport { formatInput, parseDateString } from \"./utils\";\nimport { isWithinLowerBound, isWithinUpperBound } from \"./validation\";\n\nexport const DatePicker = forwardRef<HTMLInputElement, DatePickerProps>((props, forwardedInputRef) => {\n const {\n \"data-testautoid\": testAutoId,\n id,\n className = \"\",\n label = \"Velg dato\",\n labelProps,\n defaultValue,\n defaultShow = false,\n value,\n disableBeforeDate: disableBefore,\n disableAfterDate: disableAfter,\n yearsToShow,\n name,\n helpLabel,\n errorLabel,\n invalid,\n density,\n days,\n months,\n monthLabel,\n yearLabel,\n placeholder = \"dd.mm.åååå\",\n width = \"11.25rem\",\n onChange,\n onBlur,\n onFocus,\n onKeyDown,\n action,\n showCalendarLabel = \"Åpne kalender\",\n hideCalendarLabel = \"Lukk kalender\",\n supportLabelProps,\n tooltipProps,\n ...rest\n } = props;\n\n if (process.env.NODE_ENV !== \"production\" && value && defaultValue) {\n console.warn(\n \"DatePicker må enten være controlled eller uncontrolled. Hvis du bruker defaultValue og value sammen vil defaultValue bli ignorert.\",\n );\n }\n /// Input state\n\n const disableBeforeDate = parseDateString(disableBefore);\n const minDate = disableBeforeDate ? startOfDay(disableBeforeDate) : undefined;\n const disableAfterDate = parseDateString(disableAfter);\n const maxDate = disableAfterDate ? startOfDay(disableAfterDate) : undefined;\n\n const [date, setDate] = useState(getInitialDate(value, defaultValue, minDate, maxDate));\n const [error, setError] = useState<DateValidationError | null>(null);\n\n /// Calendar state\n\n const [showCalendar, setShowCalendar] = useState(defaultShow);\n\n const calendarRef = useRef<HTMLDivElement>(null);\n const datepickerRef = useRef<HTMLDivElement>(null);\n\n /// Input events\n\n const iconButtonRef = useRef<HTMLButtonElement | null>(null);\n const inputRef = useRef<HTMLInputElement | null>(null);\n\n // Hjelper for å gjøre det enklere å både forwarde refen men også bruke den selv internt\n const unifiedInputRef = useCallback(\n (instance: HTMLInputElement | null) => {\n inputRef.current = instance;\n if (forwardedInputRef) {\n if (typeof forwardedInputRef === \"function\") {\n forwardedInputRef(instance);\n } else {\n forwardedInputRef.current = instance;\n }\n }\n },\n [inputRef, forwardedInputRef],\n );\n\n const handleFocus = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (!onFocus || !datepickerRef.current) {\n return;\n }\n\n const nextFocusIsInside = datepickerRef.current.contains(e.relatedTarget as Node);\n if (!nextFocusIsInside) {\n onFocus(e, date, { error, value: e.target.value });\n }\n },\n [onFocus, date, error],\n );\n\n const handleBlur = useCallback(\n (e: FocusEvent<HTMLInputElement>) => {\n if (onBlur) {\n onBlur(e, date, { error, value: e.target.value });\n }\n },\n [onBlur, date, error],\n );\n\n const handleKeyDownAction = useCallback(\n (e: React.KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === \"Escape\") {\n setShowCalendar(false);\n e.preventDefault();\n e.stopPropagation();\n }\n\n if (action?.onKeyDown) {\n action.onKeyDown(e);\n }\n },\n [setShowCalendar, action],\n );\n\n const handleChange = useCallback(\n (e: ChangeEvent<HTMLInputElement>) => {\n let nextDate: Date | null = null;\n let nextError: DateValidationError | null = null;\n\n if (e.target.value) {\n const val = parseDateString(e.target.value);\n if (!val) {\n nextError = \"WRONG_FORMAT\";\n } else if (minDate && !isWithinLowerBound(val, minDate)) {\n nextError = \"OUTSIDE_LOWER_BOUND\";\n } else if (maxDate && !isWithinUpperBound(val, maxDate)) {\n nextError = \"OUTSIDE_UPPER_BOUND\";\n } else {\n setShowCalendar(false);\n }\n nextDate = val || null;\n }\n\n setError(nextError);\n setDate(nextDate);\n\n if (onChange) {\n onChange(e, nextDate, { error: nextError, value: e.target.value });\n }\n },\n [onChange, setError, setDate, setShowCalendar, minDate, maxDate],\n );\n\n /// Calendar events\n\n const clickCalendar = useCallback(\n (e: MouseEvent<HTMLButtonElement>) => {\n flushSync(() => {\n setShowCalendar(!showCalendar);\n });\n\n const calendarEl = calendarRef.current;\n const button = calendarEl && (calendarEl.querySelector('[aria-pressed=\"true\"]') as HTMLButtonElement);\n button && button.focus();\n\n if (action?.onClick) {\n action.onClick(e);\n }\n },\n [setShowCalendar, showCalendar, action, calendarRef],\n );\n\n const handleClickCalendarDay = useCallback(\n ({ date }: DateInfo) => {\n setShowCalendar(false);\n setDate(date);\n\n if (inputRef.current) {\n const node = inputRef.current;\n\n node.value = formatInput(date);\n\n // Simulér et change-event så APIet blir så likt som mulig en endring av inputfeltet\n const event = document.createEvent(\"HTMLEvents\");\n event.initEvent(\"input\", true, false);\n node.dispatchEvent(event);\n\n node.focus();\n\n if (onChange) {\n // Det er ikke helt sant at dette er et React.SyntheticEvent, men it's fine – probably?\n // Den har tingene man kan forvente, men hvis du gjør serdeles fancy ting med events\n // så kan det hende du må utvide denne for å dekke behovet ditt.\n onChange(event as unknown as ChangeEvent<HTMLInputElement>, date, {\n error: null,\n value: node.value,\n });\n }\n }\n },\n [setShowCalendar, setDate, onChange],\n );\n\n const handleTabOutsideCalendar = useCallback(\n (e: KeyboardEvent) => {\n e.preventDefault();\n setShowCalendar(false);\n iconButtonRef.current && iconButtonRef.current.focus();\n },\n [setShowCalendar],\n );\n\n return (\n <InputGroup\n id={id}\n className={clsx(\"jkl-datepicker\", className, {\n \"jkl-datepicker--open\": showCalendar,\n })}\n {...rest}\n ref={datepickerRef}\n label={label}\n labelProps={labelProps}\n density={density}\n helpLabel={helpLabel}\n errorLabel={errorLabel}\n supportLabelProps={supportLabelProps}\n tooltipProps={tooltipProps}\n render={(inputProps) => (\n <BaseTextInput\n ref={unifiedInputRef}\n data-testid=\"jkl-datepicker__input\"\n data-testautoid={testAutoId}\n className=\"jkl-datepicker__input\"\n name={name}\n defaultValue={defaultValue}\n density={density}\n value={value}\n type=\"text\"\n placeholder={placeholder}\n width={width}\n onFocus={handleFocus}\n onBlur={handleBlur}\n onChange={handleChange}\n actionButton={\n <Popover\n positionReference={inputRef}\n open={showCalendar}\n onOpenChange={() => setShowCalendar(!showCalendar)}\n offset={8}\n >\n <Popover.Trigger\n {...action}\n data-testid=\"jkl-datepicker__trigger\"\n className=\"jkl-text-input-action-button\"\n title={showCalendar ? hideCalendarLabel : showCalendarLabel}\n tabIndex={0}\n onClick={clickCalendar}\n onKeyDown={handleKeyDownAction}\n asChild\n >\n <IconButton>\n <CalendarIcon />\n </IconButton>\n </Popover.Trigger>\n <Popover.Content initialFocus={-1} padding={24}>\n <Calendar\n ref={calendarRef}\n density={density}\n date={date}\n minDate={minDate}\n maxDate={maxDate}\n days={days}\n months={months}\n monthLabel={monthLabel}\n yearLabel={yearLabel}\n yearsToShow={yearsToShow}\n onDateSelected={handleClickCalendarDay}\n onTabOutside={handleTabOutsideCalendar}\n />\n </Popover.Content>\n </Popover>\n }\n {...inputProps}\n />\n )}\n />\n );\n});\n\nDatePicker.displayName = \"DatePicker\";\n"],"names":["DatePicker","forwardRef","props","forwardedInputRef","testAutoId","id","className","label","labelProps","defaultValue","defaultShow","value","disableBeforeDate","disableBefore","disableAfterDate","disableAfter","yearsToShow","name","helpLabel","errorLabel","invalid","density","days","months","monthLabel","yearLabel","placeholder","width","onChange","onBlur","onFocus","onKeyDown","action","showCalendarLabel","hideCalendarLabel","supportLabelProps","tooltipProps","rest","process","env","NODE_ENV","console","warn","parseDateString","minDate","startOfDay","maxDate","date","setDate","useState","getInitialDate","error","setError","showCalendar","setShowCalendar","calendarRef","useRef","datepickerRef","iconButtonRef","inputRef","unifiedInputRef","useCallback","instance","current","handleFocus","e","contains","relatedTarget","target","handleBlur","handleKeyDownAction","key","preventDefault","stopPropagation","handleChange","nextDate","nextError","val","isWithinLowerBound","isWithinUpperBound","clickCalendar","flushSync","calendarEl","button","querySelector","focus","onClick","handleClickCalendarDay","node","formatInput","event","document","createEvent","initEvent","dispatchEvent","handleTabOutsideCalendar","jsx","InputGroup","clsx","ref","render","inputProps","BaseTextInput","type","actionButton","jsxs","Popover","positionReference","open","onOpenChange","offset","children","Trigger","title","tabIndex","asChild","IconButton","CalendarIcon","Content","initialFocus","padding","Calendar","onDateSelected","onTabOutside","displayName"],"mappings":"+zEAwBO,MAAMA,EAAaC,GAA8C,CAACC,EAAOC,KACtE,MACF,kBAAmBC,EACnBC,GAAAA,EACAC,UAAAA,EAAY,GACZC,MAAAA,EAAQ,YACRC,WAAAA,EACAC,aAAAA,EACAC,YAAAA,GAAc,EACdC,MAAAA,EACAC,kBAAmBC,EACnBC,iBAAkBC,EAClBC,YAAAA,EACAC,KAAAA,EACAC,UAAAA,EACAC,WAAAA,EACAC,QAAAA,EACAC,QAAAA,EACAC,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAC,YAAAA,EAAc,aACdC,MAAAA,EAAQ,WACRC,SAAAA,EACAC,OAAAA,EACAC,QAAAA,EACAC,UAAAA,EACAC,OAAAA,EACAC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EAAoB,gBACpBC,kBAAAA,EACAC,aAAAA,KACGC,GACHnC,EAEyB,eAAzBoC,QAAQC,IAAIC,UAA6B7B,GAASF,GAC1CgC,QAAAC,KACJ,sIAKF,MAAA9B,EAAoB+B,EAAgB9B,GACpC+B,GAAUhC,EAAoBiC,EAAWjC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wBACVW,KAAAA,EACAR,aAAAA,EACAY,QAAAA,EACAV,MAAAA,EACA4F,KAAK,OACL7E,YAAAA,EACAC,MAAAA,EACAG,QAASkC,GACTnC,OAAQwC,GACRzC,SAAU8C,GACV8B,aACIC,EAACC,EAAA,CACGC,kBAAmBhD,GACnBiD,KAAMvD,GACNwD,aAAc,IAAMvD,IAAiBD,IACrCyD,OAAQ,EAERC,SAAA,CAAAf,EAACU,EAAQM,QAAR,IACOhF,EACJ,cAAY,0BACZ1B,UAAU,+BACV2G,MAAO5D,GAAenB,EAAoBD,EAC1CiF,SAAU,EACV5B,QAASN,GACTjD,UAAWuC,GACX6C,SAAO,EAEPJ,SAACf,EAAAoB,EAAA,CACGL,SAACf,EAAAqB,EAAA,CAAa,SAGrBX,EAAQY,QAAR,CAAgBC,cAAkB,EAAAC,QAAS,GACxCT,SAAAf,EAACyB,EAAA,CACGtB,IAAK5C,GACLlC,QAAAA,EACA0B,KAAAA,GACAH,QAAAA,GACAE,QAAAA,GACAxB,KAAAA,EACAC,OAAAA,EACAC,WAAAA,EACAC,UAAAA,EACAT,YAAAA,EACA0G,eAAgBnC,GAChBoC,aAAc5B,aAK1BM,KACR,IAMhBrG,EAAW4H,YAAc"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e
|
|
1
|
+
import{startOfDay as e}from"date-fns";import{useState as a}from"react";import{getCalendars as t,composeEventHandlers as n,subtractMonth as s,isBackDisabled as o,addMonth as d,isForwardDisabled as f}from"./utils.js";function l(e){return void 0!==e}function r(e,{onClick:a,dateObj:t}){return{onClick:n(a,(a=>{e(t,a)})),disabled:!t.selectable,"aria-pressed":t.selected,role:"button"}}function i({minDate:e,offsetMonth:a,handleOffsetChanged:t},{onClick:d,offset:f=1,calendars:l}){const r=`Gå tilbake ${f} måned${1===f?"":"er"}`;return{onClick:n(d,(()=>{t(a-s({calendars:l,offset:f,minDate:e}))})),disabled:o({calendars:l,minDate:e}),"aria-label":r,title:r}}function c({maxDate:e,offsetMonth:a,handleOffsetChanged:t},{onClick:s,offset:o=1,calendars:l}){const r=`Gå frem ${o} måned${1===o?"":"er"}`;return{onClick:n(s,(()=>{t(a+d({calendars:l,offset:o,maxDate:e}))})),disabled:f({calendars:l,maxDate:e}),"aria-label":r,title:r}}function m({date:n=e(new Date),maxDate:s,minDate:o,monthsToDisplay:d=1,firstDayOfWeek:f=0,showOutsideDays:m=!0,offset:D,onDateSelected:u,onOffsetChanged:h,selected:b}){const[C,O]=a(0),k=function(e,a){return l(e)?e:a}(D,C);function p(e){l(D)||O(e),h(e)}return{calendars:t({date:n,selected:b,monthsToDisplay:d,minDate:o,maxDate:s,offset:k,firstDayOfWeek:f,showOutsideDays:m}),getDateProps:r.bind(null,u),getBackProps:i.bind(null,{minDate:o,offsetMonth:k,handleOffsetChanged:p}),getForwardProps:c.bind(null,{maxDate:s,offsetMonth:k,handleOffsetChanged:p}),handleOffsetChanged:p}}export{m as useCalendar};
|
|
2
2
|
//# sourceMappingURL=useCalendar.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCalendar.js","sources":["../../../../../src/components/datepicker/internal/useCalendar.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport startOfDay from \"date-fns
|
|
1
|
+
{"version":3,"file":"useCalendar.js","sources":["../../../../../src/components/datepicker/internal/useCalendar.ts"],"sourcesContent":["/***\n * MIT License\n *\n * Copyright (c) 2017 Deseret Digital Media. 2022 Fremtind Forsikring AS.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport { startOfDay } from \"date-fns\";\nimport React, { useState } from \"react\";\nimport {\n composeEventHandlers,\n subtractMonth,\n addMonth,\n isBackDisabled,\n isForwardDisabled,\n getCalendars,\n DateInfo,\n CalendarMonth,\n} from \"./utils\";\n\nfunction isOffsetControlled(propOffset: number | undefined): boolean {\n return propOffset !== undefined;\n}\n\nfunction getOffset(prop: number, state: number): number {\n return isOffsetControlled(prop) ? prop : state;\n}\n\ntype BoundGetDateProps = (dateInfo: DateInfo, event: React.MouseEvent) => void;\n\ntype GetDateProps = {\n onClick?: React.MouseEventHandler;\n dateObj: DateInfo;\n};\n\ntype GetDatePropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-pressed\": boolean;\n role: \"button\";\n};\n\nfunction getDateProps(onDateSelected: BoundGetDateProps, { onClick, dateObj }: GetDateProps): GetDatePropsResult {\n return {\n onClick: composeEventHandlers(onClick, (event) => {\n onDateSelected(dateObj, event);\n }),\n disabled: !dateObj.selectable,\n \"aria-pressed\": dateObj.selected,\n role: \"button\",\n };\n}\n\ntype BoundGetBackProps = {\n handleOffsetChanged: (newOffset: number) => void;\n offsetMonth: number;\n minDate?: Date;\n};\n\ntype GetBackProps = {\n onClick?: React.MouseEventHandler;\n offset?: number;\n calendars: CalendarMonth[];\n};\n\ntype GetBackPropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-label\": string;\n title: string;\n};\n\nfunction getBackProps(\n { minDate, offsetMonth, handleOffsetChanged }: BoundGetBackProps,\n { onClick, offset = 1, calendars }: GetBackProps,\n): GetBackPropsResult {\n const label = `Gå tilbake ${offset} måned${offset === 1 ? \"\" : \"er\"}`;\n return {\n onClick: composeEventHandlers(onClick, () => {\n handleOffsetChanged(offsetMonth - subtractMonth({ calendars, offset, minDate }));\n }),\n disabled: isBackDisabled({ calendars, minDate }),\n \"aria-label\": label,\n title: label,\n };\n}\n\ntype BoundGetForwardProps = {\n handleOffsetChanged: (newOffset: number) => void;\n offsetMonth: number;\n maxDate?: Date;\n};\n\ntype GetForwardProps = {\n onClick?: React.MouseEventHandler;\n offset?: number;\n calendars: CalendarMonth[];\n};\n\ntype GetForwardPropsResult = {\n onClick: React.MouseEventHandler;\n disabled: boolean;\n \"aria-label\": string;\n title: string;\n};\n\nfunction getForwardProps(\n { maxDate, offsetMonth, handleOffsetChanged }: BoundGetForwardProps,\n { onClick, offset = 1, calendars }: GetForwardProps,\n): GetForwardPropsResult {\n const label = `Gå frem ${offset} måned${offset === 1 ? \"\" : \"er\"}`;\n return {\n onClick: composeEventHandlers(onClick, () => {\n handleOffsetChanged(offsetMonth + addMonth({ calendars, offset, maxDate }));\n }),\n disabled: isForwardDisabled({ calendars, maxDate }),\n \"aria-label\": label,\n title: label,\n };\n}\n\nexport interface UseCalendarProps {\n date?: Date;\n maxDate?: Date;\n minDate?: Date;\n monthsToDisplay?: number;\n firstDayOfWeek?: number;\n showOutsideDays?: boolean;\n offset: number;\n onDateSelected: (dateObj: DateInfo, event: React.MouseEvent) => void;\n onOffsetChanged: (newOffset: number) => void;\n selected?: Date | Date[];\n}\n\nexport type GetDatePropsFunc = (props: GetDateProps) => GetDatePropsResult;\nexport type GetBackPropsFunc = (props: GetBackProps) => GetBackPropsResult;\nexport type GetForwardPropsFunc = (props: GetForwardProps) => GetForwardPropsResult;\nexport type HandleOffsetFunc = (newOffset: number) => void;\n\nexport type UseCalendarResult = {\n calendars: CalendarMonth[];\n getDateProps: GetDatePropsFunc;\n getBackProps: GetBackPropsFunc;\n getForwardProps: GetForwardPropsFunc;\n handleOffsetChanged: HandleOffsetFunc;\n};\n\nexport function useCalendar({\n date = startOfDay(new Date()),\n maxDate,\n minDate,\n monthsToDisplay = 1,\n firstDayOfWeek = 0,\n showOutsideDays = true,\n offset,\n onDateSelected,\n onOffsetChanged,\n selected,\n}: UseCalendarProps): UseCalendarResult {\n const [stateOffset, setStateOffset] = useState(0);\n const offsetMonth = getOffset(offset, stateOffset);\n\n function handleOffsetChanged(newOffset: number) {\n if (!isOffsetControlled(offset)) {\n setStateOffset(newOffset);\n }\n onOffsetChanged(newOffset);\n }\n\n const calendars = getCalendars({\n date,\n selected,\n monthsToDisplay,\n minDate,\n maxDate,\n offset: offsetMonth,\n firstDayOfWeek,\n showOutsideDays,\n });\n return {\n calendars,\n getDateProps: getDateProps.bind(null, onDateSelected),\n getBackProps: getBackProps.bind(null, {\n minDate,\n offsetMonth,\n handleOffsetChanged,\n }),\n getForwardProps: getForwardProps.bind(null, {\n maxDate,\n offsetMonth,\n handleOffsetChanged,\n }),\n handleOffsetChanged,\n };\n}\n"],"names":["isOffsetControlled","propOffset","getDateProps","onDateSelected","onClick","dateObj","composeEventHandlers","event","disabled","selectable","selected","role","getBackProps","minDate","offsetMonth","handleOffsetChanged","offset","calendars","label","subtractMonth","isBackDisabled","title","getForwardProps","maxDate","addMonth","isForwardDisabled","useCalendar","date","startOfDay","Date","monthsToDisplay","firstDayOfWeek","showOutsideDays","onOffsetChanged","stateOffset","setStateOffset","useState","prop","state","getOffset","newOffset","getCalendars","bind"],"mappings":"uNAoCA,SAASA,EAAmBC,GACxB,YAAsB,IAAfA,CACX,CAoBA,SAASC,EAAaC,GAAqCC,QAAAA,EAASC,QAAAA,IACzD,MAAA,CACHD,QAASE,EAAqBF,GAAUG,IACpCJ,EAAeE,EAASE,EAAK,IAEjCC,UAAWH,EAAQI,WACnB,eAAgBJ,EAAQK,SACxBC,KAAM,SAEd,CAqBA,SAASC,GACHC,QAAAA,EAASC,YAAAA,EAAaC,oBAAAA,IACtBX,QAAAA,EAASY,OAAAA,EAAS,EAAGC,UAAAA,IAEvB,MAAMC,EAAQ,cAAcF,UAA0B,IAAXA,EAAe,GAAK,OACxD,MAAA,CACHZ,QAASE,EAAqBF,GAAS,KACnCW,EAAoBD,EAAcK,EAAc,CAAEF,UAAAA,EAAWD,OAAAA,EAAQH,QAAAA,IAAU,IAEnFL,SAAUY,EAAe,CAAEH,UAAAA,EAAWJ,QAAAA,IACtC,aAAcK,EACdG,MAAOH,EAEf,CAqBA,SAASI,GACHC,QAAAA,EAAST,YAAAA,EAAaC,oBAAAA,IACtBX,QAAAA,EAASY,OAAAA,EAAS,EAAGC,UAAAA,IAEvB,MAAMC,EAAQ,WAAWF,UAA0B,IAAXA,EAAe,GAAK,OACrD,MAAA,CACHZ,QAASE,EAAqBF,GAAS,KACnCW,EAAoBD,EAAc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