import _extends from"@babel/runtime/helpers/esm/extends";import _slicedToArray from"@babel/runtime/helpers/esm/slicedToArray";import _typeof from"@babel/runtime/helpers/esm/typeof";import*as React from"react";import{setRef,useEventCallback,useControlled,unstable_useId as useId}from"../utils";function stripDiacritics(e){return void 0!==e.normalize?e.normalize("NFD").replace(/[\u0300-\u036f]/g,""):e}function createFilterOptions(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=e.ignoreAccents,i=void 0===t||t,t=e.ignoreCase,a=void 0===t||t,u=e.limit,t=e.matchFrom,c=void 0===t?"any":t,l=e.stringify,e=e.trim,s=void 0!==e&&e;return function(e,t){var n=t.inputValue,o=t.getOptionLabel,r=s?n.trim():n;a&&(r=r.toLowerCase()),i&&(r=stripDiacritics(r));e=e.filter(function(e){e=(l||o)(e);return a&&(e=e.toLowerCase()),i&&(e=stripDiacritics(e)),"start"===c?0===e.indexOf(r):-1<e.indexOf(r)});return"number"==typeof u?e.slice(0,u):e}}function findIndex(e,t){for(var n=0;n<e.length;n+=1)if(t(e[n]))return n;return-1}var defaultFilterOptions=createFilterOptions(),pageSize=5;export default function useAutocomplete(e){var t=e.autoComplete,r=void 0!==t&&t,n=e.autoHighlight,o=void 0!==n&&n,i=e.autoSelect,a=void 0!==i&&i,u=e.blurOnSelect,c=void 0!==u&&u,l=e.disabled,s=e.clearOnBlur,d=void 0===s?!e.freeSolo:s,f=e.clearOnEscape,p=void 0!==f&&f,t=e.componentName,v=void 0===t?"useAutocomplete":t,n=e.defaultValue,i=void 0===n?e.multiple?[]:null:n,u=e.disableClearable,g=void 0!==u&&u,s=e.disableCloseOnSelect,h=void 0!==s&&s,f=e.disabledItemsFocusable,b=void 0!==f&&f,t=e.disableListWrap,m=void 0!==t&&t,n=e.filterOptions,u=void 0===n?defaultFilterOptions:n,s=e.filterSelectedOptions,x=void 0!==s&&s,f=e.freeSolo,y=void 0!==f&&f,O=e.getOptionDisabled,t=e.getOptionLabel,k=void 0===t?function(e){var t;return null!=(t=e.label)?t:e}:t,n=e.isOptionEqualToValue,E=void 0===n?function(e,t){return e===t}:n,C=e.groupBy,s=e.handleHomeEndKeys,R=void 0===s?!e.freeSolo:s,f=e.id,t=e.includeInputInList,S=void 0!==t&&t,n=e.inputValue,s=e.multiple,D=void 0!==s&&s,w=e.onChange,I=e.onClose,T=e.onHighlightChange,A=e.onInputChange,M=e.onOpen,t=e.open,s=e.openOnFocus,N=void 0!==s&&s,L=e.options,s=e.selectOnFocus,P=void 0===s?!e.freeSolo:s,s=e.value,V=useId(f),_=function(e){var t,n=k(e);return"string"==typeof n?n:("production"!==process.env.NODE_ENV&&(t=void 0===n?"undefined":"".concat(_typeof(n)," (").concat(n,")"),console.error("Material-UI: The `getOptionLabel` method of ".concat(v," returned ").concat(t," instead of a string for ").concat(JSON.stringify(e),"."))),String(n))},F=React.useRef(!1),H=React.useRef(!0),q=React.useRef(null),U=React.useRef(null),e=React.useState(null),z=e[0],f=e[1],e=React.useState(-1),B=e[0],K=e[1],j=o?0:-1,J=React.useRef(j),i=useControlled({controlled:s,default:i,name:v}),i=_slicedToArray(i,2),Y=i[0],W=i[1],n=useControlled({controlled:n,default:"",name:v,state:"inputValue"}),n=_slicedToArray(n,2),G=n[0],Q=n[1],n=React.useState(!1),X=n[0],Z=n[1],$=React.useCallback(function(e,t){var n;n=!D&&null!=t&&"string"==typeof(n=_(t))?n:"",G!==n&&(Q(n),A&&A(e,n,"reset"))},[_,G,D,A,Q]),ee=React.useRef();React.useEffect(function(){var e=Y!==ee.current;ee.current=Y,X&&!e||$(null,Y)},[Y,$,X,ee]);var n=useControlled({controlled:t,default:!1,name:v,state:"open"}),t=_slicedToArray(n,2),te=t[0],ne=t[1],n=React.useState(!0),t=n[0],oe=n[1],re=!D&&null!=Y&&G===_(Y),ie=te,ae=ie?u(L.filter(function(t){return!x||!(D?Y:[Y]).some(function(e){return null!==e&&E(t,e)})}),{inputValue:re&&t?"":G,getOptionLabel:_}):[],ue=te&&0<ae.length;"production"!==process.env.NODE_ENV&&null!==Y&&!y&&0<L.length&&(0<(Me=(D?Y:[Y]).filter(function(t){return!L.some(function(e){return E(e,t)})})).length&&console.warn(["Material-UI: The value provided to ".concat(v," is invalid."),"None of the options match with `".concat(1<Me.length?JSON.stringify(Me):JSON.stringify(Me[0]),"`."),"You can use the `isOptionEqualToValue` prop to customize the equality test."].join("\n")));var ce=useEventCallback(function(e){(-1===e?q.current:z.querySelector('[data-tag-index="'.concat(e,'"]'))).focus()});React.useEffect(function(){D&&B>Y.length-1&&(K(-1),ce(-1))},[Y,D,B,ce]);var le=useEventCallback(function(e){var t=e.event,n=e.index,e=e.reason,e=void 0===e?"auto":e;-1===(J.current=n)?q.current.removeAttribute("aria-activedescendant"):q.current.setAttribute("aria-activedescendant","".concat(V,"-option-").concat(n)),T&&T(t,-1===n?null:ae[n],e),U.current&&((t=U.current.querySelector('[role="option"].Mui-focused'))&&(t.classList.remove("Mui-focused"),t.classList.remove("Mui-focusVisible")),(t=U.current.parentElement.querySelector('[role="listbox"]'))&&(-1!==n?(n=U.current.querySelector('[data-option-index="'.concat(n,'"]')))&&(n.classList.add("Mui-focused"),"keyboard"===e&&n.classList.add("Mui-focusVisible"),t.scrollHeight>t.clientHeight&&"mouse"!==e&&(t.clientHeight+t.scrollTop<(n=(e=n).offsetTop+e.offsetHeight)?t.scrollTop=n-t.clientHeight:e.offsetTop-e.offsetHeight*(C?1.3:0)<t.scrollTop&&(t.scrollTop=e.offsetTop-e.offsetHeight*(C?1.3:0)))):t.scrollTop=0))}),se=useEventCallback(function(e){var t=e.event,n=e.diff,o=e.direction,o=void 0===o?"next":o,e=e.reason,e=void 0===e?"auto":e;ie&&(o=function(e,t){if(!U.current||-1===e)return-1;for(var n=e;;){if("next"===t&&n===ae.length||"previous"===t&&-1===n)return-1;var o=U.current.querySelector('[data-option-index="'.concat(n,'"]')),r=!b&&(!o||o.disabled||"true"===o.getAttribute("aria-disabled"));if(!(o&&!o.hasAttribute("tabindex")||r))return n;n+="next"===t?1:-1}}(function(){var e=ae.length-1;if("reset"===n)return j;if("start"===n)return 0;if("end"===n)return e;var t=J.current+n;return t<0?-1===t&&S?-1:m&&-1!==J.current||1<Math.abs(n)?0:e:e<t?t===1+e&&S?-1:m||1<Math.abs(n)?e:0:t}(),o),le({index:o,reason:e,event:t}),r&&"reset"!==n&&(-1===o?q.current.value=G:(o=_(ae[o]),0===(q.current.value=o).toLowerCase().indexOf(G.toLowerCase())&&0<G.length&&q.current.setSelectionRange(G.length,o.length))))}),de=React.useCallback(function(){var t,n,e;ie&&(t=D?Y[0]:Y,0!==ae.length&&null!=t?U.current&&(null==t?J.current>=ae.length-1?le({index:ae.length-1}):le({index:J.current}):(n=ae[J.current],D&&n&&-1!==findIndex(Y,function(e){return E(n,e)})||(-1===(e=findIndex(ae,function(e){return E(e,t)}))?se({diff:"reset"}):le({index:e})))):se({diff:"reset"}))},[ae.length,!D&&Y,x,se,le,ie,G,D]),fe=useEventCallback(function(e){setRef(U,e),e&&de()});"production"!==process.env.NODE_ENV&&React.useEffect(function(){q.current&&"INPUT"===q.current.nodeName||console.error(["Material-UI: Unable to find the input element. It was resolved to ".concat(q.current," while an HTMLInputElement was expected."),"Instead, ".concat(v," expects an input element."),"","useAutocomplete"===v?"Make sure you have binded getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.":"Make sure you have customized the input component correctly."].join("\n"))},[v]),React.useEffect(function(){de()},[de]);function pe(e){te||(ne(!0),oe(!0),M&&M(e))}function ve(e,t){te&&(ne(!1),I&&I(e,t))}function ge(e,t,n,o){Y!==t&&(w&&w(e,t,n,o),W(t))}function he(e,t){var n,o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:"selectOption",r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:"options",i=o,o=t;D&&(o=Array.isArray(Y)?Y.slice():[],"production"===process.env.NODE_ENV||1<(n=o.filter(function(e){return E(t,e)})).length&&console.error(["Material-UI: The `isOptionEqualToValue` method of ".concat(v," do not handle the arguments correctly."),"The component expects a single value to match a given option but found ".concat(n.length," matches.")].join("\n")),-1===(n=findIndex(o,function(e){return E(t,e)}))?o.push(t):"freeSolo"!==r&&(o.splice(n,1),i="removeOption")),$(e,o),ge(e,o,i,{option:t}),h||e.ctrlKey||e.metaKey||ve(e,i),(!0===c||"touch"===c&&be.current||"mouse"===c&&!be.current)&&q.current.blur()}var be=React.useRef(!1);function me(e,t){D&&(ve(e,"toggleInput"),-1===(e=B)?""===G&&"previous"===t&&(e=Y.length-1):(e=(e+="next"===t?1:-1)<0?0:e)===Y.length&&(e=-1),e=function(e,t){if(-1===e)return-1;for(var n=e;;){if("next"===t&&n===Y.length||"previous"===t&&-1===n)return-1;var o=z.querySelector('[data-tag-index="'.concat(n,'"]'));if(o&&o.hasAttribute("tabindex")&&!o.disabled&&"true"!==o.getAttribute("aria-disabled"))return n;n+="next"===t?1:-1}}(e,t),K(e),ce(e))}function xe(e){F.current=!0,Q(""),A&&A(e,"","clear"),ge(e,D?[]:null,"clear")}function ye(e){Z(!0),N&&!F.current&&pe(e)}function Oe(e){null!==U.current&&U.current.parentElement.contains(document.activeElement)?q.current.focus():(Z(!1),H.current=!0,F.current=!1,a&&-1!==J.current&&ie?he(e,ae[J.current],"blur"):a&&y&&""!==G?he(e,G,"blur","freeSolo"):d&&$(e,Y),ve(e,"blur"))}function ke(e){var t=e.target.value;G!==t&&(Q(t),oe(!1),A&&A(e,t,"input")),""===t?g||D||ge(e,null,"clear"):pe(e)}function Ee(e){le({event:e,index:Number(e.currentTarget.getAttribute("data-option-index")),reason:"mouse"})}function Ce(){be.current=!0}function Re(e){var t=Number(e.currentTarget.getAttribute("data-option-index"));he(e,ae[t],"selectOption"),be.current=!1}function Se(e){te?ve(e,"toggleInput"):pe(e)}function De(e){e.target.getAttribute("id")!==V&&e.preventDefault()}function we(){q.current.focus(),P&&H.current&&q.current.selectionEnd-q.current.selectionStart==0&&q.current.select(),H.current=!1}function Ie(e){""!==G&&te||Se(e)}var Te,Ae,t=(t=y&&0<G.length)||(D?0<Y.length:null!==Y),Me=ae;return C&&(Te=new Map,Ae=!1,Me=ae.reduce(function(e,t,n){var o=C(t);return 0<e.length&&e[e.length-1].group===o?e[e.length-1].options.push(t):("production"!==process.env.NODE_ENV&&(Te.get(o)&&!Ae&&(console.warn("Material-UI: The options provided combined with the `groupBy` method of ".concat(v," returns duplicated headers."),"You can solve the issue by sorting the options with the output of `groupBy`."),Ae=!0),Te.set(o,!0)),e.push({key:n,index:n,group:o,options:[t]})),e},[])),l&&X&&Oe(),{getRootProps:function(){var o,e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return _extends({"aria-owns":ue?"".concat(V,"-listbox"):null,role:"combobox","aria-expanded":ue},e,{onKeyDown:(o=e,function(e){if(o.onKeyDown&&o.onKeyDown(e),!e.defaultMuiPrevented&&(-1!==B&&-1===["ArrowLeft","ArrowRight"].indexOf(e.key)&&(K(-1),ce(-1)),229!==e.which))switch(e.key){case"Home":ie&&R&&(e.preventDefault(),se({diff:"start",direction:"next",reason:"keyboard",event:e}));break;case"End":ie&&R&&(e.preventDefault(),se({diff:"end",direction:"previous",reason:"keyboard",event:e}));break;case"PageUp":e.preventDefault(),se({diff:-pageSize,direction:"previous",reason:"keyboard",event:e}),pe(e);break;case"PageDown":e.preventDefault(),se({diff:pageSize,direction:"next",reason:"keyboard",event:e}),pe(e);break;case"ArrowDown":e.preventDefault(),se({diff:1,direction:"next",reason:"keyboard",event:e}),pe(e);break;case"ArrowUp":e.preventDefault(),se({diff:-1,direction:"previous",reason:"keyboard",event:e}),pe(e);break;case"ArrowLeft":me(e,"previous");break;case"ArrowRight":me(e,"next");break;case"Enter":if(-1!==J.current&&ie){var t=ae[J.current],n=!!O&&O(t);if(e.preventDefault(),n)return;he(e,t,"selectOption"),r&&q.current.setSelectionRange(q.current.value.length,q.current.value.length)}else y&&""!==G&&!1==re&&(D&&e.preventDefault(),he(e,G,"createOption","freeSolo"));break;case"Escape":ie?(e.preventDefault(),e.stopPropagation(),ve(e,"escape")):p&&(""!==G||D&&0<Y.length)&&(e.preventDefault(),e.stopPropagation(),xe(e));break;case"Backspace":D&&""===G&&0<Y.length&&(n=-1===B?Y.length-1:B,(t=Y.slice()).splice(n,1),ge(e,t,"removeOption",{option:Y[n]}))}}),onMouseDown:De,onClick:we})},getInputLabelProps:function(){return{id:"".concat(V,"-label"),htmlFor:V}},getInputProps:function(){return{id:V,value:G,onBlur:Oe,onFocus:ye,onChange:ke,onMouseDown:Ie,"aria-activedescendant":ie?"":null,"aria-autocomplete":r?"both":"list","aria-controls":ue?"".concat(V,"-listbox"):null,autoComplete:"off",ref:q,autoCapitalize:"none",spellCheck:"false"}},getClearProps:function(){return{tabIndex:-1,onClick:xe}},getPopupIndicatorProps:function(){return{tabIndex:-1,onClick:Se}},getTagProps:function(e){var n,e=e.index;return{key:e,"data-tag-index":e,tabIndex:-1,onDelete:(n=e,function(e){var t=Y.slice();t.splice(n,1),ge(e,t,"removeOption",{option:Y[n]})})}},getListboxProps:function(){return{role:"listbox",id:"".concat(V,"-listbox"),"aria-labelledby":"".concat(V,"-label"),ref:fe,onMouseDown:function(e){e.preventDefault()}}},getOptionProps:function(e){var t=e.index,n=e.option,o=(D?Y:[Y]).some(function(e){return null!=e&&E(n,e)}),e=!!O&&O(n);return{key:_(n),tabIndex:-1,role:"option",id:"".concat(V,"-option-").concat(t),onMouseOver:Ee,onClick:Re,onTouchStart:Ce,"data-option-index":t,"aria-disabled":e,"aria-selected":o}},id:V,inputValue:G,value:Y,dirty:t,popupOpen:ie,focused:X||-1!==B,anchorEl:z,setAnchorEl:f,focusedTag:B,groupedOptions:Me}}export{createFilterOptions};