@osrd-project/ui-core 0.0.71 → 0.0.73
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/dist/hooks/useModalPosition.d.ts +1 -2
- package/dist/index.esm.js +1262 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/theme.css +1 -1
- package/dist/theme.css.map +1 -1
- package/package.json +3 -3
- package/dist/stories/Button.stories.d.ts +0 -16
- package/dist/stories/Checkbox.stories.d.ts +0 -9
- package/dist/stories/CheckboxTree.stories.d.ts +0 -16
- package/dist/stories/ComboBox.stories.d.ts +0 -21
- package/dist/stories/ComboBoxCustom.stories.d.ts +0 -10
- package/dist/stories/DatePicker.stories.d.ts +0 -10
- package/dist/stories/Input.stories.d.ts +0 -27
- package/dist/stories/PasswordInput.stories.d.ts +0 -7
- package/dist/stories/RadioButton.stories.d.ts +0 -7
- package/dist/stories/RadioGroup.stories.d.ts +0 -14
- package/dist/stories/Select.stories.d.ts +0 -23
- package/dist/stories/Slider.stories.d.ts +0 -9
- package/dist/stories/TextArea.stories.d.ts +0 -16
- package/dist/stories/TimePicker.stories.d.ts +0 -10
- package/dist/stories/TokenInput.stories.d.ts +0 -7
- package/dist/stories/TolerancePicker.stories.d.ts +0 -10
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,1263 @@
|
|
|
1
|
-
import e,{useEffect as t,useState as a,useCallback as n,useRef as l,useMemo as s}from"react";import{Gear as r,Info as i,CheckCircle as o,Alert as c,Blocked as d,RequiredInput as m,X as u,XCircle as p,ChevronDown as g,ChevronLeft as h,ChevronRight as E,Calendar as b,EyeClosed as v,Eye as N}from"@osrd-project/ui-icons";import f from"classnames";const C=({label:t,variant:a="Primary",isLoading:n=!1,isDisabled:l=!1,leadingIcon:s=null,counter:i=null,size:o="large",onClick:c,...d})=>e.createElement("button",{...d,className:f("button flex items-center",d.className,a.toLowerCase(),o.toLowerCase(),{loading:n}),onClick:()=>{n||l||!c||c()},disabled:l||n},n?e.createElement("span",{className:"icon"},e.createElement(r,{variant:"fill",size:"lg"})):e.createElement(e.Fragment,null,s&&e.createElement("span",{className:"leading-icon mr-2"},s),t,null!==i&&e.createElement("span",{className:"counter ml-2"},i))),y=(e,a)=>{t((()=>{const t=t=>{e.current&&!e.current.contains(t.target)&&a(t)};return document.addEventListener("mousedown",t),()=>{document.removeEventListener("mousedown",t)}}),[e,a])},w=({text:t})=>e.createElement("span",{className:"base-hint"},t),k=({status:t,small:a,className:n})=>{const l=a?"sm":"lg";return e.createElement("span",{className:f("status-icon",n,t)},"loading"===t&&e.createElement(r,{size:l}),"info"===t&&e.createElement(i,{variant:"fill",size:l}),"success"===t&&e.createElement(o,{variant:"fill",size:l}),"warning"===t&&e.createElement(c,{variant:"fill",size:l}),"error"===t&&e.createElement(d,{variant:"fill",size:l}))},D=({htmlFor:t,text:a,required:n,hasHint:l,disabled:s,small:r=!1})=>e.createElement("div",{className:f("base-label-wrapper",{"has-hint":l,small:r})},n&&e.createElement("span",{className:"required"},e.createElement(m,null)),e.createElement("label",{className:f("label",{disabled:s}),htmlFor:t},a)),M=({statusWithMessage:t,showIcon:a,small:n,onClose:l})=>{const{tooltip:s,status:r,message:i}=t;return void 0===i?null:e.createElement("div",{className:f({"status-message-wrapper":!s,"status-message-wrapper-tooltip":s,"tooltip-left":"left"===s,"tooltip-right":"right"===s,[r]:r})},a&&e.createElement(k,{status:r,small:n}),e.createElement("span",{className:f("status-message",{[r]:r})},i),"info"===r&&s&&e.createElement("button",{className:"status-close",onClick:l},e.createElement(u,{size:"sm"})))},S=({id:t,label:a,hint:n,required:l,disabled:s,statusWithMessage:r,statusIconPosition:i="next-to-field",narrow:o=!1,small:c=!1,className:d,children:m,onCloseStatusMessage:u})=>{const p=r?{[r.status]:!0}:{},g=o?"left":void 0;if(o&&l)throw new Error("narrow should not be used with required for now. This breaks the input UI.");return e.createElement("div",{className:f("feed-back",p,d,{small:c,narrow:o})},e.createElement("div",{className:"custom-field"},a&&e.createElement(D,{htmlFor:t,text:a,required:l,hasHint:Boolean(n),disabled:s,small:c}),n&&e.createElement(w,{text:n}),e.createElement("div",{className:"field-and-status-icon"},m,r&&"next-to-field"===i&&e.createElement(k,{status:r.status,small:c,className:"next-to-field"})),r&&e.createElement(M,{small:c,statusWithMessage:{...r,tooltip:r?.tooltip??g},showIcon:"before-status-message"===i,onClose:u})))};function I({onBlur:e,onKeyUp:t}){const[l,s]=a(!1);return{handleKeyUp:n((e=>{"Tab"===e.key&&s(!0),t?.(e)}),[t]),handleBlur:n((t=>{s(!1),e?.(t)}),[e]),isFocusByTab:l}}const T=({value:t,type:a,disabled:n,readOnly:l})=>{const s="object"==typeof t&&null!==t&&"onClickCallback"in t,r=s?t.content:t,i=s?{onClick:t.onClickCallback}:{};return e.createElement("div",{className:f(`${a}-content-wrapper`,{disabled:n,"read-only":l}),...i},e.createElement("span",{className:`${a}-content`},r))},P=e.forwardRef((({id:t,label:a,type:n,hint:l,leadingContent:s,trailingContent:r,required:i,disabled:o=!1,readOnly:c=!1,statusWithMessage:d,narrow:m,inputFieldWrapperClassname:u="",small:p=!1,withIcons:g=[],onKeyUp:h,onBlur:E,onCloseStatusMessage:b,...v},N)=>{const{handleKeyUp:C,handleBlur:y,isFocusByTab:w}=I({onBlur:E,onKeyUp:h});return e.createElement(S,{id:t,label:a,hint:l,statusWithMessage:d,disabled:o,required:i,small:p,statusIconPosition:d?.tooltip||m?"before-status-message":void 0,narrow:m,className:f("input-field-wrapper",u),onCloseStatusMessage:b},s&&e.createElement(T,{value:s,type:"leading",disabled:o,readOnly:c}),e.createElement("div",{className:f("input-container",{"focused-by-tab":w})},e.createElement("input",{ref:N,className:f("input",{"with-leading-only":s&&!r,"with-trailing-only":r&&!s,"with-leading-and-trailing":s&&r,[`with-icons-${g.length}`]:g.length>0,[d?.status||""]:!!d}),id:t,type:n,disabled:o,readOnly:c,onKeyUp:C,onBlur:y,...v}),e.createElement("div",{className:f("input-icons",{small:p})},g.map(((t,a)=>e.createElement("span",{key:a,className:t?.className,onClick:t.action},t.icon))))),r&&e.createElement(T,{value:r,type:"trailing",disabled:o,readOnly:c}))}));P.displayName="Input";const x=({suggestions:r,customLabel:i,numberOfSuggestionsToShow:o=5,value:c,small:d,getSuggestionLabel:m,onChange:u,onSelectSuggestion:h,resetSuggestions:E,...b})=>{const[v,N]=a(-1),[C,w]=a(""),[k,D]=a(!1),M=l([]),S=l(null),I=l(null),T=n((()=>{S.current?.focus()}),[S]),x=()=>{D(!1),N(-1),setTimeout((()=>{S.current?.blur()}),0),E()};t((()=>{w(c?m(c):"")}),[c]);const K=s((()=>k&&r.length>0&&!b.disabled),[k,r.length,b.disabled]),F=e=>{const t=r.at(e);h(t),w(m(t)),x()},$=()=>{w(c?m(c):""),x()},W=()=>{w(""),h(void 0),E(),T()};y(I,$);const B=s((()=>[...c?[{icon:e.createElement(p,{variant:"fill"}),action:W,className:"clear-icon"}]:[],{icon:e.createElement(g,{size:d?"sm":"lg"}),action:T,className:f("chevron-icon",{disabled:b.disabled})}]),[c]);return e.createElement("div",{className:"combo-box",style:{"--number-of-suggestions":o},ref:I},i&&e.createElement("label",{htmlFor:b.id},i),e.createElement(P,{...b,ref:S,value:C,onChange:e=>{u?.(e),w(e.currentTarget.value)},onKeyDown:e=>{"ArrowDown"===e.key?N((e=>{const t=e<r.length-1?e+1:e;return M.current[t]&&M.current[t].scrollIntoView({block:"nearest"}),t})):"ArrowUp"===e.key?N((e=>{const t=e>0?e-1:e;return M.current[t]&&M.current[t].scrollIntoView({block:"nearest"}),t})):("Enter"===e.key||"Tab"===e.key)&&v>=0?F(v):"Escape"===e.key&&$()},onFocus:e=>{e.stopPropagation(),D(!0)},withIcons:B,small:d}),K&&e.createElement("ul",{className:"suggestions-list"},r.map(((t,a)=>e.createElement("li",{ref:e=>M.current[a]=e,key:`${m(t)}-${a}`,className:f("suggestion-item",{active:a===v,selected:c&&m(c)===m(t),small:d}),onClick:()=>F(a),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>{N(a)}},m(t))))))},K=e=>e.normalize("NFD").replace(/[\u0300-\u036f]/g,""),F=(e,t)=>{const[n,l]=a(""),r=s((()=>((e,t,a)=>{const n=K(a).trim().toLowerCase();if(!n)return t;const l=t=>{const a=K(e(t).toLowerCase());return a.startsWith(n)?2:a.includes(n)?1:0};return t.map((e=>({suggestion:e,score:l(e)}))).filter((({score:e})=>e>0)).sort((({score:e},{score:t})=>t-e)).map((({suggestion:e})=>e))})(t,e,n)),[e,n]);return{suggestions:r,onChange:e=>{l(e.target.value)},resetSuggestions:()=>{l("")}}},$=({label:t,small:a,hint:n,disabled:l,checked:s,readOnly:r,isIndeterminate:i=!1,onClick:o,onKeyUp:c,onBlur:d,...m})=>{const{handleKeyUp:u,handleBlur:p,isFocusByTab:g}=I({onBlur:d,onKeyUp:c});return e.createElement("label",{className:f("custom-checkbox",{small:a})},e.createElement("input",{className:f({"read-only":r}),type:"checkbox",checked:s,disabled:l,ref:e=>e&&(e.indeterminate=i),onClick:e=>{r?(e.preventDefault(),e.stopPropagation()):o?.(e)},onBlur:p,onKeyUp:u,...m}),e.createElement("span",{className:f("checkmark",{"focused-by-tab":g})}),t&&e.createElement("div",{className:"label"},t),n&&e.createElement("span",{className:"hint"},n))},W=t=>{const{items:a,onClickItem:n,small:l=!1,label:s="",readOnly:r=!1,disabled:i=!1}=t;return e.createElement(e.Fragment,null,e.createElement("span",{className:"checkbox-list-label"},s),e.createElement("ul",{className:f("checkbox-list",{small:l})},a.map((a=>{const{id:s,props:o,items:c}=a;return e.createElement("li",{key:s},e.createElement($,{small:l,onClick:e=>n(e,a),checked:a.props.checked,isIndeterminate:a.props.isIndeterminate,...o,disabled:i,readOnly:r}),c&&e.createElement(W,{...t,items:c}))}))))};var B;!function(e){e[e.UNCHECKED=0]="UNCHECKED",e[e.CHECKED=1]="CHECKED",e[e.INDETERMINATE=2]="INDETERMINATE"}(B||(B={}));const O=(e,t,a)=>{e.forEach((e=>{t(e,a),e.items&&e.items.length>0&&O(e.items,t,e)}))},R=(e,t,a,n)=>{n[e]=t,a[e]?.forEach((e=>R(e,t,a,n)))},U=(e,t,a)=>{const{parentChildrenMap:n,childrenParentMap:l}=a,s=l[e];if(void 0===s)return;const r=n[s].map((e=>t[e]));let i;i=r.every((e=>e===B.CHECKED))?B.CHECKED:r.every((e=>e===B.UNCHECKED))?B.UNCHECKED:B.INDETERMINATE,t[s]=i,U(s,t,{parentChildrenMap:n,childrenParentMap:l})},H=(e,t,a)=>{const n={...t},l=n[a]===B.CHECKED?B.UNCHECKED:B.CHECKED,{parentChildrenMap:s,childrenParentMap:r}=(e=>{const t={},a={};return O(e,((e,n)=>{void 0!==n?.id&&(t[n.id]||(t[n.id]=[]),t[n.id].push(e.id),a[e.id]=n.id)})),{parentChildrenMap:t,childrenParentMap:a}})(e);return R(a,l,s,n),U(a,n,{parentChildrenMap:s,childrenParentMap:r}),n},L=(e,t)=>{const a=(e=>{const t={};return O(e,(e=>{e.props.isIndeterminate?t[e.id]=B.INDETERMINATE:t[e.id]=e.props.checked?B.CHECKED:B.UNCHECKED})),t})(e);return((e,t)=>{const a=JSON.parse(JSON.stringify(e));return O(a,(e=>{const{checked:a,isIndeterminate:n,...l}=e.props;e.props=l,t[e.id]===B.INDETERMINATE?e.props.isIndeterminate=!0:t[e.id]===B.CHECKED?e.props.checked=!0:e.props.checked=!1})),a})(e,H(e,a,t.id))},q=({items:t,small:a,id:n,label:l,hint:s,statusWithMessage:r,disabled:i,required:o,readOnly:c,onChange:d,computeNewItemsTree:m})=>e.createElement(S,{id:n,label:l,hint:s,statusWithMessage:r,statusIconPosition:"before-status-message",disabled:i,required:o,small:a},e.createElement(W,{small:a,items:t,disabled:i,readOnly:c,onClickItem:(e,a)=>{const n=m?m(t,a):L(t,a);d?.(n,a),a.props.onClick?.(e)}})),z="Invalid selectedSlot: If start and end are defined, the start date must be before the end date.",Y="Invalid selectableSlot: If start and end are defined, the start date must be before the end date.",A="selectedSlot must be within selectableSlot",G="initialDate must be within selectableSlot";function V(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function _(e){return!e.start||!e.end||V(e.start).getTime()<=V(e.end).getTime()}function j(e,t){return!(!e||!t)&&(e.getDate()===t.getDate()&&e.getMonth()===t.getMonth()&&e.getFullYear()===t.getFullYear())}function J(e,t){if(!t)return!0;const a=V(e),n=t.start?V(t.start):void 0,l=t.end?V(t.end):void 0;return(!n||a>=n)&&(!l||a<=l)}function Q(e){if(!e)return"";return`${String(e.getDate()).padStart(2,"0")}/${String(e.getMonth()+1).padStart(2,"0")}/${String(e.getFullYear()).slice(-2)}`}function X({value:e,isRangeMode:t}){return t?function(e){let t="";if(e){const{start:a,end:n}=e;if(j(a,n))t=Q(a);else{let e=Q(a);a&&n&&a.getFullYear()===n.getFullYear()&&(e=e.slice(0,5)),t=`${e} - ${Q(n)}`}}return t}(e):Q(e)}function Z({value:e,isRangeMode:t}){return t?e:e?{start:e,end:e}:e}function ee({displayedMonthStartDate:e,selectableSlot:t,selectedSlot:a}){const n=t?.start??new Date;n.setHours(0,0,0,0);const l=e.getFullYear(),s=e.getMonth(),r=function(e,t){const a=new Date(t,e+1,0).getDate(),n=[];for(let l=1;l<=a;l++)n.push(new Date(t,e,l));return n}(s,l);return{days:[...function(e,t){const a=new Date(t,e,1).getDay();if(1===a)return[];const n=0===a?6:a-1,l=new Date(t,e,0),s=[];for(let e=0;e<n;e++){const t=l.getDate()-e;s.unshift(new Date(l.getFullYear(),l.getMonth(),t))}return s}(s,l),...r,...function(e,t){const a=(7-new Date(t,e+1,0).getDay())%7;if(0===a)return[];const n=new Date(t,e+1,1),l=[];for(let e=0;e<a;e++){const t=e+1;l.push(new Date(n.getFullYear(),n.getMonth(),t))}return l}(s,l)],isReferenceDate:e=>V(e).getTime()===V(n).getTime(),buildDayWrapperClassName:e=>{const l=a&&j(e,a.start)||!1,r=a&&j(e,a.end)||!1,i=a?.start&&a.end&&J(e,a)||l||r,o=J(e,t);let c={"inside-selectable-slot":o,"outside-selectable-slot":!o,"current-month":e.getMonth()===s,past:V(e)<V(n)};return a&&(c={...c,start:l,end:r,"within-selected-slot":i}),f("day-wrapper",c)},isDateSelectable:e=>!!J(e,t)&&e.getMonth()===s}}const te=["M","T","W","T","F","S","S"],ae=({date:t,isReferenceDate:a,isSelectable:n,dayWrapperClassName:l,onClick:s})=>e.createElement("div",{onClick:()=>{n&&s(t)},className:"day-background"},e.createElement("div",{className:l},e.createElement("span",{className:"day"},t.getDate()),a&&e.createElement("span",{className:"current-date-highlight"}))),ne=t=>{const{days:a,isReferenceDate:n,isDateSelectable:l,buildDayWrapperClassName:s}=ee(t),{displayedMonthStartDate:r,onDayClick:i}=t;return e.createElement("div",{className:"calendar-wrapper"},e.createElement("div",{className:"calendar-anatomy"},e.createElement("p",{className:"calendar-month-label"},r.toLocaleString("en-GB",{month:"short"})),e.createElement("div",{className:"calendar-grid-wrapper"},e.createElement("div",{className:"calendar-weekday-labels"},te.map(((t,a)=>e.createElement("p",{key:`${t}-${a}`},t)))),e.createElement("div",{className:"calendar-days-grid"},a.map((t=>e.createElement(ae,{key:t.getTime(),date:t,isReferenceDate:n(t),isSelectable:l(t),dayWrapperClassName:s(t),onClick:i})))))))};function le({initialDate:e,selectedSlot:n,selectableSlot:l,numberOfMonths:s=1}){!function(e,t,a){if(e&&!_(e))throw new Error(z);if(t&&!_(t))throw new Error(Y);if(e?.start&&e?.end&&t?.start&&t?.end&&(V(e.start)<V(t.start)||V(e.end)>V(t.end)))throw new Error(A);if(a&&t?.start&&t?.end&&(V(a)<V(t.start)||V(a)>V(t.end)))throw new Error(G)}(n,l,e);const[r,i]=a(new Date),o=function(e,t){const a=[];for(let n=0;n<t;n++){const t=new Date(e);t.setMonth(e.getMonth()+n,1),a.push(new Date(t.getFullYear(),t.getMonth(),1))}return a}(r,s),c=r.getFullYear(),d=r.getMonth(),m=new Date(c,d,1),u=new Date(c,d+1,0),p=void 0===l||null===l.start||l.start<m,g=void 0===l||null===l.end||l.end>u,h=p||g;return t((()=>{i(e??n?.start??l?.start??new Date)}),[e,n,l]),{displayedMonthsStartDates:o,showNavigationBtn:h,canGoToPreviousMonth:p,canGoToNextMonth:g,handleGoToPreviousMonth:()=>{if(p){i(new Date(0===d?c-1:c,0===d?11:d-1,1))}},handleGoToNextMonth:()=>{if(g){i(new Date(11===d?c+1:c,11===d?0:d+1,1))}}}}const se=({initialDate:t,selectedSlot:a,selectableSlot:n,numberOfMonths:l=1,onDayClick:s,modalPosition:r,calendarPickerRef:i})=>{const{displayedMonthsStartDates:o,showNavigationBtn:c,canGoToNextMonth:d,canGoToPreviousMonth:m,handleGoToNextMonth:u,handleGoToPreviousMonth:p}=le({initialDate:t,selectedSlot:a,selectableSlot:n,numberOfMonths:l});return e.createElement("div",{ref:i,className:"calendar-picker",style:r},c&&e.createElement("span",{className:f("calendar-navigation-btn","previous",{disabled:!m}),onClick:p},e.createElement(h,{size:"lg"})),e.createElement("div",{className:f("calendar-list",{"navigation-btn-hidden":!c})},o.map((t=>e.createElement(ne,{key:t.getTime(),displayedMonthStartDate:t,selectableSlot:n,selectedSlot:a,onDayClick:s})))),c&&e.createElement("span",{className:f("calendar-navigation-btn","next",{disabled:!d}),onClick:u},e.createElement(E,{size:"lg"})))},re=(e,l,s=3,r=0)=>{const[i,o]=a({top:0,left:0}),c=n((()=>{if(e.current&&l.current){const t=e.current.getBoundingClientRect(),a=l.current.getBoundingClientRect();let n=t.left+t.width/2-a.width/2,i=t.bottom+window.scrollY-s;n-=r,n+a.width>window.innerWidth?n=window.innerWidth-a.width:n<0&&(n=10),i+a.height>window.innerHeight&&(i=window.innerHeight-a.height-r),o({top:i,left:n})}}),[e,l,s,r]);return t((()=>{c();const e=()=>c();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}),[c]),{modalPosition:i,calculatePosition:c}},ie=/^\d{2}\/\d{2}\/\d{2}$/;function oe(e){const{value:n,isRangeMode:s,selectableSlot:r,errorMessages:i,onDateChange:o}=e,[c,d]=a(!1),[m,u]=a(X(e)),[p,g]=a(Z(e)),[h,E]=a(),b=l(null),v=l(null);y(b,(e=>{v.current&&v.current.parentElement?.parentElement?.contains(e.target)||d(!1)}));const{calculatePosition:N,modalPosition:f}=re(v,b,3,-24);return t((()=>{c&&N()}),[c,N]),t((()=>{const t=X(e);t!==m&&u(t),E(void 0),g(Z(e))}),[n]),{showPicker:c,inputValue:m,statusWithMessage:h,selectedSlot:p,modalPosition:f,inputRef:v,calendarPickerRef:b,setShowPicker:d,handleDayClick:e=>{if(s){const t=function(e,t){return t&&null!==t?.start?t.end?{start:e,end:null}:V(e).getTime()===V(t.start).getTime()?void 0:V(e)<V(t.start)?{start:e,end:t.start}:{start:t.start,end:e}:{start:e,end:null}}(e,n);o(e,t)}else o(e)},handleInputClick:()=>{s&&d(!0)},handleInputOnChange:e=>{if(s)return;u(e);if(ie.test(e)){const[t,a,n]=e.split("/").map(Number),l=new Date(n+2e3,a-1,t);!isNaN(l.getTime())&&J(l,r)&&o?o(l):E({status:"error",message:i?.invalidDate})}else{if(/^[0-9/]+$/.test(e)&&e.length<8)E(void 0);else E({status:"error",message:i?.invalidInput})}}}}const ce=({inputRef:a,isOpen:n,onClose:s,children:r})=>{const i=l(null),{modalPosition:o,calculatePosition:c}=re(a,i);return t((()=>{n&&c()}),[c,n]),y(i,s),n?e.createElement("div",{className:"modal-ui-overlay"},e.createElement("div",{ref:i,className:"modal-ui-content",style:{top:o.top,left:o.left}},e.createElement("button",{className:"close-button",onClick:s},e.createElement(u,{size:"lg"})),r)):null},de=t=>{const{inputValue:a,statusWithMessage:n,selectedSlot:l,showPicker:s,modalPosition:r,inputRef:i,calendarPickerRef:o,setShowPicker:c,handleDayClick:d,handleInputClick:m,handleInputOnChange:u}=oe(t),{inputFieldWrapperClassname:p,...g}=t.inputProps,{selectableSlot:h}=t;return e.createElement("div",{className:"date-picker"},e.createElement("div",null,e.createElement(P,{...g,ref:i,value:a,onClick:m,type:"text",trailingContent:{content:e.createElement(b,null),onClickCallback:()=>c(!s)},inputFieldWrapperClassname:f("date-picker-input",p,{"range-mode":t.isRangeMode}),autoComplete:"off",onChange:e=>u(e.target.value),statusWithMessage:n})),e.createElement(ce,{inputRef:i,isOpen:s,onClose:()=>c(!1)},e.createElement("div",{className:"calendar-picker-wrapper"},e.createElement(se,{...t.calendarPickerProps,selectedSlot:l,onDayClick:d,modalPosition:r,calendarPickerRef:o,selectableSlot:h}))))},me=e.forwardRef((({inputFieldWrapperClassname:t,...n},l)=>{const[s,r]=a(!1);return e.createElement(P,{...n,type:s?"text":"password",trailingContent:{content:s?e.createElement(v,null):e.createElement(N,null),onClickCallback:()=>r(!s)},inputFieldWrapperClassname:f("password-input",t),ref:l})}));me.displayName="PasswordInput";const ue=({id:t,label:a,value:n,hint:l,readOnly:s,onBlur:r,onKeyUp:i,small:o,...c})=>{const{handleKeyUp:d,handleBlur:m,isFocusByTab:u}=I({onBlur:r,onKeyUp:i});return e.createElement("div",{className:f("radio-button",{"read-only":s,small:o}),tabIndex:0},e.createElement("div",{className:"radio-container"},e.createElement("input",{className:"radio-input",id:t||n,type:"radio",value:n,tabIndex:-1,onBlur:m,onKeyUp:d,...c}),e.createElement("span",{className:f("checkmark",{focused:u})}),e.createElement("label",{htmlFor:t||n,className:"radio-label"},a)),l&&e.createElement("div",{className:"hint"},l))},pe=({label:t,value:n,subtitle:l,readOnly:s,disabled:r,options:i,statusWithMessage:o,required:c,small:d})=>{const[u,p]=a(n),g=o?.status?{[o.status]:!0}:{};return e.createElement("div",{className:f("radio-button-wrapper",g)},t&&e.createElement("label",{className:"label"},c&&e.createElement("span",{className:"required"},e.createElement(m,null)),t," ",l&&e.createElement("span",{className:"subtitle"},l)),i.map((t=>e.createElement(ue,{key:t.value,...t,readOnly:s,disabled:r,checked:u===t.value,onChange:e=>{((e,t)=>{s||(p(t.value),t.onChange?.(e))})(e,t)},small:d}))),o?.message&&e.createElement("div",{className:"status-with-message"},e.createElement(k,{status:o.status}),e.createElement("span",{className:f("status-message",g)},o.message)))},ge="__PLACEHOLDER__",he=({id:n,label:l,hint:s,value:r,options:i,placeholder:o,statusWithMessage:c,required:d,disabled:m,narrow:u,readOnly:p,small:g,getOptionLabel:h,getOptionValue:E,onChange:b,...v})=>{const[N,C]=a(r);return t((()=>{C(r)}),[r]),e.createElement(S,{id:n,label:l,hint:s,statusWithMessage:c,required:d,disabled:m,small:g,narrow:u},e.createElement("select",{id:n,className:f("osrd-ui-custom-select",c?.status,{"placeholder-selected":o&&!N,small:g,"read-only":p}),value:N?E(N):void 0,required:d,disabled:m||p,onChange:e=>{const t=e.target.value===ge?void 0:i.find((t=>E(t)===e.target.value));C(t),b(t)},...v},o&&e.createElement("option",{value:ge},`– ${o} –`),i.map((t=>e.createElement("option",{key:E(t),value:E(t)},h(t))))))},Ee=({id:t,label:n,value:l,hint:s,required:r,disabled:i,statusWithMessage:o,maxLength:c,onChange:d,onKeyUp:m,onBlur:u,...p})=>{const[g,h]=a(l),E=g?.length||0,{handleKeyUp:b,handleBlur:v,isFocusByTab:N}=I({onBlur:u,onKeyUp:m});return e.createElement(S,{id:t,label:n,hint:s,statusWithMessage:o,disabled:i,required:r,className:"text-area-field-wrapper"},e.createElement("div",{className:f("text-area-wrapper",{"focused-by-tab":N})},c&&e.createElement("div",{className:f("char-count",{error:E===c,warning:c-E<=40})},E,"/",c),e.createElement("textarea",{className:f("text-area",{[o?.status||""]:!!o}),id:t,value:g,disabled:i,maxLength:c,onChange:e=>{h(e.target.value),d?.(e)},onBlur:v,onKeyUp:b,...p})))},be=({range:t,selectedItem:a,className:n,onSelectItem:l})=>e.createElement("div",{className:"time-grid"},t.map((t=>e.createElement("div",{key:t,className:f(n,{selected:a===t}),onClick:()=>l(t)},t.toString().padStart(2,"0")))));function ve(e,t){return Math.max(0,Math.min(t,e)).toString().padStart(2,"0")}const Ne=({onTimeChange:t,hours:s=0,minutes:r=0,seconds:i=0,displaySeconds:o=!1,...c})=>{const[d,m]=a(!1),u=l(null),p=n((e=>{let a=r+e,n=s;a>=60?(a=0,n=(n+1)%24):a<0&&(a=59,n=(n+23)%24),t({hours:n,minutes:a,seconds:i})}),[s,r,i,t]),g=n((e=>{let a=i+e,n=r,l=s;a>=60?(a=0,n+=1,n>=60&&(n=0,l=(l+1)%24)):a<0&&(a=59,n-=1,n<0&&(n=59,l=(l+23)%24)),t({hours:l,minutes:n,seconds:a})}),[s,r,i,t]),h=n((e=>{const a=e.target.value;if(o){const[e,n,l]=a.split(":");void 0!==e&&void 0!==n&&void 0!==l&&t({hours:parseInt(e),minutes:parseInt(n),seconds:parseInt(l)})}else{const[e,n]=a.split(":");void 0!==e&&void 0!==n&&t({hours:parseInt(e),minutes:parseInt(n)})}}),[o,t]),E=o?`:${ve(i,59)}`:"",b=`${ve(s,23)}:${ve(r,59)}${E}`,v=[...Array(24).keys()],N=[...Array(12).keys()].map((e=>5*e)),C=n((()=>m(!0)),[]),y=n((()=>m(!1)),[]);return e.createElement("div",{className:"time-picker"},e.createElement(P,{...c,className:f("input","time-input",c.className),type:"time",name:"time",value:b,onClick:C,onChange:h,ref:u,step:o?1:60}),e.createElement(ce,{inputRef:u,isOpen:d,onClose:y},e.createElement("div",{className:"time-picker-container"},e.createElement(be,{range:v,selectedItem:s,className:"hour",onSelectItem:e=>t({hours:e,minutes:r,seconds:i})}),e.createElement("div",{className:"time-separator"},":"),e.createElement("div",{className:"minute-container"},e.createElement(be,{range:N,selectedItem:r,className:"minute",onSelectItem:e=>t({hours:s,minutes:e,seconds:i})}),e.createElement("div",{className:"minute-buttons"},e.createElement("button",{onClick:()=>p(-1),className:"minute-button"},"-1mn"),e.createElement("button",{onClick:()=>p(1),className:"minute-button"},"+1mn"))),o&&e.createElement(e.Fragment,null,e.createElement("div",{className:"time-separator"},":"),e.createElement("div",{className:"second-container"},e.createElement(be,{range:N,selectedItem:i,className:"second",onSelectItem:e=>t({hours:s,minutes:r,seconds:e})}),e.createElement("div",{className:"second-buttons"},e.createElement("button",{onClick:()=>g(-1),className:"second-button"},"-1s"),e.createElement("button",{onClick:()=>g(1),className:"second-button"},"+1s")))))))},fe=({id:n,value:l,min:s=0,max:r=100,step:i=1,width:o=112,onChange:c,onChangeCommitted:d,disabled:m,className:u,containerClassName:p,...g})=>{const[h,E]=a(Number(void 0!==l?l:s));t((()=>{E(Number(l))}),[l]);const b=e=>{d&&d(e)},v=Number(s)-5,N=(h-v)/(Number(r)+5-v)*100;return e.createElement("div",{className:f("range-wrapper",p,{disabled:m}),style:{width:`${o}px`}},e.createElement("input",{type:"range",className:f("range-slider",u),id:n,value:h,min:s,max:r,step:i,onChange:e=>{const t=Number(e.target.value);E(t),c?.(e)},onMouseUp:b,onKeyUp:b,disabled:m,style:{"--slider-progress":`${N}%`},...g}))},Ce=[{label:"00",value:0},{label:"05",value:300},{label:"10",value:600},{label:"15",value:900},{label:"20",value:1200},{label:"25",value:1500},{label:"30",value:1800},{label:"35",value:2100},{label:"40",value:2400},{label:"45",value:2700},{label:"60",value:3600},{label:"75",value:4500},{label:"90",value:5400},{label:"105",value:6300},{label:"120",value:7200},{label:"150",value:9e3},{label:"180",value:10800},{label:"210",value:12600},{label:"240",value:14400}],ye=({onSelection:t,selectedTolerance:a,toleranceSign:n})=>e.createElement("div",{className:"tolerance-picker-section"},e.createElement("div",{className:`tolerance-grid ${n}-tolerance`},Ce.map((({label:l,value:s},r)=>e.createElement("button",{key:`${l}-${r}`,className:f("minute",{selected:a===s}),style:{gridArea:`a${r+1}`},onClick:()=>t(s)},`${"minus"===n?"-":"+"}${l}`))))),we=({onToleranceChange:n,toleranceValues:{minusTolerance:s,plusTolerance:r}={minusTolerance:Ce[0].value,plusTolerance:Ce[0].value},translateWarningMessage:i,...o})=>{const c=(e,t)=>`-${Ce[e]?.label||""}/+${Ce[t]?.label||""}`,[d,m]=a(!1),[u,p]=a(c(0,0)),[g,h]=a(void 0),E=l(null);return t((()=>{const e=Ce.findIndex((e=>e.value===s)),t=Ce.findIndex((e=>e.value===r));if(e<0||t<0){const t=e<0?s:r;h({status:"warning",message:i?.(t)||`${t} is not a valid tolerance value.`})}else h(void 0);p(c(e,t))}),[s,r]),e.createElement("div",{className:"tolerance-picker"},e.createElement("div",null,e.createElement(P,{...o,value:u,statusWithMessage:g,onClick:()=>m(!d),type:"text",ref:E})),e.createElement(ce,{inputRef:E,isOpen:d,onClose:()=>m(!1)},e.createElement("div",{className:"time-tolerance"},e.createElement(ye,{onSelection:e=>n({minusTolerance:e,plusTolerance:r}),selectedTolerance:s,toleranceSign:"minus"}),e.createElement("div",{className:"divider"}),e.createElement(ye,{onSelection:e=>n({minusTolerance:s,plusTolerance:e}),selectedTolerance:r,toleranceSign:"plus"}))))},ke=({label:t,tokens:n})=>{const[s,r]=a(n),[i,o]=a(""),[c,d]=a(null),m=l(null);return e.createElement("div",{className:"token-input-wrapper"},e.createElement("label",{className:"input-label"},t),e.createElement("div",{className:"tokens-wrapper",onClick:e=>{e.target===e.currentTarget&&m.current?.focus()}},s.map(((t,a)=>e.createElement("div",{key:`${t}-${a}`,onClick:()=>d(a),className:f("token-item-wrapper",{selected:c===a})},e.createElement("span",{className:"token-label"},t),e.createElement("span",{className:"token-close-btn",onClick:()=>r((e=>e.filter(((e,t)=>t!==a))))},e.createElement(u,null))))),e.createElement("input",{type:"text",value:i,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&""!==i.trim()&&(r((e=>[...e,i])),o(""))},className:"token-input",ref:m})))};export{C as Button,$ as Checkbox,W as CheckboxList,q as CheckboxesTree,x as ComboBox,de as DatePicker,P as Input,me as PasswordInput,ue as RadioButton,pe as RadioGroup,he as Select,fe as Slider,Ee as TextArea,Ne as TimePicker,ke as TokenInput,we as TolerancePicker,F as useDefaultComboBox};
|
|
1
|
+
import React, { useEffect, useState, useCallback, useRef, useMemo } from 'react';
|
|
2
|
+
import { Gear, Info, CheckCircle, Alert, Blocked, RequiredInput, X, XCircle, ChevronDown, ChevronLeft, ChevronRight, Calendar as Calendar$1, EyeClosed, Eye } from '@osrd-project/ui-icons';
|
|
3
|
+
import cx from 'classnames';
|
|
4
|
+
|
|
5
|
+
const Button = ({ label, variant = 'Primary', isLoading = false, isDisabled = false, leadingIcon = null, counter = null, size = 'large', onClick, ...btnAttrs }) => {
|
|
6
|
+
const handleClick = () => {
|
|
7
|
+
if (!isLoading && !isDisabled && onClick) {
|
|
8
|
+
onClick();
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
return (React.createElement("button", { ...btnAttrs, className: cx('button flex items-center', btnAttrs.className, variant.toLowerCase(), size.toLowerCase(), {
|
|
12
|
+
loading: isLoading,
|
|
13
|
+
}), onClick: handleClick, disabled: isDisabled || isLoading }, isLoading ? (React.createElement("span", { className: "icon" },
|
|
14
|
+
React.createElement(Gear, { variant: "fill", size: "lg" }))) : (React.createElement(React.Fragment, null,
|
|
15
|
+
leadingIcon && React.createElement("span", { className: "leading-icon mr-2" }, leadingIcon),
|
|
16
|
+
label,
|
|
17
|
+
counter !== null && React.createElement("span", { className: "counter ml-2" }, counter)))));
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const useOutsideClick = (ref, handler) => {
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
const handleClickOutside = (event) => {
|
|
23
|
+
if (ref.current && !ref.current.contains(event.target)) {
|
|
24
|
+
handler(event);
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
document.addEventListener('mousedown', handleClickOutside);
|
|
28
|
+
return () => {
|
|
29
|
+
document.removeEventListener('mousedown', handleClickOutside);
|
|
30
|
+
};
|
|
31
|
+
}, [ref, handler]);
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const Hint = ({ text }) => React.createElement("span", { className: "base-hint" }, text);
|
|
35
|
+
|
|
36
|
+
const InputStatusIcon = ({ status, small, className }) => {
|
|
37
|
+
const size = small ? 'sm' : 'lg';
|
|
38
|
+
return (React.createElement("span", { className: cx('status-icon', className, status) },
|
|
39
|
+
status === 'loading' && React.createElement(Gear, { size: size }),
|
|
40
|
+
status === 'info' && React.createElement(Info, { variant: "fill", size: size }),
|
|
41
|
+
status === 'success' && React.createElement(CheckCircle, { variant: "fill", size: size }),
|
|
42
|
+
status === 'warning' && React.createElement(Alert, { variant: "fill", size: size }),
|
|
43
|
+
status === 'error' && React.createElement(Blocked, { variant: "fill", size: size })));
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const Label = ({ htmlFor, text, required, hasHint, disabled, small = false }) => (React.createElement("div", { className: cx('base-label-wrapper', { 'has-hint': hasHint, small }) },
|
|
47
|
+
required && (React.createElement("span", { className: "required" },
|
|
48
|
+
React.createElement(RequiredInput, null))),
|
|
49
|
+
React.createElement("label", { className: cx('label', { disabled: disabled }), htmlFor: htmlFor }, text)));
|
|
50
|
+
|
|
51
|
+
const StatusMessage = ({ statusWithMessage, showIcon, small, onClose }) => {
|
|
52
|
+
const { tooltip, status, message } = statusWithMessage;
|
|
53
|
+
if (message === undefined)
|
|
54
|
+
return null;
|
|
55
|
+
return (React.createElement("div", { className: cx({
|
|
56
|
+
'status-message-wrapper': !tooltip,
|
|
57
|
+
'status-message-wrapper-tooltip': tooltip,
|
|
58
|
+
'tooltip-left': tooltip === 'left',
|
|
59
|
+
'tooltip-right': tooltip === 'right',
|
|
60
|
+
[status]: status,
|
|
61
|
+
}) },
|
|
62
|
+
showIcon && React.createElement(InputStatusIcon, { status: status, small: small }),
|
|
63
|
+
React.createElement("span", { className: cx('status-message', { [status]: status }) }, message),
|
|
64
|
+
status === 'info' && tooltip && (React.createElement("button", { className: "status-close", onClick: onClose },
|
|
65
|
+
React.createElement(X, { size: "sm" })))));
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const FieldWrapper = ({ id, label, hint, required, disabled, statusWithMessage, statusIconPosition = 'next-to-field', narrow = false, small = false, className, children, onCloseStatusMessage, }) => {
|
|
69
|
+
const statusClassname = statusWithMessage ? { [statusWithMessage.status]: true } : {};
|
|
70
|
+
const defaultTooltip = narrow ? 'left' : undefined;
|
|
71
|
+
if (narrow && required) {
|
|
72
|
+
throw new Error('narrow should not be used with required for now. This breaks the input UI.');
|
|
73
|
+
}
|
|
74
|
+
return (React.createElement("div", { className: cx('feed-back', statusClassname, className, { small, narrow }) },
|
|
75
|
+
React.createElement("div", { className: "custom-field" },
|
|
76
|
+
label && (React.createElement(Label, { htmlFor: id, text: label, required: required, hasHint: Boolean(hint), disabled: disabled, small: small })),
|
|
77
|
+
hint && React.createElement(Hint, { text: hint }),
|
|
78
|
+
React.createElement("div", { className: "field-and-status-icon" },
|
|
79
|
+
children,
|
|
80
|
+
statusWithMessage && statusIconPosition === 'next-to-field' && (React.createElement(InputStatusIcon, { status: statusWithMessage.status, small: small, className: "next-to-field" }))),
|
|
81
|
+
statusWithMessage && (React.createElement(StatusMessage, { small: small, statusWithMessage: {
|
|
82
|
+
...statusWithMessage,
|
|
83
|
+
tooltip: statusWithMessage?.tooltip ?? defaultTooltip,
|
|
84
|
+
}, showIcon: statusIconPosition === 'before-status-message', onClose: onCloseStatusMessage })))));
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
function useFocusByTab({ onBlur, onKeyUp }) {
|
|
88
|
+
const [isFocusByTab, setIsFocusByTab] = useState(false);
|
|
89
|
+
const handleKeyUp = useCallback((event) => {
|
|
90
|
+
if (event.key === 'Tab')
|
|
91
|
+
setIsFocusByTab(true);
|
|
92
|
+
onKeyUp?.(event);
|
|
93
|
+
}, [onKeyUp]);
|
|
94
|
+
const handleBlur = useCallback((event) => {
|
|
95
|
+
setIsFocusByTab(false);
|
|
96
|
+
onBlur?.(event);
|
|
97
|
+
}, [onBlur]);
|
|
98
|
+
return { handleKeyUp, handleBlur, isFocusByTab };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const InputAffix = ({ value, type, disabled, readOnly }) => {
|
|
102
|
+
const isContentWithCallback = typeof value === 'object' && value !== null && 'onClickCallback' in value;
|
|
103
|
+
const spanContent = isContentWithCallback
|
|
104
|
+
? value.content
|
|
105
|
+
: value;
|
|
106
|
+
const wrapperProps = isContentWithCallback
|
|
107
|
+
? { onClick: value.onClickCallback }
|
|
108
|
+
: {};
|
|
109
|
+
return (React.createElement("div", { className: cx(`${type}-content-wrapper`, { disabled, 'read-only': readOnly }), ...wrapperProps },
|
|
110
|
+
React.createElement("span", { className: `${type}-content` }, spanContent)));
|
|
111
|
+
};
|
|
112
|
+
const Input = React.forwardRef(({ id, label, type, hint, leadingContent, trailingContent, required, disabled = false, readOnly = false, statusWithMessage, narrow, inputFieldWrapperClassname = '', small = false, withIcons = [], onKeyUp, onBlur, onCloseStatusMessage, ...rest }, ref) => {
|
|
113
|
+
const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
|
|
114
|
+
return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, disabled: disabled, required: required, small: small, statusIconPosition: statusWithMessage?.tooltip || narrow ? 'before-status-message' : undefined, narrow: narrow, className: cx('input-field-wrapper', inputFieldWrapperClassname), onCloseStatusMessage: onCloseStatusMessage },
|
|
115
|
+
leadingContent && (React.createElement(InputAffix, { value: leadingContent, type: "leading", disabled: disabled, readOnly: readOnly })),
|
|
116
|
+
React.createElement("div", { className: cx('input-container', {
|
|
117
|
+
'focused-by-tab': isFocusByTab,
|
|
118
|
+
}) },
|
|
119
|
+
React.createElement("input", { ref: ref, className: cx('input', {
|
|
120
|
+
'with-leading-only': leadingContent && !trailingContent,
|
|
121
|
+
'with-trailing-only': trailingContent && !leadingContent,
|
|
122
|
+
'with-leading-and-trailing': leadingContent && trailingContent,
|
|
123
|
+
[`with-icons-${withIcons.length}`]: withIcons.length > 0,
|
|
124
|
+
[statusWithMessage?.status || '']: !!statusWithMessage,
|
|
125
|
+
}), id: id, type: type, disabled: disabled, readOnly: readOnly, onKeyUp: handleKeyUp, onBlur: handleBlur, ...rest }),
|
|
126
|
+
React.createElement("div", { className: cx('input-icons', {
|
|
127
|
+
small,
|
|
128
|
+
}) }, withIcons.map((iconConfig, index) => (React.createElement("span", { key: index, className: iconConfig?.className, onClick: iconConfig.action }, iconConfig.icon))))),
|
|
129
|
+
trailingContent && (React.createElement(InputAffix, { value: trailingContent, type: "trailing", disabled: disabled, readOnly: readOnly }))));
|
|
130
|
+
});
|
|
131
|
+
Input.displayName = 'Input';
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* ComboBox component
|
|
135
|
+
*
|
|
136
|
+
* You can use the hook useDefaultComboBox to get the default behavior.
|
|
137
|
+
* See the stories.
|
|
138
|
+
*/
|
|
139
|
+
const ComboBox = ({ suggestions, customLabel, numberOfSuggestionsToShow = 5, value, small, getSuggestionLabel, onChange, onSelectSuggestion, resetSuggestions, ...inputProps }) => {
|
|
140
|
+
const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(-1);
|
|
141
|
+
const [inputValue, setInputValue] = useState('');
|
|
142
|
+
const [isInputFocused, setIsInputFocused] = useState(false);
|
|
143
|
+
const suggestionRefs = useRef([]);
|
|
144
|
+
const inputRef = useRef(null);
|
|
145
|
+
const wrapperRef = useRef(null);
|
|
146
|
+
const focusInput = useCallback(() => {
|
|
147
|
+
inputRef.current?.focus();
|
|
148
|
+
}, [inputRef]);
|
|
149
|
+
const removeFocus = () => {
|
|
150
|
+
setIsInputFocused(false);
|
|
151
|
+
setActiveSuggestionIndex(-1);
|
|
152
|
+
setTimeout(() => {
|
|
153
|
+
inputRef.current?.blur();
|
|
154
|
+
}, 0);
|
|
155
|
+
resetSuggestions();
|
|
156
|
+
};
|
|
157
|
+
/* eslint-disable react-hooks/exhaustive-deps */
|
|
158
|
+
useEffect(() => {
|
|
159
|
+
if (value) {
|
|
160
|
+
setInputValue(getSuggestionLabel(value));
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
setInputValue('');
|
|
164
|
+
}
|
|
165
|
+
}, [value]);
|
|
166
|
+
const showSuggestions = useMemo(() => isInputFocused && suggestions.length > 0 && !inputProps.disabled, [isInputFocused, suggestions.length, inputProps.disabled]);
|
|
167
|
+
// behavior
|
|
168
|
+
const handleInputChange = (e) => {
|
|
169
|
+
onChange?.(e);
|
|
170
|
+
setInputValue(e.currentTarget.value);
|
|
171
|
+
};
|
|
172
|
+
const selectSuggestion = (index) => {
|
|
173
|
+
const selectedSuggestion = suggestions.at(index);
|
|
174
|
+
onSelectSuggestion(selectedSuggestion);
|
|
175
|
+
setInputValue(getSuggestionLabel(selectedSuggestion));
|
|
176
|
+
removeFocus();
|
|
177
|
+
};
|
|
178
|
+
const closeSuggestions = () => {
|
|
179
|
+
setInputValue(value ? getSuggestionLabel(value) : '');
|
|
180
|
+
removeFocus();
|
|
181
|
+
};
|
|
182
|
+
const handleKeyDown = (e) => {
|
|
183
|
+
if (e.key === 'ArrowDown') {
|
|
184
|
+
setActiveSuggestionIndex((prev) => {
|
|
185
|
+
const newIndex = prev < suggestions.length - 1 ? prev + 1 : prev;
|
|
186
|
+
if (suggestionRefs.current[newIndex]) {
|
|
187
|
+
suggestionRefs.current[newIndex].scrollIntoView({
|
|
188
|
+
block: 'nearest',
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
return newIndex;
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
else if (e.key === 'ArrowUp') {
|
|
195
|
+
setActiveSuggestionIndex((prev) => {
|
|
196
|
+
const newIndex = prev > 0 ? prev - 1 : prev;
|
|
197
|
+
if (suggestionRefs.current[newIndex]) {
|
|
198
|
+
suggestionRefs.current[newIndex].scrollIntoView({
|
|
199
|
+
block: 'nearest',
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
return newIndex;
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
else if ((e.key === 'Enter' || e.key === 'Tab') && activeSuggestionIndex >= 0) {
|
|
206
|
+
selectSuggestion(activeSuggestionIndex);
|
|
207
|
+
}
|
|
208
|
+
else if (e.key === 'Escape') {
|
|
209
|
+
closeSuggestions();
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
const handleInputFocus = (e) => {
|
|
213
|
+
e.stopPropagation();
|
|
214
|
+
setIsInputFocused(true);
|
|
215
|
+
};
|
|
216
|
+
const clearInput = () => {
|
|
217
|
+
setInputValue('');
|
|
218
|
+
onSelectSuggestion(undefined);
|
|
219
|
+
resetSuggestions();
|
|
220
|
+
focusInput();
|
|
221
|
+
};
|
|
222
|
+
useOutsideClick(wrapperRef, closeSuggestions);
|
|
223
|
+
const inputIcons = useMemo(() => [
|
|
224
|
+
// Conditionally include the clear icon only when input is not empty
|
|
225
|
+
...(value
|
|
226
|
+
? [
|
|
227
|
+
{
|
|
228
|
+
icon: React.createElement(XCircle, { variant: "fill" }),
|
|
229
|
+
action: clearInput,
|
|
230
|
+
className: 'clear-icon',
|
|
231
|
+
},
|
|
232
|
+
]
|
|
233
|
+
: []),
|
|
234
|
+
// chevron of the select
|
|
235
|
+
{
|
|
236
|
+
icon: React.createElement(ChevronDown, { size: small ? 'sm' : 'lg' }),
|
|
237
|
+
action: focusInput,
|
|
238
|
+
className: cx('chevron-icon', {
|
|
239
|
+
disabled: inputProps.disabled,
|
|
240
|
+
}),
|
|
241
|
+
},
|
|
242
|
+
], [value]);
|
|
243
|
+
return (React.createElement("div", { className: "combo-box", style: { '--number-of-suggestions': numberOfSuggestionsToShow }, ref: wrapperRef },
|
|
244
|
+
customLabel && React.createElement("label", { htmlFor: inputProps.id }, customLabel),
|
|
245
|
+
React.createElement(Input, { ...inputProps, ref: inputRef, value: inputValue, onChange: handleInputChange, onKeyDown: handleKeyDown, onFocus: handleInputFocus, withIcons: inputIcons, small: small }),
|
|
246
|
+
showSuggestions && (React.createElement("ul", { className: "suggestions-list" }, suggestions.map((suggestion, index) => (React.createElement("li", { ref: (el) => (suggestionRefs.current[index] = el), key: `${getSuggestionLabel(suggestion)}-${index}`, className: cx('suggestion-item', {
|
|
247
|
+
active: index === activeSuggestionIndex,
|
|
248
|
+
selected: value && getSuggestionLabel(value) === getSuggestionLabel(suggestion),
|
|
249
|
+
small,
|
|
250
|
+
}), onClick: () => selectSuggestion(index), onMouseDown: (e) => e.preventDefault(), onMouseEnter: () => {
|
|
251
|
+
setActiveSuggestionIndex(index);
|
|
252
|
+
} }, getSuggestionLabel(suggestion))))))));
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const normalizeString = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
|
256
|
+
const defaultFilterSuggestions = (getSuggestionLabel, suggestions, query) => {
|
|
257
|
+
const input = normalizeString(query).trim().toLowerCase();
|
|
258
|
+
if (!input) {
|
|
259
|
+
return suggestions;
|
|
260
|
+
}
|
|
261
|
+
const getSuggestionScore = (suggestion) => {
|
|
262
|
+
const suggestionLabel = normalizeString(getSuggestionLabel(suggestion).toLowerCase());
|
|
263
|
+
if (suggestionLabel.startsWith(input)) {
|
|
264
|
+
return 2;
|
|
265
|
+
}
|
|
266
|
+
if (suggestionLabel.includes(input)) {
|
|
267
|
+
return 1;
|
|
268
|
+
}
|
|
269
|
+
return 0;
|
|
270
|
+
};
|
|
271
|
+
return suggestions
|
|
272
|
+
.map((suggestion) => ({
|
|
273
|
+
suggestion,
|
|
274
|
+
score: getSuggestionScore(suggestion),
|
|
275
|
+
}))
|
|
276
|
+
.filter(({ score }) => score > 0)
|
|
277
|
+
.sort(({ score: scoreA }, { score: scoreB }) => scoreB - scoreA)
|
|
278
|
+
.map(({ suggestion }) => suggestion);
|
|
279
|
+
};
|
|
280
|
+
const useDefaultComboBox = (suggestions, getSuggestionLabel) => {
|
|
281
|
+
const [query, setQuery] = useState('');
|
|
282
|
+
const filteredSuggestions = useMemo(() => defaultFilterSuggestions(getSuggestionLabel, suggestions, query),
|
|
283
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
284
|
+
[suggestions, query]);
|
|
285
|
+
const onChange = (e) => {
|
|
286
|
+
setQuery(e.target.value);
|
|
287
|
+
};
|
|
288
|
+
const resetSuggestions = () => {
|
|
289
|
+
setQuery('');
|
|
290
|
+
};
|
|
291
|
+
return { suggestions: filteredSuggestions, onChange, resetSuggestions };
|
|
292
|
+
};
|
|
293
|
+
|
|
294
|
+
const Checkbox = ({ label, small, hint, disabled, checked, readOnly, isIndeterminate = false, onClick, onKeyUp, onBlur, ...rest }) => {
|
|
295
|
+
const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
|
|
296
|
+
const handleClick = (e) => {
|
|
297
|
+
if (readOnly) {
|
|
298
|
+
e.preventDefault();
|
|
299
|
+
e.stopPropagation();
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
onClick?.(e);
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
return (React.createElement("label", { className: cx('custom-checkbox', { small }) },
|
|
306
|
+
React.createElement("input", {
|
|
307
|
+
//read-only state is not working on checkbox as well explain here : https://stackoverflow.com/a/70375659
|
|
308
|
+
className: cx({ 'read-only': readOnly }), type: "checkbox", checked: checked, disabled: disabled, ref: (input) => input && (input.indeterminate = isIndeterminate), onClick: handleClick, onBlur: handleBlur, onKeyUp: handleKeyUp, ...rest }),
|
|
309
|
+
React.createElement("span", { className: cx('checkmark', { 'focused-by-tab': isFocusByTab }) }),
|
|
310
|
+
label && React.createElement("div", { className: "label" }, label),
|
|
311
|
+
hint && React.createElement("span", { className: "hint" }, hint)));
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const CheckboxList = (checkBoxListprops) => {
|
|
315
|
+
const { items, onClickItem, small = false, label = '', readOnly = false, disabled = false, } = checkBoxListprops;
|
|
316
|
+
return (React.createElement(React.Fragment, null,
|
|
317
|
+
React.createElement("span", { className: "checkbox-list-label" }, label),
|
|
318
|
+
React.createElement("ul", { className: cx('checkbox-list', { small: small }) }, items.map((item) => {
|
|
319
|
+
const { id, props, items: subItems } = item;
|
|
320
|
+
return (React.createElement("li", { key: id },
|
|
321
|
+
React.createElement(Checkbox, { small: small, onClick: (e) => onClickItem(e, item), checked: item.props.checked, isIndeterminate: item.props.isIndeterminate, ...props, disabled: disabled, readOnly: readOnly }),
|
|
322
|
+
subItems && React.createElement(CheckboxList, { ...checkBoxListprops, items: subItems })));
|
|
323
|
+
}))));
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
var CheckboxState;
|
|
327
|
+
(function (CheckboxState) {
|
|
328
|
+
CheckboxState[CheckboxState["UNCHECKED"] = 0] = "UNCHECKED";
|
|
329
|
+
CheckboxState[CheckboxState["CHECKED"] = 1] = "CHECKED";
|
|
330
|
+
CheckboxState[CheckboxState["INDETERMINATE"] = 2] = "INDETERMINATE";
|
|
331
|
+
})(CheckboxState || (CheckboxState = {}));
|
|
332
|
+
|
|
333
|
+
const traverseTree = (items, onVisit, parent) => {
|
|
334
|
+
items.forEach((item) => {
|
|
335
|
+
onVisit(item, parent);
|
|
336
|
+
if (item.items && item.items.length > 0) {
|
|
337
|
+
traverseTree(item.items, onVisit, item);
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
const buildRelationshipMaps = (items) => {
|
|
342
|
+
const parentChildrenMap = {};
|
|
343
|
+
const childrenParentMap = {};
|
|
344
|
+
traverseTree(items, (item, parent) => {
|
|
345
|
+
if (parent?.id !== undefined) {
|
|
346
|
+
if (!parentChildrenMap[parent.id]) {
|
|
347
|
+
parentChildrenMap[parent.id] = [];
|
|
348
|
+
}
|
|
349
|
+
parentChildrenMap[parent.id].push(item.id);
|
|
350
|
+
childrenParentMap[item.id] = parent.id;
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
return { parentChildrenMap, childrenParentMap };
|
|
354
|
+
};
|
|
355
|
+
const updateItemAndDescendantsStates = (itemId, newItemStates, parentChildrenMap, itemStates) => {
|
|
356
|
+
itemStates[itemId] = newItemStates;
|
|
357
|
+
parentChildrenMap[itemId]?.forEach((child) => updateItemAndDescendantsStates(child, newItemStates, parentChildrenMap, itemStates));
|
|
358
|
+
};
|
|
359
|
+
const updateAscendantsStates = (childId, itemStates, relastionShipMap) => {
|
|
360
|
+
const { parentChildrenMap, childrenParentMap } = relastionShipMap;
|
|
361
|
+
const parentId = childrenParentMap[childId];
|
|
362
|
+
if (parentId === undefined)
|
|
363
|
+
return;
|
|
364
|
+
const siblings = parentChildrenMap[parentId];
|
|
365
|
+
const siblingStates = siblings.map((siblingId) => itemStates[siblingId]);
|
|
366
|
+
let parentState;
|
|
367
|
+
if (siblingStates.every((state) => state === CheckboxState.CHECKED)) {
|
|
368
|
+
parentState = CheckboxState.CHECKED;
|
|
369
|
+
}
|
|
370
|
+
else if (siblingStates.every((state) => state === CheckboxState.UNCHECKED)) {
|
|
371
|
+
parentState = CheckboxState.UNCHECKED;
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
parentState = CheckboxState.INDETERMINATE;
|
|
375
|
+
}
|
|
376
|
+
itemStates[parentId] = parentState;
|
|
377
|
+
updateAscendantsStates(parentId, itemStates, { parentChildrenMap, childrenParentMap });
|
|
378
|
+
};
|
|
379
|
+
const updateItemStates = (itemsTree, initialItemStates, clickedItemId) => {
|
|
380
|
+
const newItemStates = { ...initialItemStates };
|
|
381
|
+
const newClickedItemState = newItemStates[clickedItemId] === CheckboxState.CHECKED
|
|
382
|
+
? CheckboxState.UNCHECKED
|
|
383
|
+
: CheckboxState.CHECKED;
|
|
384
|
+
const { parentChildrenMap, childrenParentMap } = buildRelationshipMaps(itemsTree);
|
|
385
|
+
updateItemAndDescendantsStates(clickedItemId, newClickedItemState, parentChildrenMap, newItemStates);
|
|
386
|
+
updateAscendantsStates(clickedItemId, newItemStates, { parentChildrenMap, childrenParentMap });
|
|
387
|
+
return newItemStates;
|
|
388
|
+
};
|
|
389
|
+
const computeInitialItemStates = (items) => {
|
|
390
|
+
const itemStates = {};
|
|
391
|
+
traverseTree(items, (item) => {
|
|
392
|
+
if (item.props.isIndeterminate)
|
|
393
|
+
itemStates[item.id] = CheckboxState.INDETERMINATE;
|
|
394
|
+
else
|
|
395
|
+
itemStates[item.id] = item.props.checked ? CheckboxState.CHECKED : CheckboxState.UNCHECKED;
|
|
396
|
+
});
|
|
397
|
+
return itemStates;
|
|
398
|
+
};
|
|
399
|
+
const applyStateToItem = (itemsTree, itemStates) => {
|
|
400
|
+
const clonedItemsTree = JSON.parse(JSON.stringify(itemsTree));
|
|
401
|
+
traverseTree(clonedItemsTree, (item) => {
|
|
402
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
403
|
+
const { checked, isIndeterminate, ...otherProps } = item.props;
|
|
404
|
+
item.props = otherProps;
|
|
405
|
+
if (itemStates[item.id] === CheckboxState.INDETERMINATE)
|
|
406
|
+
item.props.isIndeterminate = true;
|
|
407
|
+
else if (itemStates[item.id] === CheckboxState.CHECKED)
|
|
408
|
+
item.props.checked = true;
|
|
409
|
+
else
|
|
410
|
+
item.props.checked = false;
|
|
411
|
+
});
|
|
412
|
+
return clonedItemsTree;
|
|
413
|
+
};
|
|
414
|
+
const computeNewItemsTree = (itemsTree, clickedItem) => {
|
|
415
|
+
const initialItemStates = computeInitialItemStates(itemsTree);
|
|
416
|
+
const updatedItemStates = updateItemStates(itemsTree, initialItemStates, clickedItem.id);
|
|
417
|
+
return applyStateToItem(itemsTree, updatedItemStates);
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
const CheckboxesTree = ({ items, small, id, label, hint, statusWithMessage, disabled, required, readOnly, onChange, computeNewItemsTree: computeNewItemsTree$1, }) => {
|
|
421
|
+
const handleClick = (e, item) => {
|
|
422
|
+
const newItems = computeNewItemsTree$1
|
|
423
|
+
? computeNewItemsTree$1(items, item)
|
|
424
|
+
: computeNewItemsTree(items, item);
|
|
425
|
+
onChange?.(newItems, item);
|
|
426
|
+
item.props.onClick?.(e);
|
|
427
|
+
};
|
|
428
|
+
return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, statusIconPosition: "before-status-message", disabled: disabled, required: required, small: small },
|
|
429
|
+
React.createElement(CheckboxList, { small: small, items: items, disabled: disabled, readOnly: readOnly, onClickItem: handleClick })));
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
const INVALID_SELECTED_SLOT_ERROR = 'Invalid selectedSlot: If start and end are defined, the start date must be before the end date.';
|
|
433
|
+
const INVALID_SELECTABLE_SLOT_ERROR = 'Invalid selectableSlot: If start and end are defined, the start date must be before the end date.';
|
|
434
|
+
const INVALID_SELECTED_SLOT_BASED_ON_SELECTABLE_SLOT_ERROR = 'selectedSlot must be within selectableSlot';
|
|
435
|
+
const INVALID_INITIAL_DATE_ERROR = 'initialDate must be within selectableSlot';
|
|
436
|
+
const containsOnlyNumbersAndSlashes = (s) => /^[0-9/]+$/.test(s);
|
|
437
|
+
/**
|
|
438
|
+
* Normalize the given date to midnight
|
|
439
|
+
* @param date The date to normalize
|
|
440
|
+
* @returns The normalized date
|
|
441
|
+
*/
|
|
442
|
+
function normalizeDate(date) {
|
|
443
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Check if the given slot is valid
|
|
447
|
+
* @param slot The slot to check
|
|
448
|
+
* @returns True if the slot is valid, false otherwise
|
|
449
|
+
*/
|
|
450
|
+
function isValidSlot(slot) {
|
|
451
|
+
if (slot.start && slot.end) {
|
|
452
|
+
return normalizeDate(slot.start).getTime() <= normalizeDate(slot.end).getTime();
|
|
453
|
+
}
|
|
454
|
+
return true;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Get the dates from the previous month that are in the first week of the current month
|
|
458
|
+
* @param month The month of the current date
|
|
459
|
+
* @param fullYear The year of the current date
|
|
460
|
+
* @returns An array of dates from the previous month that are in the first week of the current month
|
|
461
|
+
*/
|
|
462
|
+
function getDatesFromPreviousMonthInFirstWeek(month, fullYear) {
|
|
463
|
+
const firstDayOfMonth = new Date(fullYear, month, 1);
|
|
464
|
+
const firstDayOfWeek = firstDayOfMonth.getDay();
|
|
465
|
+
// if the first day of the week is Monday, we don't need to return any dates from the previous month
|
|
466
|
+
if (firstDayOfWeek === 1) {
|
|
467
|
+
return [];
|
|
468
|
+
}
|
|
469
|
+
const daysFromPrevMonth = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1;
|
|
470
|
+
const lastDayPrevMonth = new Date(fullYear, month, 0);
|
|
471
|
+
const dates = [];
|
|
472
|
+
for (let i = 0; i < daysFromPrevMonth; i++) {
|
|
473
|
+
const day = lastDayPrevMonth.getDate() - i;
|
|
474
|
+
dates.unshift(new Date(lastDayPrevMonth.getFullYear(), lastDayPrevMonth.getMonth(), day));
|
|
475
|
+
}
|
|
476
|
+
return dates;
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Get the dates from the next month that are in the last week of the current month
|
|
480
|
+
* @param month The month of the current date
|
|
481
|
+
* @param fullYear The year of the current date
|
|
482
|
+
* @returns An array of dates from the next month that are in the last week of the current month
|
|
483
|
+
*/
|
|
484
|
+
function getDatesFromNextMonthInLastWeek(month, fullYear) {
|
|
485
|
+
const lastDayOfMonth = new Date(fullYear, month + 1, 0);
|
|
486
|
+
const lastDayOfWeek = lastDayOfMonth.getDay();
|
|
487
|
+
const daysFromNextMonth = (7 - lastDayOfWeek) % 7;
|
|
488
|
+
if (daysFromNextMonth === 0) {
|
|
489
|
+
return [];
|
|
490
|
+
}
|
|
491
|
+
const nextMonth = new Date(fullYear, month + 1, 1);
|
|
492
|
+
const dates = [];
|
|
493
|
+
for (let i = 0; i < daysFromNextMonth; i++) {
|
|
494
|
+
const day = i + 1;
|
|
495
|
+
dates.push(new Date(nextMonth.getFullYear(), nextMonth.getMonth(), day));
|
|
496
|
+
}
|
|
497
|
+
return dates;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Get all the dates in the month of the given date
|
|
501
|
+
* @param month The month of the current date
|
|
502
|
+
* @param fullYear The year of the current date
|
|
503
|
+
* @returns An array of all the dates in the month of the given date
|
|
504
|
+
*/
|
|
505
|
+
function getAllDatesInMonth(month, fullYear) {
|
|
506
|
+
const lastDayOfMonth = new Date(fullYear, month + 1, 0);
|
|
507
|
+
const totalDaysInMonth = lastDayOfMonth.getDate();
|
|
508
|
+
const dates = [];
|
|
509
|
+
for (let day = 1; day <= totalDaysInMonth; day++) {
|
|
510
|
+
dates.push(new Date(fullYear, month, day));
|
|
511
|
+
}
|
|
512
|
+
return dates;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Check if the given dates are the same day
|
|
516
|
+
* @param date1 The first date
|
|
517
|
+
* @param date2 The second date
|
|
518
|
+
* @returns True if the dates are the same day, false otherwise
|
|
519
|
+
*/
|
|
520
|
+
function isSameDay(date1, date2) {
|
|
521
|
+
if (!date1 || !date2) {
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
return (date1.getDate() === date2.getDate() &&
|
|
525
|
+
date1.getMonth() === date2.getMonth() &&
|
|
526
|
+
date1.getFullYear() === date2.getFullYear());
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Check if the given date is within the given slot
|
|
530
|
+
* if the slot is not provided, the date is considered to be within the slot
|
|
531
|
+
* if a boundary of the slot is not provided, it's considered to be an open boundary
|
|
532
|
+
* @param date The date to check
|
|
533
|
+
* @param slot The slot to check
|
|
534
|
+
* @returns True if the date is within the slot, false otherwise
|
|
535
|
+
*/
|
|
536
|
+
function isWithinInterval(date, slot) {
|
|
537
|
+
if (!slot)
|
|
538
|
+
return true;
|
|
539
|
+
const normalizedDate = normalizeDate(date);
|
|
540
|
+
const normalizedStart = slot.start ? normalizeDate(slot.start) : undefined;
|
|
541
|
+
const normalizedEnd = slot.end ? normalizeDate(slot.end) : undefined;
|
|
542
|
+
const isAfterStart = normalizedStart ? normalizedDate >= normalizedStart : true;
|
|
543
|
+
const isBeforeEnd = normalizedEnd ? normalizedDate <= normalizedEnd : true;
|
|
544
|
+
return isAfterStart && isBeforeEnd;
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Generates a list of dates, each representing the start of a month,
|
|
548
|
+
* starting from a given date and continuing for a specified number of months.
|
|
549
|
+
* This function correctly handles year rollover.
|
|
550
|
+
* @param startDate - The date from which to start generating month start dates.
|
|
551
|
+
* @param monthsCount - The number of month start dates to generate.
|
|
552
|
+
* @returns An array of Dates, each set to the first day of consecutive months starting from startDate.
|
|
553
|
+
*/
|
|
554
|
+
function generateSequentialDates(startDate, monthsCount) {
|
|
555
|
+
const dates = [];
|
|
556
|
+
for (let i = 0; i < monthsCount; i++) {
|
|
557
|
+
const date = new Date(startDate);
|
|
558
|
+
date.setMonth(startDate.getMonth() + i, 1);
|
|
559
|
+
dates.push(new Date(date.getFullYear(), date.getMonth(), 1));
|
|
560
|
+
}
|
|
561
|
+
return dates;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Format the given date as a string in the format 'dd/mm/yy'.
|
|
565
|
+
* @param date The date to format
|
|
566
|
+
* @returns The formatted date string
|
|
567
|
+
*/
|
|
568
|
+
function formatDateString(date) {
|
|
569
|
+
if (!date)
|
|
570
|
+
return '';
|
|
571
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
572
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
573
|
+
const year = String(date.getFullYear()).slice(-2);
|
|
574
|
+
return `${day}/${month}/${year}`;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Handles the logic for when a day is clicked on the calendar.
|
|
578
|
+
*
|
|
579
|
+
* @param clickedDate - The date that was clicked.
|
|
580
|
+
* @param isRangeMode - Whether the calendar is in range mode.
|
|
581
|
+
* @param prevSelectedSlot - The previously selected slot.
|
|
582
|
+
* Spec 1: If the user clicks on a single date, that date is set as the start date of the slot.
|
|
583
|
+
* Spec 2: If the user selects the same end date as the start date, clear the slot
|
|
584
|
+
* Spec 3: If the user clicks on a date that is before the currently selected start date, the new date becomes the start date and the previous start date becomes the end date.
|
|
585
|
+
* Spec 4: If the user clicks on a date that is after the currently selected start date, that date becomes the end date of the slot.
|
|
586
|
+
* Spec 5: If a slot is already defined (i.e., both start and end dates are defined) and the user clicks on a new date, the existing slot is cleared and the new date becomes the start date of the new slot.
|
|
587
|
+
*/
|
|
588
|
+
function computeNewSelectedSlot(clickedDate, prevSelectedSlot) {
|
|
589
|
+
if (!prevSelectedSlot || prevSelectedSlot?.start === null) {
|
|
590
|
+
// Spec 1
|
|
591
|
+
return { start: clickedDate, end: null };
|
|
592
|
+
}
|
|
593
|
+
else if (!prevSelectedSlot.end) {
|
|
594
|
+
if (normalizeDate(clickedDate).getTime() === normalizeDate(prevSelectedSlot.start).getTime()) {
|
|
595
|
+
// Spec 2
|
|
596
|
+
return undefined;
|
|
597
|
+
}
|
|
598
|
+
else if (normalizeDate(clickedDate) < normalizeDate(prevSelectedSlot.start)) {
|
|
599
|
+
// Spec 3
|
|
600
|
+
return { start: clickedDate, end: prevSelectedSlot.start };
|
|
601
|
+
}
|
|
602
|
+
else {
|
|
603
|
+
// Spec 4
|
|
604
|
+
return { start: prevSelectedSlot.start, end: clickedDate };
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
else {
|
|
608
|
+
// Spec 5
|
|
609
|
+
return { start: clickedDate, end: null };
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Format the selected slot to a string that can be displayed in the input field.
|
|
614
|
+
* @param slot The new selected slot
|
|
615
|
+
* @returns The formatted string
|
|
616
|
+
* Spec 0: If the slot is undefined, return an empty string.
|
|
617
|
+
* Spec 1: If the start and end dates are the same, return the formatted date of the start date.
|
|
618
|
+
* Spec 2: If the start and end dates are in the same year, return the formatted start date without the year and end date.
|
|
619
|
+
* Spec 3: If the start and end dates are in different years, return the formatted start date and end date with the year.
|
|
620
|
+
*/
|
|
621
|
+
function formatSlotToInputValue(slot) {
|
|
622
|
+
let formattedDate = '';
|
|
623
|
+
if (slot) {
|
|
624
|
+
const { start, end } = slot;
|
|
625
|
+
if (isSameDay(start, end)) {
|
|
626
|
+
formattedDate = formatDateString(start);
|
|
627
|
+
}
|
|
628
|
+
else {
|
|
629
|
+
let formattedStartDate = formatDateString(start);
|
|
630
|
+
if (start && end && start.getFullYear() === end.getFullYear()) {
|
|
631
|
+
formattedStartDate = formattedStartDate.slice(0, 5);
|
|
632
|
+
}
|
|
633
|
+
formattedDate = `${formattedStartDate} - ${formatDateString(end)}`;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
return formattedDate;
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Format the new value to a string that can be displayed in the input field.
|
|
640
|
+
* @param value The new value
|
|
641
|
+
* @param isRangeMode Whether the calendar is in range mode
|
|
642
|
+
* @returns The formatted string
|
|
643
|
+
*/
|
|
644
|
+
function formatInputValue({ value, isRangeMode }) {
|
|
645
|
+
if (isRangeMode) {
|
|
646
|
+
return formatSlotToInputValue(value);
|
|
647
|
+
}
|
|
648
|
+
return formatDateString(value);
|
|
649
|
+
}
|
|
650
|
+
function formatValueToSlot({ value, isRangeMode }) {
|
|
651
|
+
if (isRangeMode) {
|
|
652
|
+
return value;
|
|
653
|
+
}
|
|
654
|
+
return value ? { start: value, end: value } : value;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Validates the selected and selectable slots as well as the initial date.
|
|
658
|
+
* @param selectedSlot The selected slot to validate.
|
|
659
|
+
* @param selectableSlot The selectable slot to validate.
|
|
660
|
+
* @param date The date to validate.
|
|
661
|
+
*
|
|
662
|
+
* Three main validation checks are performed:
|
|
663
|
+
* - Check if the selected and selectable slots are valid.
|
|
664
|
+
* - Ensures the selected slot is within the selectable slot.
|
|
665
|
+
* - Ensures the initial date is within the selectable slot
|
|
666
|
+
*/
|
|
667
|
+
function validateSlots(selectedSlot, selectableSlot, date) {
|
|
668
|
+
if (selectedSlot && !isValidSlot(selectedSlot)) {
|
|
669
|
+
throw new Error(INVALID_SELECTED_SLOT_ERROR);
|
|
670
|
+
}
|
|
671
|
+
if (selectableSlot && !isValidSlot(selectableSlot)) {
|
|
672
|
+
throw new Error(INVALID_SELECTABLE_SLOT_ERROR);
|
|
673
|
+
}
|
|
674
|
+
if (selectedSlot?.start &&
|
|
675
|
+
selectedSlot?.end &&
|
|
676
|
+
selectableSlot?.start &&
|
|
677
|
+
selectableSlot?.end &&
|
|
678
|
+
(normalizeDate(selectedSlot.start) < normalizeDate(selectableSlot.start) ||
|
|
679
|
+
normalizeDate(selectedSlot.end) > normalizeDate(selectableSlot.end))) {
|
|
680
|
+
throw new Error(INVALID_SELECTED_SLOT_BASED_ON_SELECTABLE_SLOT_ERROR);
|
|
681
|
+
}
|
|
682
|
+
if (date &&
|
|
683
|
+
selectableSlot?.start &&
|
|
684
|
+
selectableSlot?.end &&
|
|
685
|
+
(normalizeDate(date) < normalizeDate(selectableSlot.start) ||
|
|
686
|
+
normalizeDate(date) > normalizeDate(selectableSlot.end))) {
|
|
687
|
+
throw new Error(INVALID_INITIAL_DATE_ERROR);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
function useCalendar({ displayedMonthStartDate, selectableSlot, selectedSlot, }) {
|
|
692
|
+
const referenceDate = selectableSlot?.start ?? new Date();
|
|
693
|
+
referenceDate.setHours(0, 0, 0, 0);
|
|
694
|
+
const displayedYear = displayedMonthStartDate.getFullYear();
|
|
695
|
+
const displayedMonth = displayedMonthStartDate.getMonth();
|
|
696
|
+
const daysInMonth = getAllDatesInMonth(displayedMonth, displayedYear);
|
|
697
|
+
const daysInLastMonth = getDatesFromPreviousMonthInFirstWeek(displayedMonth, displayedYear);
|
|
698
|
+
const daysInNextMonth = getDatesFromNextMonthInLastWeek(displayedMonth, displayedYear);
|
|
699
|
+
const allDays = [...daysInLastMonth, ...daysInMonth, ...daysInNextMonth];
|
|
700
|
+
const buildDayWrapperClassName = (date) => {
|
|
701
|
+
const isStart = (selectedSlot && isSameDay(date, selectedSlot.start)) || false;
|
|
702
|
+
const isEnd = (selectedSlot && isSameDay(date, selectedSlot.end)) || false;
|
|
703
|
+
const withinSelectedSlot = (selectedSlot?.start && selectedSlot.end && isWithinInterval(date, selectedSlot)) ||
|
|
704
|
+
isStart ||
|
|
705
|
+
isEnd;
|
|
706
|
+
const insideSelectableSlot = isWithinInterval(date, selectableSlot);
|
|
707
|
+
let classNames = {
|
|
708
|
+
'inside-selectable-slot': insideSelectableSlot,
|
|
709
|
+
'outside-selectable-slot': !insideSelectableSlot,
|
|
710
|
+
'current-month': date.getMonth() === displayedMonth,
|
|
711
|
+
past: normalizeDate(date) < normalizeDate(referenceDate),
|
|
712
|
+
};
|
|
713
|
+
if (selectedSlot) {
|
|
714
|
+
classNames = {
|
|
715
|
+
...classNames,
|
|
716
|
+
start: isStart,
|
|
717
|
+
end: isEnd,
|
|
718
|
+
'within-selected-slot': withinSelectedSlot,
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
return cx('day-wrapper', classNames);
|
|
722
|
+
};
|
|
723
|
+
const isDateSelectable = (date) => {
|
|
724
|
+
// Check if the date is within the selectable interval
|
|
725
|
+
if (!isWithinInterval(date, selectableSlot))
|
|
726
|
+
return false;
|
|
727
|
+
// Check if the date is in the currently displayed month
|
|
728
|
+
if (date.getMonth() !== displayedMonth)
|
|
729
|
+
return false;
|
|
730
|
+
return true;
|
|
731
|
+
};
|
|
732
|
+
return {
|
|
733
|
+
days: allDays,
|
|
734
|
+
isReferenceDate: (date) => normalizeDate(date).getTime() === normalizeDate(referenceDate).getTime(),
|
|
735
|
+
buildDayWrapperClassName,
|
|
736
|
+
isDateSelectable,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
const WEEKDAY_LABELS = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
|
741
|
+
const Day = ({ date, isReferenceDate, isSelectable, dayWrapperClassName, onClick }) => (React.createElement("div", { onClick: () => {
|
|
742
|
+
if (isSelectable)
|
|
743
|
+
onClick(date);
|
|
744
|
+
}, className: "day-background" },
|
|
745
|
+
React.createElement("div", { className: dayWrapperClassName },
|
|
746
|
+
React.createElement("span", { className: "day" }, date.getDate()),
|
|
747
|
+
isReferenceDate && React.createElement("span", { className: "current-date-highlight" }))));
|
|
748
|
+
const Calendar = (props) => {
|
|
749
|
+
const { days, isReferenceDate, isDateSelectable, buildDayWrapperClassName } = useCalendar(props);
|
|
750
|
+
const { displayedMonthStartDate, onDayClick } = props;
|
|
751
|
+
return (React.createElement("div", { className: "calendar-wrapper" },
|
|
752
|
+
React.createElement("div", { className: "calendar-anatomy" },
|
|
753
|
+
React.createElement("p", { className: "calendar-month-label" }, displayedMonthStartDate.toLocaleString('en-GB', { month: 'short' })),
|
|
754
|
+
React.createElement("div", { className: "calendar-grid-wrapper" },
|
|
755
|
+
React.createElement("div", { className: "calendar-weekday-labels" }, WEEKDAY_LABELS.map((label, index) => (React.createElement("p", { key: `${label}-${index}` }, label)))),
|
|
756
|
+
React.createElement("div", { className: "calendar-days-grid" }, days.map((date) => (React.createElement(Day, { key: date.getTime(), date: date, isReferenceDate: isReferenceDate(date), isSelectable: isDateSelectable(date), dayWrapperClassName: buildDayWrapperClassName(date), onClick: onDayClick }))))))));
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
function useCalendarPicker({ initialDate, selectedSlot, selectableSlot, numberOfMonths = 1, }) {
|
|
760
|
+
validateSlots(selectedSlot, selectableSlot, initialDate);
|
|
761
|
+
const [activeDate, setActiveDate] = useState(new Date());
|
|
762
|
+
const displayedMonthsStartDates = generateSequentialDates(activeDate, numberOfMonths);
|
|
763
|
+
const activeYear = activeDate.getFullYear();
|
|
764
|
+
const activeMonth = activeDate.getMonth();
|
|
765
|
+
const firstDayOfMonth = new Date(activeYear, activeMonth, 1);
|
|
766
|
+
const lastDayOfMonth = new Date(activeYear, activeMonth + 1, 0);
|
|
767
|
+
const canGoToPreviousMonth = selectableSlot === undefined || selectableSlot.start === null
|
|
768
|
+
? true
|
|
769
|
+
: selectableSlot.start < firstDayOfMonth;
|
|
770
|
+
const canGoToNextMonth = selectableSlot === undefined || selectableSlot.end === null
|
|
771
|
+
? true
|
|
772
|
+
: selectableSlot.end > lastDayOfMonth;
|
|
773
|
+
const showNavigationBtn = canGoToPreviousMonth || canGoToNextMonth;
|
|
774
|
+
const handleGoToPreviousMonth = () => {
|
|
775
|
+
if (canGoToPreviousMonth) {
|
|
776
|
+
const previousActiveMonth = activeMonth === 0 ? 11 : activeMonth - 1;
|
|
777
|
+
const previousActiveYear = activeMonth === 0 ? activeYear - 1 : activeYear;
|
|
778
|
+
setActiveDate(new Date(previousActiveYear, previousActiveMonth, 1));
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
const handleGoToNextMonth = () => {
|
|
782
|
+
if (canGoToNextMonth) {
|
|
783
|
+
const nextActiveMonth = activeMonth === 11 ? 0 : activeMonth + 1;
|
|
784
|
+
const nextActiveYear = activeMonth === 11 ? activeYear + 1 : activeYear;
|
|
785
|
+
setActiveDate(new Date(nextActiveYear, nextActiveMonth, 1));
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
useEffect(() => {
|
|
789
|
+
setActiveDate(initialDate ?? selectedSlot?.start ?? selectableSlot?.start ?? new Date());
|
|
790
|
+
}, [initialDate, selectedSlot, selectableSlot]);
|
|
791
|
+
return {
|
|
792
|
+
displayedMonthsStartDates,
|
|
793
|
+
showNavigationBtn,
|
|
794
|
+
canGoToPreviousMonth,
|
|
795
|
+
canGoToNextMonth,
|
|
796
|
+
handleGoToPreviousMonth,
|
|
797
|
+
handleGoToNextMonth,
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
const CalendarPicker = ({ initialDate, selectedSlot, selectableSlot, numberOfMonths = 1, onDayClick, modalPosition, calendarPickerRef, }) => {
|
|
802
|
+
const { displayedMonthsStartDates, showNavigationBtn, canGoToNextMonth, canGoToPreviousMonth, handleGoToNextMonth, handleGoToPreviousMonth, } = useCalendarPicker({
|
|
803
|
+
initialDate,
|
|
804
|
+
selectedSlot,
|
|
805
|
+
selectableSlot,
|
|
806
|
+
numberOfMonths,
|
|
807
|
+
});
|
|
808
|
+
return (React.createElement("div", { ref: calendarPickerRef, className: "calendar-picker", style: modalPosition },
|
|
809
|
+
showNavigationBtn && (React.createElement("span", { className: cx('calendar-navigation-btn', 'previous', {
|
|
810
|
+
disabled: !canGoToPreviousMonth,
|
|
811
|
+
}), onClick: handleGoToPreviousMonth },
|
|
812
|
+
React.createElement(ChevronLeft, { size: "lg" }))),
|
|
813
|
+
React.createElement("div", { className: cx('calendar-list', { 'navigation-btn-hidden': !showNavigationBtn }) }, displayedMonthsStartDates.map((date) => (React.createElement(Calendar, { key: date.getTime(), displayedMonthStartDate: date, selectableSlot: selectableSlot, selectedSlot: selectedSlot, onDayClick: onDayClick })))),
|
|
814
|
+
showNavigationBtn && (React.createElement("span", { className: cx('calendar-navigation-btn', 'next', {
|
|
815
|
+
disabled: !canGoToNextMonth,
|
|
816
|
+
}), onClick: handleGoToNextMonth },
|
|
817
|
+
React.createElement(ChevronRight, { size: "lg" })))));
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
const useModalPosition = (inputRef, modalRef, offset = 3 // Default offset below the input
|
|
821
|
+
) => {
|
|
822
|
+
const [modalPosition, setModalPosition] = useState({
|
|
823
|
+
top: 0,
|
|
824
|
+
left: 0,
|
|
825
|
+
});
|
|
826
|
+
const calculatePosition = useCallback(() => {
|
|
827
|
+
if (inputRef.current && modalRef.current) {
|
|
828
|
+
const inputRect = inputRef.current.getBoundingClientRect();
|
|
829
|
+
const modal = modalRef.current;
|
|
830
|
+
const modalRect = modal.getBoundingClientRect();
|
|
831
|
+
const offsetParent = modal.offsetParent;
|
|
832
|
+
const parentRect = offsetParent ? offsetParent.getBoundingClientRect() : { top: 0, left: 0 };
|
|
833
|
+
// Adjust the top position: place it below the input while considering an offset
|
|
834
|
+
const top = inputRect.bottom - parentRect.top - offset;
|
|
835
|
+
// Center the modal horizontally relative to the input
|
|
836
|
+
let left = inputRect.left - parentRect.left + (inputRect.width - modalRect.width) / 2;
|
|
837
|
+
// Prevent going out of bounds on the left
|
|
838
|
+
if (left < 10) {
|
|
839
|
+
left = 10;
|
|
840
|
+
}
|
|
841
|
+
setModalPosition({ top, left });
|
|
842
|
+
}
|
|
843
|
+
}, [inputRef, modalRef, offset]);
|
|
844
|
+
useEffect(() => {
|
|
845
|
+
calculatePosition();
|
|
846
|
+
const handleResize = () => calculatePosition();
|
|
847
|
+
window.addEventListener('resize', handleResize);
|
|
848
|
+
return () => window.removeEventListener('resize', handleResize);
|
|
849
|
+
}, [calculatePosition]);
|
|
850
|
+
return { modalPosition, calculatePosition };
|
|
851
|
+
};
|
|
852
|
+
|
|
853
|
+
const MODAL_VERTICAL_OFFSET = 3;
|
|
854
|
+
// Regex for "xx/xx/xx"
|
|
855
|
+
const SINGLE_DATE_REGEX = /^\d{2}\/\d{2}\/\d{2}$/;
|
|
856
|
+
function useDatePicker(datePickerProps) {
|
|
857
|
+
const { value, isRangeMode, selectableSlot, errorMessages, onDateChange } = datePickerProps;
|
|
858
|
+
const [showPicker, setShowPicker] = useState(false);
|
|
859
|
+
const [inputValue, setInputValue] = useState(formatInputValue(datePickerProps));
|
|
860
|
+
const [selectedSlot, setSelectedSlot] = useState(formatValueToSlot(datePickerProps));
|
|
861
|
+
const [statusWithMessage, setStatusWithMessage] = useState();
|
|
862
|
+
const calendarPickerRef = useRef(null);
|
|
863
|
+
const inputRef = useRef(null);
|
|
864
|
+
useOutsideClick(calendarPickerRef, (e) => {
|
|
865
|
+
// Do not close the picker if any children in input wrapper is clicked.
|
|
866
|
+
// This wrapper include, the input itself, the trailing content (which contains the calendar icon) and the leading content
|
|
867
|
+
if (inputRef.current &&
|
|
868
|
+
inputRef.current.parentElement?.parentElement?.contains(e.target))
|
|
869
|
+
return;
|
|
870
|
+
setShowPicker(false);
|
|
871
|
+
});
|
|
872
|
+
const { calculatePosition, modalPosition } = useModalPosition(inputRef, calendarPickerRef, MODAL_VERTICAL_OFFSET);
|
|
873
|
+
const handleInputClick = () => {
|
|
874
|
+
if (isRangeMode) {
|
|
875
|
+
setShowPicker(true);
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
const handleDayClick = (clickedDate) => {
|
|
879
|
+
if (isRangeMode) {
|
|
880
|
+
const newSelectedSlot = computeNewSelectedSlot(clickedDate, value);
|
|
881
|
+
onDateChange(clickedDate, newSelectedSlot);
|
|
882
|
+
}
|
|
883
|
+
else {
|
|
884
|
+
onDateChange(clickedDate);
|
|
885
|
+
}
|
|
886
|
+
};
|
|
887
|
+
const handleInputOnChange = (newValue) => {
|
|
888
|
+
if (isRangeMode) {
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
setInputValue(newValue);
|
|
892
|
+
const inputIsDate = SINGLE_DATE_REGEX.test(newValue);
|
|
893
|
+
if (inputIsDate) {
|
|
894
|
+
const [day, month, year] = newValue.split('/').map(Number);
|
|
895
|
+
const date = new Date(year + 2000, month - 1, day);
|
|
896
|
+
if (!isNaN(date.getTime()) && isWithinInterval(date, selectableSlot) && onDateChange) {
|
|
897
|
+
onDateChange(date);
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
setStatusWithMessage({ status: 'error', message: errorMessages?.invalidDate });
|
|
901
|
+
}
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
if (containsOnlyNumbersAndSlashes(newValue) && newValue.length < 8) {
|
|
905
|
+
setStatusWithMessage(undefined);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
setStatusWithMessage({
|
|
909
|
+
status: 'error',
|
|
910
|
+
message: errorMessages?.invalidInput,
|
|
911
|
+
});
|
|
912
|
+
};
|
|
913
|
+
useEffect(() => {
|
|
914
|
+
if (showPicker)
|
|
915
|
+
calculatePosition();
|
|
916
|
+
}, [showPicker, calculatePosition]);
|
|
917
|
+
useEffect(() => {
|
|
918
|
+
const newInput = formatInputValue(datePickerProps);
|
|
919
|
+
if (newInput !== inputValue) {
|
|
920
|
+
// we only set the input value if it has changed
|
|
921
|
+
// otherwise the user loses the focus
|
|
922
|
+
setInputValue(newInput);
|
|
923
|
+
}
|
|
924
|
+
setStatusWithMessage(undefined);
|
|
925
|
+
setSelectedSlot(formatValueToSlot(datePickerProps));
|
|
926
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
927
|
+
}, [value]);
|
|
928
|
+
return {
|
|
929
|
+
showPicker,
|
|
930
|
+
inputValue,
|
|
931
|
+
statusWithMessage,
|
|
932
|
+
selectedSlot,
|
|
933
|
+
modalPosition,
|
|
934
|
+
inputRef,
|
|
935
|
+
calendarPickerRef,
|
|
936
|
+
setShowPicker,
|
|
937
|
+
handleDayClick,
|
|
938
|
+
handleInputClick,
|
|
939
|
+
handleInputOnChange,
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
const InputModal = ({ inputRef, isOpen, onClose, children }) => {
|
|
944
|
+
const modalRef = useRef(null);
|
|
945
|
+
const { modalPosition, calculatePosition } = useModalPosition(inputRef, modalRef);
|
|
946
|
+
useEffect(() => {
|
|
947
|
+
if (isOpen) {
|
|
948
|
+
calculatePosition();
|
|
949
|
+
}
|
|
950
|
+
}, [calculatePosition, isOpen]);
|
|
951
|
+
useOutsideClick(modalRef, onClose);
|
|
952
|
+
if (!isOpen)
|
|
953
|
+
return null;
|
|
954
|
+
return (React.createElement("div", { className: "modal-ui-overlay" },
|
|
955
|
+
React.createElement("div", { ref: modalRef, className: "modal-ui-content", style: { top: modalPosition.top, left: modalPosition.left } },
|
|
956
|
+
React.createElement("button", { className: "close-button", onClick: onClose },
|
|
957
|
+
React.createElement(X, { size: "lg" })),
|
|
958
|
+
children)));
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
const DatePicker = (props) => {
|
|
962
|
+
const { inputValue, statusWithMessage, selectedSlot, showPicker, modalPosition, inputRef, calendarPickerRef, setShowPicker, handleDayClick, handleInputClick, handleInputOnChange, } = useDatePicker(props);
|
|
963
|
+
const { inputFieldWrapperClassname, ...otherInputProps } = props.inputProps;
|
|
964
|
+
const { selectableSlot } = props;
|
|
965
|
+
return (React.createElement("div", { className: "date-picker" },
|
|
966
|
+
React.createElement("div", null,
|
|
967
|
+
React.createElement(Input, { ...otherInputProps, ref: inputRef, value: inputValue, onClick: handleInputClick, type: "text", trailingContent: {
|
|
968
|
+
content: React.createElement(Calendar$1, null),
|
|
969
|
+
onClickCallback: () => setShowPicker(!showPicker),
|
|
970
|
+
}, inputFieldWrapperClassname: cx('date-picker-input', inputFieldWrapperClassname, {
|
|
971
|
+
'range-mode': props.isRangeMode,
|
|
972
|
+
}), autoComplete: "off", onChange: (e) => handleInputOnChange(e.target.value), statusWithMessage: statusWithMessage })),
|
|
973
|
+
React.createElement(InputModal, { inputRef: inputRef, isOpen: showPicker, onClose: () => setShowPicker(false) },
|
|
974
|
+
React.createElement("div", { className: "calendar-picker-wrapper" },
|
|
975
|
+
React.createElement(CalendarPicker, { ...props.calendarPickerProps, selectedSlot: selectedSlot, onDayClick: handleDayClick, modalPosition: modalPosition, calendarPickerRef: calendarPickerRef, selectableSlot: selectableSlot })))));
|
|
976
|
+
};
|
|
977
|
+
|
|
978
|
+
const PasswordInput = React.forwardRef(({ inputFieldWrapperClassname, ...otherProps }, ref) => {
|
|
979
|
+
const [showPassword, toggleShowPassword] = useState(false);
|
|
980
|
+
return (React.createElement(Input, { ...otherProps, type: showPassword ? 'text' : 'password', trailingContent: {
|
|
981
|
+
content: showPassword ? React.createElement(EyeClosed, null) : React.createElement(Eye, null),
|
|
982
|
+
onClickCallback: () => toggleShowPassword(!showPassword),
|
|
983
|
+
}, inputFieldWrapperClassname: cx('password-input', inputFieldWrapperClassname), ref: ref }));
|
|
984
|
+
});
|
|
985
|
+
PasswordInput.displayName = 'PasswordInput';
|
|
986
|
+
|
|
987
|
+
const RadioButton = ({ id, label, value, hint, readOnly, onBlur, onKeyUp, small, ...rest }) => {
|
|
988
|
+
const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
|
|
989
|
+
return (React.createElement("div", { className: cx('radio-button', { 'read-only': readOnly, small }), tabIndex: 0 },
|
|
990
|
+
React.createElement("div", { className: "radio-container" },
|
|
991
|
+
React.createElement("input", { className: "radio-input", id: id || value, type: "radio", value: value, tabIndex: -1, onBlur: handleBlur, onKeyUp: handleKeyUp, ...rest }),
|
|
992
|
+
React.createElement("span", { className: cx('checkmark', { focused: isFocusByTab }) }),
|
|
993
|
+
React.createElement("label", { htmlFor: id || value, className: "radio-label" }, label)),
|
|
994
|
+
hint && React.createElement("div", { className: "hint" }, hint)));
|
|
995
|
+
};
|
|
996
|
+
|
|
997
|
+
const RadioGroup = ({ label, value, subtitle, readOnly, disabled, options, statusWithMessage, required, small, }) => {
|
|
998
|
+
const [selectedValue, setSelectedValue] = useState(value);
|
|
999
|
+
const handleOptionChange = (e, nextOption) => {
|
|
1000
|
+
if (!readOnly) {
|
|
1001
|
+
setSelectedValue(nextOption.value);
|
|
1002
|
+
nextOption.onChange?.(e);
|
|
1003
|
+
}
|
|
1004
|
+
};
|
|
1005
|
+
const statusClassname = statusWithMessage?.status ? { [statusWithMessage.status]: true } : {};
|
|
1006
|
+
return (React.createElement("div", { className: cx('radio-button-wrapper', statusClassname) },
|
|
1007
|
+
label && (React.createElement("label", { className: "label" },
|
|
1008
|
+
required && (React.createElement("span", { className: "required" },
|
|
1009
|
+
React.createElement(RequiredInput, null))),
|
|
1010
|
+
label,
|
|
1011
|
+
" ",
|
|
1012
|
+
subtitle && React.createElement("span", { className: "subtitle" }, subtitle))),
|
|
1013
|
+
options.map((option) => (React.createElement(RadioButton, { key: option.value, ...option, readOnly: readOnly, disabled: disabled, checked: selectedValue === option.value, onChange: (e) => {
|
|
1014
|
+
handleOptionChange(e, option);
|
|
1015
|
+
}, small: small }))),
|
|
1016
|
+
statusWithMessage?.message && (React.createElement("div", { className: "status-with-message" },
|
|
1017
|
+
React.createElement(InputStatusIcon, { status: statusWithMessage.status }),
|
|
1018
|
+
React.createElement("span", { className: cx('status-message', statusClassname) }, statusWithMessage.message)))));
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
const PLACEHOLDER_VALUE = '__PLACEHOLDER__';
|
|
1022
|
+
const Select = ({ id, label, hint, value, options, placeholder, statusWithMessage, required, disabled, narrow, readOnly, small, getOptionLabel, getOptionValue, onChange, ...props }) => {
|
|
1023
|
+
const [selectedOption, setSelectedOption] = useState(value);
|
|
1024
|
+
const handleOnChange = (e) => {
|
|
1025
|
+
const newSelectedOption = e.target.value === PLACEHOLDER_VALUE
|
|
1026
|
+
? undefined
|
|
1027
|
+
: options.find((option) => getOptionValue(option) === e.target.value);
|
|
1028
|
+
setSelectedOption(newSelectedOption);
|
|
1029
|
+
onChange(newSelectedOption);
|
|
1030
|
+
};
|
|
1031
|
+
useEffect(() => {
|
|
1032
|
+
setSelectedOption(value);
|
|
1033
|
+
}, [value]);
|
|
1034
|
+
return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, required: required, disabled: disabled, small: small, narrow: narrow },
|
|
1035
|
+
React.createElement("select", { id: id, className: cx('osrd-ui-custom-select', statusWithMessage?.status, {
|
|
1036
|
+
'placeholder-selected': placeholder && !selectedOption,
|
|
1037
|
+
small,
|
|
1038
|
+
'read-only': readOnly,
|
|
1039
|
+
}), value: selectedOption ? getOptionValue(selectedOption) : undefined, required: required, disabled: disabled || readOnly, onChange: handleOnChange, ...props },
|
|
1040
|
+
placeholder && React.createElement("option", { value: PLACEHOLDER_VALUE }, `– ${placeholder} –`),
|
|
1041
|
+
options.map((option) => (React.createElement("option", { key: getOptionValue(option), value: getOptionValue(option) }, getOptionLabel(option)))))));
|
|
1042
|
+
};
|
|
1043
|
+
|
|
1044
|
+
const CHAR_COUNT_ERROR_THRESHOLD = 40;
|
|
1045
|
+
const TextArea = ({ id, label, value: initialValue, hint, required, disabled, statusWithMessage, maxLength, onChange, onKeyUp, onBlur, ...rest }) => {
|
|
1046
|
+
const [value, setValue] = useState(initialValue);
|
|
1047
|
+
const charCount = value?.length || 0;
|
|
1048
|
+
const { handleKeyUp, handleBlur, isFocusByTab } = useFocusByTab({ onBlur, onKeyUp });
|
|
1049
|
+
const handleChange = (e) => {
|
|
1050
|
+
setValue(e.target.value);
|
|
1051
|
+
onChange?.(e);
|
|
1052
|
+
};
|
|
1053
|
+
return (React.createElement(FieldWrapper, { id: id, label: label, hint: hint, statusWithMessage: statusWithMessage, disabled: disabled, required: required, className: "text-area-field-wrapper" },
|
|
1054
|
+
React.createElement("div", { className: cx('text-area-wrapper', { 'focused-by-tab': isFocusByTab }) },
|
|
1055
|
+
maxLength && (React.createElement("div", { className: cx('char-count', {
|
|
1056
|
+
error: charCount === maxLength,
|
|
1057
|
+
warning: maxLength - charCount <= CHAR_COUNT_ERROR_THRESHOLD,
|
|
1058
|
+
}) },
|
|
1059
|
+
charCount,
|
|
1060
|
+
"/",
|
|
1061
|
+
maxLength)),
|
|
1062
|
+
React.createElement("textarea", { className: cx('text-area', { [statusWithMessage?.status || '']: !!statusWithMessage }), id: id, value: value, disabled: disabled, maxLength: maxLength, onChange: handleChange, onBlur: handleBlur, onKeyUp: handleKeyUp, ...rest }))));
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
const TimeRange = ({ range, selectedItem, className, onSelectItem }) => (React.createElement("div", { className: "time-grid" }, range.map((item) => (React.createElement("div", { key: item, className: cx(className, { selected: selectedItem === item }), onClick: () => onSelectItem(item) }, item.toString().padStart(2, '0'))))));
|
|
1066
|
+
function formatTimeValue(value, max) {
|
|
1067
|
+
return Math.max(0, Math.min(max, value)).toString().padStart(2, '0');
|
|
1068
|
+
}
|
|
1069
|
+
const TimePicker = ({ onTimeChange, hours = 0, minutes = 0, seconds = 0, displaySeconds = false, ...otherProps }) => {
|
|
1070
|
+
const [isModalOpen, setIsModalOpen] = useState(false);
|
|
1071
|
+
const inputRef = useRef(null);
|
|
1072
|
+
const incrementMinute = useCallback((increment) => {
|
|
1073
|
+
let newMinutes = minutes + increment;
|
|
1074
|
+
let newHours = hours;
|
|
1075
|
+
if (newMinutes >= 60) {
|
|
1076
|
+
newMinutes = 0;
|
|
1077
|
+
newHours = (newHours + 1) % 24;
|
|
1078
|
+
}
|
|
1079
|
+
else if (newMinutes < 0) {
|
|
1080
|
+
newMinutes = 59;
|
|
1081
|
+
newHours = (newHours + 23) % 24; // minus 1 hour
|
|
1082
|
+
}
|
|
1083
|
+
onTimeChange({ hours: newHours, minutes: newMinutes, seconds });
|
|
1084
|
+
}, [hours, minutes, seconds, onTimeChange]);
|
|
1085
|
+
const incrementSeconds = useCallback((increment) => {
|
|
1086
|
+
let newSeconds = seconds + increment;
|
|
1087
|
+
let newMinutes = minutes;
|
|
1088
|
+
let newHours = hours;
|
|
1089
|
+
if (newSeconds >= 60) {
|
|
1090
|
+
newSeconds = 0;
|
|
1091
|
+
newMinutes += 1;
|
|
1092
|
+
if (newMinutes >= 60) {
|
|
1093
|
+
newMinutes = 0;
|
|
1094
|
+
newHours = (newHours + 1) % 24;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
else if (newSeconds < 0) {
|
|
1098
|
+
newSeconds = 59;
|
|
1099
|
+
newMinutes -= 1;
|
|
1100
|
+
if (newMinutes < 0) {
|
|
1101
|
+
newMinutes = 59;
|
|
1102
|
+
newHours = (newHours + 23) % 24; // minus 1 hour
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
onTimeChange({ hours: newHours, minutes: newMinutes, seconds: newSeconds });
|
|
1106
|
+
}, [hours, minutes, seconds, onTimeChange]);
|
|
1107
|
+
const handleChange = useCallback((event) => {
|
|
1108
|
+
const value = event.target.value;
|
|
1109
|
+
if (!displaySeconds) {
|
|
1110
|
+
const [h, m] = value.split(':');
|
|
1111
|
+
if (h !== undefined && m !== undefined) {
|
|
1112
|
+
onTimeChange({ hours: parseInt(h), minutes: parseInt(m) });
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
else {
|
|
1116
|
+
const [h, m, s] = value.split(':');
|
|
1117
|
+
if (h !== undefined && m !== undefined && s !== undefined) {
|
|
1118
|
+
onTimeChange({ hours: parseInt(h), minutes: parseInt(m), seconds: parseInt(s) });
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}, [displaySeconds, onTimeChange]);
|
|
1122
|
+
const displayedSecondsPart = displaySeconds ? `:${formatTimeValue(seconds, 59)}` : '';
|
|
1123
|
+
const selectedTime = `${formatTimeValue(hours, 23)}:${formatTimeValue(minutes, 59)}${displayedSecondsPart}`;
|
|
1124
|
+
const hoursRange = [...Array(24).keys()];
|
|
1125
|
+
const minutesAndSecondsRange = [...Array(12).keys()].map((i) => i * 5);
|
|
1126
|
+
const openModal = useCallback(() => setIsModalOpen(true), []);
|
|
1127
|
+
const closeModal = useCallback(() => setIsModalOpen(false), []);
|
|
1128
|
+
return (React.createElement("div", { className: "time-picker" },
|
|
1129
|
+
React.createElement(Input, { ...otherProps, className: cx('input', 'time-input', otherProps.className), type: "time", name: "time", value: selectedTime, onClick: openModal, onChange: handleChange, ref: inputRef, step: displaySeconds ? 1 : 60 }),
|
|
1130
|
+
React.createElement(InputModal, { inputRef: inputRef, isOpen: isModalOpen, onClose: closeModal },
|
|
1131
|
+
React.createElement("div", { className: "time-picker-container" },
|
|
1132
|
+
React.createElement(TimeRange, { range: hoursRange, selectedItem: hours, className: "hour", onSelectItem: (h) => onTimeChange({ hours: h, minutes, seconds }) }),
|
|
1133
|
+
React.createElement("div", { className: "time-separator" }, ":"),
|
|
1134
|
+
React.createElement("div", { className: "minute-container" },
|
|
1135
|
+
React.createElement(TimeRange, { range: minutesAndSecondsRange, selectedItem: minutes, className: "minute", onSelectItem: (m) => onTimeChange({ hours, minutes: m, seconds }) }),
|
|
1136
|
+
React.createElement("div", { className: "minute-buttons" },
|
|
1137
|
+
React.createElement("button", { onClick: () => incrementMinute(-1), className: "minute-button" }, "-1mn"),
|
|
1138
|
+
React.createElement("button", { onClick: () => incrementMinute(1), className: "minute-button" }, "+1mn"))),
|
|
1139
|
+
displaySeconds && (React.createElement(React.Fragment, null,
|
|
1140
|
+
React.createElement("div", { className: "time-separator" }, ":"),
|
|
1141
|
+
React.createElement("div", { className: "second-container" },
|
|
1142
|
+
React.createElement(TimeRange, { range: minutesAndSecondsRange, selectedItem: seconds, className: "second", onSelectItem: (s) => onTimeChange({ hours, minutes, seconds: s }) }),
|
|
1143
|
+
React.createElement("div", { className: "second-buttons" },
|
|
1144
|
+
React.createElement("button", { onClick: () => incrementSeconds(-1), className: "second-button" }, "-1s"),
|
|
1145
|
+
React.createElement("button", { onClick: () => incrementSeconds(1), className: "second-button" }, "+1s")))))))));
|
|
1146
|
+
};
|
|
1147
|
+
|
|
1148
|
+
// onChange returns an event or number
|
|
1149
|
+
const Slider = ({ id, value: initialValue, min = 0, max = 100, step = 1, width = 112, onChange, onChangeCommitted, disabled, className, containerClassName, ...rest }) => {
|
|
1150
|
+
const [value, setValue] = useState(initialValue !== undefined ? Number(initialValue) : Number(min));
|
|
1151
|
+
useEffect(() => {
|
|
1152
|
+
setValue(Number(initialValue));
|
|
1153
|
+
}, [initialValue]);
|
|
1154
|
+
const handleChange = (e) => {
|
|
1155
|
+
const newValue = Number(e.target.value);
|
|
1156
|
+
setValue(newValue);
|
|
1157
|
+
onChange?.(e);
|
|
1158
|
+
};
|
|
1159
|
+
const handleCommit = (e) => {
|
|
1160
|
+
if (onChangeCommitted) {
|
|
1161
|
+
onChangeCommitted(e);
|
|
1162
|
+
}
|
|
1163
|
+
};
|
|
1164
|
+
// margin to keep the colored track aligned with the thumb
|
|
1165
|
+
const visualMargin = 5;
|
|
1166
|
+
const visualMin = Number(min) - visualMargin;
|
|
1167
|
+
const visualMax = Number(max) + visualMargin;
|
|
1168
|
+
const visualProgress = ((value - visualMin) / (visualMax - visualMin)) * 100;
|
|
1169
|
+
return (React.createElement("div", { className: cx('range-wrapper', containerClassName, { disabled }), style: { width: `${width}px` } },
|
|
1170
|
+
React.createElement("input", { type: "range", className: cx('range-slider', className), id: id, value: value, min: min, max: max, step: step, onChange: handleChange, onMouseUp: handleCommit, onKeyUp: handleCommit, disabled: disabled, style: {
|
|
1171
|
+
'--slider-progress': `${visualProgress}%`,
|
|
1172
|
+
}, ...rest })));
|
|
1173
|
+
};
|
|
1174
|
+
|
|
1175
|
+
const TOLERANCE_RANGES = [
|
|
1176
|
+
{ label: '00', value: 0 },
|
|
1177
|
+
{ label: '05', value: 300 },
|
|
1178
|
+
{ label: '10', value: 600 },
|
|
1179
|
+
{ label: '15', value: 900 },
|
|
1180
|
+
{ label: '20', value: 1200 },
|
|
1181
|
+
{ label: '25', value: 1500 },
|
|
1182
|
+
{ label: '30', value: 1800 },
|
|
1183
|
+
{ label: '35', value: 2100 },
|
|
1184
|
+
{ label: '40', value: 2400 },
|
|
1185
|
+
{ label: '45', value: 2700 },
|
|
1186
|
+
{ label: '60', value: 3600 },
|
|
1187
|
+
{ label: '75', value: 4500 },
|
|
1188
|
+
{ label: '90', value: 5400 },
|
|
1189
|
+
{ label: '105', value: 6300 },
|
|
1190
|
+
{ label: '120', value: 7200 },
|
|
1191
|
+
{ label: '150', value: 9000 },
|
|
1192
|
+
{ label: '180', value: 10800 },
|
|
1193
|
+
{ label: '210', value: 12600 },
|
|
1194
|
+
{ label: '240', value: 14400 },
|
|
1195
|
+
];
|
|
1196
|
+
|
|
1197
|
+
const ToleranceRangeGrid = ({ onSelection, selectedTolerance, toleranceSign, }) => (React.createElement("div", { className: "tolerance-picker-section" },
|
|
1198
|
+
React.createElement("div", { className: `tolerance-grid ${toleranceSign}-tolerance` }, TOLERANCE_RANGES.map(({ label, value }, index) => (React.createElement("button", { key: `${label}-${index}`, className: cx('minute', { selected: selectedTolerance === value }), style: { gridArea: `a${index + 1}` }, onClick: () => onSelection(value) }, `${toleranceSign === 'minus' ? '-' : '+'}${label}`))))));
|
|
1199
|
+
|
|
1200
|
+
/* eslint-disable react-hooks/exhaustive-deps */
|
|
1201
|
+
const TolerancePicker = ({ onToleranceChange, toleranceValues: { minusTolerance, plusTolerance } = {
|
|
1202
|
+
minusTolerance: TOLERANCE_RANGES[0].value,
|
|
1203
|
+
plusTolerance: TOLERANCE_RANGES[0].value,
|
|
1204
|
+
}, translateWarningMessage, ...inputProps }) => {
|
|
1205
|
+
const formatToleranceValue = (minusIndex, plusIndex) => `-${TOLERANCE_RANGES[minusIndex]?.label || ''}/+${TOLERANCE_RANGES[plusIndex]?.label || ''}`;
|
|
1206
|
+
const [showPicker, setShowPicker] = useState(false);
|
|
1207
|
+
const [inputValue, setInputValue] = useState(formatToleranceValue(0, 0));
|
|
1208
|
+
const [warningStatus, setWarningStatus] = useState(undefined);
|
|
1209
|
+
const inputRef = useRef(null);
|
|
1210
|
+
useEffect(() => {
|
|
1211
|
+
const minusToleranceIndex = TOLERANCE_RANGES.findIndex((range) => range.value === minusTolerance);
|
|
1212
|
+
const plusToleranceIndex = TOLERANCE_RANGES.findIndex((range) => range.value === plusTolerance);
|
|
1213
|
+
if (minusToleranceIndex < 0 || plusToleranceIndex < 0) {
|
|
1214
|
+
const invalidTolerance = minusToleranceIndex < 0 ? minusTolerance : plusTolerance;
|
|
1215
|
+
setWarningStatus({
|
|
1216
|
+
status: 'warning',
|
|
1217
|
+
message: translateWarningMessage?.(invalidTolerance) ||
|
|
1218
|
+
`${invalidTolerance} is not a valid tolerance value.`,
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
else {
|
|
1222
|
+
setWarningStatus(undefined);
|
|
1223
|
+
}
|
|
1224
|
+
setInputValue(formatToleranceValue(minusToleranceIndex, plusToleranceIndex));
|
|
1225
|
+
}, [minusTolerance, plusTolerance]);
|
|
1226
|
+
return (React.createElement("div", { className: "tolerance-picker" },
|
|
1227
|
+
React.createElement("div", null,
|
|
1228
|
+
React.createElement(Input, { ...inputProps, value: inputValue, statusWithMessage: warningStatus, onClick: () => setShowPicker(!showPicker), type: "text", ref: inputRef })),
|
|
1229
|
+
React.createElement(InputModal, { inputRef: inputRef, isOpen: showPicker, onClose: () => setShowPicker(false) },
|
|
1230
|
+
React.createElement("div", { className: "time-tolerance" },
|
|
1231
|
+
React.createElement(ToleranceRangeGrid, { onSelection: (e) => onToleranceChange({ minusTolerance: e, plusTolerance }), selectedTolerance: minusTolerance, toleranceSign: "minus" }),
|
|
1232
|
+
React.createElement("div", { className: "divider" }),
|
|
1233
|
+
React.createElement(ToleranceRangeGrid, { onSelection: (e) => onToleranceChange({ minusTolerance, plusTolerance: e }), selectedTolerance: plusTolerance, toleranceSign: "plus" })))));
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
const TokenInput = ({ label, tokens: initialTokens }) => {
|
|
1237
|
+
const [tokens, setTokens] = useState(initialTokens);
|
|
1238
|
+
const [newToken, setNewToken] = useState('');
|
|
1239
|
+
const [selectedToken, setSelectedToken] = useState(null);
|
|
1240
|
+
const inputRef = useRef(null);
|
|
1241
|
+
const addToken = (e) => {
|
|
1242
|
+
if (e.key === 'Enter' && newToken.trim() !== '') {
|
|
1243
|
+
setTokens((oldTokens) => [...oldTokens, newToken]);
|
|
1244
|
+
setNewToken('');
|
|
1245
|
+
}
|
|
1246
|
+
};
|
|
1247
|
+
const focusInput = (e) => {
|
|
1248
|
+
if (e.target === e.currentTarget) {
|
|
1249
|
+
inputRef.current?.focus();
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
return (React.createElement("div", { className: "token-input-wrapper" },
|
|
1253
|
+
React.createElement("label", { className: "input-label" }, label),
|
|
1254
|
+
React.createElement("div", { className: "tokens-wrapper", onClick: focusInput },
|
|
1255
|
+
tokens.map((token, index) => (React.createElement("div", { key: `${token}-${index}`, onClick: () => setSelectedToken(index), className: cx('token-item-wrapper', { selected: selectedToken === index }) },
|
|
1256
|
+
React.createElement("span", { className: "token-label" }, token),
|
|
1257
|
+
React.createElement("span", { className: "token-close-btn", onClick: () => setTokens((oldTokens) => oldTokens.filter((_t, i) => i !== index)) },
|
|
1258
|
+
React.createElement(X, null))))),
|
|
1259
|
+
React.createElement("input", { type: "text", value: newToken, onChange: (e) => setNewToken(e.target.value), onKeyDown: addToken, className: "token-input", ref: inputRef }))));
|
|
1260
|
+
};
|
|
1261
|
+
|
|
1262
|
+
export { Button, Checkbox, CheckboxList, CheckboxesTree, ComboBox, DatePicker, Input, PasswordInput, RadioButton, RadioGroup, Select, Slider, TextArea, TimePicker, TokenInput, TolerancePicker, useDefaultComboBox };
|
|
2
1263
|
//# sourceMappingURL=index.esm.js.map
|