flux0uz-turnstone
Version:
React customisable autocomplete component with typeahead and grouped results from multiple APIs.
26 lines (23 loc) • 28.5 kB
JavaScript
(function(l,me){typeof exports=="object"&&typeof module!="undefined"?module.exports=me(require("react")):typeof define=="function"&&define.amd?define(["react"],me):(l=typeof globalThis!="undefined"?globalThis:l||self,l.turnstone=me(l.React))})(this,function(l){"use strict";function me(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var X=me(l),Qe={exports:{}},Wt="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",Bt=Wt,Vt=Bt;function ze(){}function Ke(){}Ke.resetWarningCache=ze;var $t=function(){function e(a,n,i,o,u,v){if(v!==Vt){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}e.isRequired=e;function r(){return e}var t={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:r,element:e,elementType:e,instanceOf:r,node:e,objectOf:r,oneOf:r,oneOfType:r,shape:r,exact:r,checkPropTypes:Ke,resetWarningCache:ze};return t.PropTypes=t,t};Qe.exports=$t();var f=Qe.exports;const Je="SET_QUERY",Ye="SET_ITEMS",Xe="SET_ITEMS_ERROR",Ze="CLEAR",et="SET_HIGHLIGHTED",Ut="CLEAR_HIGHLIGHTED",tt="NEXT_HIGHLIGHTED",rt="PREV_HIGHLIGHTED",nt="SET_SELECTED",R=void 0;function ue(e){return e===R}const Ce=(e,r)=>r[e]?{index:e,text:r[e].text}:R,Gt=(e,r)=>{const t=(()=>{let a,n;switch(r.type){case Je:return a={itemsError:!1,query:r.query,selected:R},r.query.length<e.props.minQueryLength&&(a.canShowListbox=!1),r.query.length===0&&e.props.defaultListbox&&(a.canShowListbox=!0),a;case Ye:return a={items:r.items,itemsError:!1,highlighted:r.items.length&&e.query.length?Ce(0,r.items):R},(e.query.length||r.items.length)&&(a.canShowListbox=!0),a;case Ze:return{query:"",items:[],itemsError:!1,canShowListbox:!1,highlighted:R,selected:R};case Xe:return{items:[],itemsError:!0,canShowListbox:!1};case et:return{highlighted:Ce(r.index,e.items)};case Ut:return{highlighted:R};case rt:return e.highlighted&&e.highlighted.index>0?{highlighted:Ce(e.highlighted.index-1,e.items)}:{};case tt:return e.highlighted&&e.highlighted.index<e.items.length-1?{highlighted:Ce(e.highlighted.index+1,e.items)}:{};case nt:return n=ue(r.index)?r.item:e.items[r.index],{selected:n,query:n?n.text:R};default:throw new Error("Invalid action type passed to reducer")}})();return{...e,...t}},at=e=>({type:Je,query:e}),qt=e=>({type:Ye,items:e}),Qt=()=>({type:Xe}),zt=()=>({type:Ze}),it=e=>({type:et,index:e}),Kt=()=>({type:rt}),Jt=()=>({type:tt}),we=e=>{const r=nt;return typeof e=="object"?{type:r,item:e}:{type:r,index:e}};var Ie={exports:{}},pe={};/*
object-assign
(c) Sindre Sorhus
@license MIT
*/var ot=Object.getOwnPropertySymbols,Yt=Object.prototype.hasOwnProperty,Xt=Object.prototype.propertyIsEnumerable;function Zt(e){if(e==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function er(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de",Object.getOwnPropertyNames(e)[0]==="5")return!1;for(var r={},t=0;t<10;t++)r["_"+String.fromCharCode(t)]=t;var a=Object.getOwnPropertyNames(r).map(function(i){return r[i]});if(a.join("")!=="0123456789")return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(i){n[i]=i}),Object.keys(Object.assign({},n)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}er();/** @license React v17.0.2
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var tr=X.default,st=60103;if(pe.Fragment=60107,typeof Symbol=="function"&&Symbol.for){var ut=Symbol.for;st=ut("react.element"),pe.Fragment=ut("react.fragment")}var rr=tr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,nr=Object.prototype.hasOwnProperty,ar={key:!0,ref:!0,__self:!0,__source:!0};function ct(e,r,t){var a,n={},i=null,o=null;t!==void 0&&(i=""+t),r.key!==void 0&&(i=""+r.key),r.ref!==void 0&&(o=r.ref);for(a in r)nr.call(r,a)&&!ar.hasOwnProperty(a)&&(n[a]=r[a]);if(e&&e.defaultProps)for(a in r=e.defaultProps,r)n[a]===void 0&&(n[a]=r[a]);return{$$typeof:st,type:e,key:i,ref:o,props:n,_owner:rr.current}}pe.jsx=ct,pe.jsxs=ct,Ie.exports=pe;const p=Ie.exports.jsx,lt=Ie.exports.jsxs,ft=Ie.exports.Fragment,Z=l.createContext(),ir=e=>{const{text:r="",items:t=[]}=e,{children:a,...n}=e,[i,o]=l.useReducer(Gt,{query:r,items:t,itemsError:!1,canShowListbox:!1,highlighted:R,selected:R,props:n});return l.useEffect(()=>o(at(r)),[r]),p(Z.Provider,{value:{state:i,dispatch:o},children:a})},Ne={listbox:{position:"absolute",zIndex:4}};function or(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function sr(e){const{text:r,match:t,global:a,styles:n}=e,o=`${a?"":"^"}(${or(t)})`,u=new RegExp(o,"i"),v=t?r.split(u).filter(c=>c.length):[r],s=v.map((c,h)=>c.toLowerCase()===t.toLowerCase()?p("strong",{className:n.match,children:v[h]},`part${h}`):p(X.default.Fragment,{children:v[h]},`part${h}`));return p(ft,{children:s})}function dt(e){const{index:r,item:t,styles:a}=e,{state:n,dispatch:i}=l.useContext(Z),{highlighted:o,query:u}=n,v=n.props.Item,s=t.searchType==="contains",c=o&&r===o.index,h=a[c?"highlightedItem":"item"],m=()=>{i(it(r))},S=()=>{i(we(r))},P=(y,d)=>{i(we({value:y,displayField:d,text:y[d]}))},x=v?p(v,{appearsInDefaultListbox:t.defaultListbox,groupId:t.groupId,groupIndex:t.groupIndex,groupName:t.groupName,index:r,isHighlighted:c,item:t.value,query:u,searchType:t.searchType,setSelected:P,totalItems:n.items.length}):n.props.matchText&&!t.defaultListbox?p(sr,{text:t.text,match:u,global:s,styles:a}):p(ft,{children:t.text});return p("div",{className:h,onMouseEnter:m,onMouseDown:S,role:"option","aria-selected":c,"aria-label":t.text,children:x})}function ur(e){const{groupName:r,index:t,item:a,styles:n}=e,{state:i}=l.useContext(Z),o=i.props.GroupName,u=!!r&&(o?p(o,{id:a.groupId,index:a.groupIndex,children:r}):r);return lt(X.default.Fragment,{children:[!!u&&p("div",{className:n.groupHeading,children:u}),p(dt,{index:t,item:a,styles:n},`item${t}`)]})}function cr(e){const{id:r,items:t,noItemsMessage:a,styles:n}=e,{state:i}=l.useContext(Z),o=()=>p("div",{id:r,className:n.listbox,style:Ne.listbox,role:"listbox",children:t.map((s,c)=>c===0||s.groupIndex!==t[c-1].groupIndex?p(ur,{groupName:s.groupName,index:c,item:s,styles:n},`item${c}`):p(dt,{index:c,item:s,styles:n},`item${c}`))}),u=()=>p("div",{id:r,className:n.listbox,style:Ne.listbox,children:p("div",{className:n.noItems,children:a})});return(()=>t&&t.length?o():a&&i.query?u():p(X.default.Fragment,{}))()}function lr(e){const{id:r,errorMessage:t,styles:a}=e;return p("div",{id:r,className:a.errorbox,style:Ne.listbox,children:p("div",{className:a.errorMessage,children:t})})}function fr(e,r,t){var a=this,n=l.useRef(null),i=l.useRef(0),o=l.useRef(null),u=l.useRef([]),v=l.useRef(),s=l.useRef(),c=l.useRef(e),h=l.useRef(!0);c.current=e;var m=!r&&r!==0&&typeof window!="undefined";if(typeof e!="function")throw new TypeError("Expected a function");r=+r||0,t=t||{};var S=!!t.leading,P="trailing"in t?!!t.trailing:!0,x="maxWait"in t,y=x?Math.max(+t.maxWait||0,r):null;l.useEffect(function(){return h.current=!0,function(){h.current=!1}},[]);var d=l.useMemo(function(){var G=function(E){var g=u.current,M=v.current;return u.current=v.current=null,i.current=E,s.current=c.current.apply(M,g)},N=function(E,g){m&&cancelAnimationFrame(o.current),o.current=m?requestAnimationFrame(E):setTimeout(E,g)},F=function(E){if(!h.current)return!1;var g=E-n.current,M=E-i.current;return!n.current||g>=r||g<0||x&&M>=y},A=function(E){return o.current=null,P&&u.current?G(E):(u.current=v.current=null,s.current)},O=function(){var E=Date.now();if(F(E))return A(E);if(!!h.current){var g=E-n.current,M=E-i.current,T=r-g,le=x?Math.min(T,y-M):T;N(O,le)}},D=function(){for(var E=[],g=0;g<arguments.length;g++)E[g]=arguments[g];var M=Date.now(),T=F(M);if(u.current=E,v.current=a,n.current=M,T){if(!o.current&&h.current)return i.current=n.current,N(O,r),S?G(n.current):s.current;if(x)return N(O,r),G(n.current)}return o.current||N(O,r),s.current};return D.cancel=function(){o.current&&(m?cancelAnimationFrame(o.current):clearTimeout(o.current)),i.current=0,u.current=n.current=v.current=o.current=null},D.isPending=function(){return!!o.current},D.flush=function(){return o.current?A(Date.now()):s.current},D},[S,x,r,y,P,m]);return d}function dr(e,r){return e===r}function vt(e){return typeof e=="function"?function(){return e}:e}function vr(e){var r=l.useState(vt(e)),t=r[0],a=r[1],n=l.useCallback(function(i){return a(vt(i))},[]);return[t,n]}function hr(e,r,t){var a=t&&t.equalityFn||dr,n=vr(e),i=n[0],o=n[1],u=fr(l.useCallback(function(s){return o(s)},[o]),r,t),v=l.useRef(e);return a(v.current,e)||(u(e),v.current=e),[i,u]}/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function ht(e,r,t,a){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(c){try{s(a.next(c))}catch(h){o(h)}}function v(c){try{s(a.throw(c))}catch(h){o(h)}}function s(c){c.done?i(c.value):n(c.value).then(u,v)}s((a=a.apply(e,r||[])).next())})}function mt(e,r){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},a,n,i,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(s){return function(c){return v([s,c])}}function v(s){if(a)throw new TypeError("Generator is already executing.");for(;t;)try{if(a=1,n&&(i=s[0]&2?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[s[0]&2,i.value]),s[0]){case 0:case 1:i=s;break;case 4:return t.label++,{value:s[1],done:!1};case 5:t.label++,n=s[1],s=[0];continue;case 7:s=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(s[0]===6||s[0]===2)){t=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){t.label=s[1];break}if(s[0]===6&&t.label<i[1]){t.label=i[1],i=s;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(s);break}i[2]&&t.ops.pop(),t.trys.pop();continue}s=r.call(e,t)}catch(c){s=[6,c],n=0}finally{a=i=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}var q=function(){},I=q(),ge=Object,_=function(e){return e===I},ee=function(e){return typeof e=="function"},z=function(e,r){return ge.assign({},e,r)},Fe="undefined",Ae=function(){return typeof window!=Fe},mr=function(){return typeof document!=Fe},pr=function(){return Ae()&&typeof window.requestAnimationFrame!=Fe},Oe=new WeakMap,gr=0,ye=function(e){var r=typeof e,t=e&&e.constructor,a=t==Date,n,i;if(ge(e)===e&&!a&&t!=RegExp){if(n=Oe.get(e),n)return n;if(n=++gr+"~",Oe.set(e,n),t==Array){for(n="@",i=0;i<e.length;i++)n+=ye(e[i])+",";Oe.set(e,n)}if(t==ge){n="#";for(var o=ge.keys(e).sort();!_(i=o.pop());)_(e[i])||(n+=i+":"+ye(e[i])+",");Oe.set(e,n)}}else n=a?e.toJSON():r=="symbol"?e.toString():r=="string"?JSON.stringify(e):""+e;return n},Me=!0,yr=function(){return Me},pt=Ae(),He=mr(),Pe=pt&&window.addEventListener?window.addEventListener.bind(window):q,br=He?document.addEventListener.bind(document):q,je=pt&&window.removeEventListener?window.removeEventListener.bind(window):q,xr=He?document.removeEventListener.bind(document):q,Er=function(){var e=He&&document.visibilityState;return _(e)||e!=="hidden"},Tr=function(e){return br("visibilitychange",e),Pe("focus",e),function(){xr("visibilitychange",e),je("focus",e)}},Sr=function(e){var r=function(){Me=!0,e()},t=function(){Me=!1};return Pe("online",r),Pe("offline",t),function(){je("online",r),je("offline",t)}},Cr={isOnline:yr,isVisible:Er},wr={initFocus:Tr,initReconnect:Sr},Le=!Ae()||"Deno"in window,Ir=function(e){return pr()?window.requestAnimationFrame(e):setTimeout(e,1)},be=Le?l.useEffect:l.useLayoutEffect,ke=typeof navigator!="undefined"&&navigator.connection,gt=!Le&&ke&&(["slow-2g","2g"].includes(ke.effectiveType)||ke.saveData),yt=function(e){if(ee(e))try{e=e()}catch{e=""}var r=[].concat(e);e=typeof e=="string"?e:(Array.isArray(e)?e.length:e)?ye(e):"";var t=e?"$swr$"+e:"";return[e,r,t]},te=new WeakMap,bt=0,xt=1,Et=2,xe=function(e,r,t,a,n,i,o){o===void 0&&(o=!0);var u=te.get(e),v=u[0],s=u[1],c=u[3],h=v[r],m=s[r];if(o&&m)for(var S=0;S<m.length;++S)m[S](t,a,n);return i&&(delete c[r],h&&h[0])?h[0](Et).then(function(){return e.get(r)}):e.get(r)},Or=0,We=function(){return++Or},Tt=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return ht(void 0,void 0,void 0,function(){var t,a,n,i,o,u,v,s,c,h,m,S,P,x,y,d,G,N,F,A;return mt(this,function(O){switch(O.label){case 0:if(t=e[0],a=e[1],n=e[2],i=e[3],o=typeof i=="boolean"?{revalidate:i}:i||{},u=_(o.populateCache)?!0:o.populateCache,v=o.revalidate!==!1,s=o.rollbackOnError!==!1,c=o.optimisticData,h=yt(a),m=h[0],S=h[2],!m)return[2];if(P=te.get(t),x=P[2],e.length<3)return[2,xe(t,m,t.get(m),I,I,v,!0)];if(y=n,G=We(),x[m]=[G,0],N=!_(c),F=t.get(m),N&&(t.set(m,c),xe(t,m,c)),ee(y))try{y=y(t.get(m))}catch(D){d=D}return y&&ee(y.then)?[4,y.catch(function(D){d=D})]:[3,2];case 1:if(y=O.sent(),G!==x[m][0]){if(d)throw d;return[2,y]}else d&&N&&s&&(u=!0,y=F,t.set(m,F));O.label=2;case 2:return u&&(d||(ee(u)&&(y=u(y,F)),t.set(m,y)),t.set(S,z(t.get(S),{error:d}))),x[m][1]=We(),[4,xe(t,m,y,d,I,v,!!u)];case 3:if(A=O.sent(),d)throw d;return[2,u?A:y]}})})},St=function(e,r){for(var t in e)e[t][0]&&e[t][0](r)},Ct=function(e,r){if(!te.has(e)){var t=z(wr,r),a={},n=Tt.bind(I,e),i=q;if(te.set(e,[a,{},{},{},n]),!Le){var o=t.initFocus(setTimeout.bind(I,St.bind(I,a,bt))),u=t.initReconnect(setTimeout.bind(I,St.bind(I,a,xt)));i=function(){o&&o(),u&&u(),te.delete(e)}}return[e,n,i]}return[e,te.get(e)[4]]},Lr=function(e,r,t,a,n){var i=t.errorRetryCount,o=n.retryCount,u=~~((Math.random()+.5)*(1<<(o<8?o:8)))*t.errorRetryInterval;!_(i)&&o>i||setTimeout(a,u,n)},wt=Ct(new Map),It=wt[0],_r=wt[1],Ot=z({onLoadingSlow:q,onSuccess:q,onError:q,onErrorRetry:Lr,onDiscarded:q,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:gt?1e4:5e3,focusThrottleInterval:5*1e3,dedupingInterval:2*1e3,loadingTimeout:gt?5e3:3e3,compare:function(e,r){return ye(e)==ye(r)},isPaused:function(){return!1},cache:It,mutate:_r,fallback:{}},Cr),Lt=function(e,r){var t=z(e,r);if(r){var a=e.use,n=e.fallback,i=r.use,o=r.fallback;a&&i&&(t.use=a.concat(i)),n&&o&&(t.fallback=z(n,o))}return t},Be=l.createContext({}),Dr=function(e){var r=e.value,t=Lt(l.useContext(Be),r),a=r&&r.provider,n=l.useState(function(){return a?Ct(a(t.cache||It),r):I})[0];return n&&(t.cache=n[0],t.mutate=n[1]),be(function(){return n?n[2]:I},[]),l.createElement(Be.Provider,z(e,{value:t}))},Rr=function(e,r){var t=l.useState({})[1],a=l.useRef(e),n=l.useRef({data:!1,error:!1,isValidating:!1}),i=l.useCallback(function(o){var u=!1,v=a.current;for(var s in o){var c=s;v[c]!==o[c]&&(v[c]=o[c],n.current[c]&&(u=!0))}u&&!r.current&&t({})},[]);return be(function(){a.current=e}),[a,n.current,i]},Nr=function(e){return ee(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(e[1]===null?e[2]:e[1])||{}]},Fr=function(){return z(Ot,l.useContext(Be))},Ar=function(e){return function(){for(var t=[],a=0;a<arguments.length;a++)t[a]=arguments[a];var n=Fr(),i=Nr(t),o=i[0],u=i[1],v=i[2],s=Lt(n,v),c=e,h=s.use;if(h)for(var m=h.length;m-- >0;)c=h[m](c);return c(o,u||s.fetcher,s)}},_t=function(e,r,t){var a=r[e]||(r[e]=[]);return a.push(t),function(){var n=a.indexOf(t);n>=0&&(a[n]=a[a.length-1],a.pop())}},Ve={dedupe:!0},Mr=function(e,r,t){var a=t.cache,n=t.compare,i=t.fallbackData,o=t.suspense,u=t.revalidateOnMount,v=t.refreshInterval,s=t.refreshWhenHidden,c=t.refreshWhenOffline,h=te.get(a),m=h[0],S=h[1],P=h[2],x=h[3],y=yt(e),d=y[0],G=y[1],N=y[2],F=l.useRef(!1),A=l.useRef(!1),O=l.useRef(d),D=l.useRef(r),E=l.useRef(t),g=function(){return E.current},M=function(){return g().isVisible()&&g().isOnline()},T=function(k){return a.set(N,z(a.get(N),k))},le=a.get(d),Ee=_(i)?t.fallback[d]:i,B=_(le)?Ee:le,_e=a.get(N)||{},re=_e.error,ne=!F.current,fe=function(){return ne&&!_(u)?u:g().isPaused()?!1:o?!_(B):_(B)||t.revalidateIfStale},L=function(){return!d||!r?!1:_e.isValidating?!0:ne&&fe()},V=L(),ae=Rr({data:B,error:re,isValidating:V},A),j=ae[0],de=ae[1],ve=ae[2],Q=l.useCallback(function(k){return ht(void 0,void 0,void 0,function(){var b,C,H,ie,oe,W,w,$,U,Te,he,K,Se;return mt(this,function(se){switch(se.label){case 0:if(b=D.current,!d||!b||A.current||g().isPaused())return[2,!1];ie=!0,oe=k||{},W=!x[d]||!oe.dedupe,w=function(){return!A.current&&d===O.current&&F.current},$=function(){var J=x[d];J&&J[1]===H&&delete x[d]},U={isValidating:!1},Te=function(){T({isValidating:!1}),w()&&ve(U)},T({isValidating:!0}),ve({isValidating:!0}),se.label=1;case 1:return se.trys.push([1,3,,4]),W&&(xe(a,d,j.current.data,j.current.error,!0),t.loadingTimeout&&!a.get(d)&&setTimeout(function(){ie&&w()&&g().onLoadingSlow(d,t)},t.loadingTimeout),x[d]=[b.apply(void 0,G),We()]),Se=x[d],C=Se[0],H=Se[1],[4,C];case 2:return C=se.sent(),W&&setTimeout($,t.dedupingInterval),!x[d]||x[d][1]!==H?(W&&w()&&g().onDiscarded(d),[2,!1]):(T({error:I}),U.error=I,he=P[d],!_(he)&&(H<=he[0]||H<=he[1]||he[1]===0)?(Te(),W&&w()&&g().onDiscarded(d),[2,!1]):(n(j.current.data,C)?U.data=j.current.data:U.data=C,n(a.get(d),C)||a.set(d,C),W&&w()&&g().onSuccess(C,d,t),[3,4]));case 3:return K=se.sent(),$(),g().isPaused()||(T({error:K}),U.error=K,W&&w()&&(g().onError(K,d,t),(typeof t.shouldRetryOnError=="boolean"&&t.shouldRetryOnError||ee(t.shouldRetryOnError)&&t.shouldRetryOnError(K))&&M()&&g().onErrorRetry(K,d,t,Q,{retryCount:(oe.retryCount||0)+1,dedupe:!0}))),[3,4];case 4:return ie=!1,Te(),w()&&W&&xe(a,d,U.data,U.error,!1),[2,!0]}})})},[d]),De=l.useCallback(Tt.bind(I,a,function(){return O.current}),[]);if(be(function(){D.current=r,E.current=t}),be(function(){if(!!d){var k=d!==O.current,b=Q.bind(I,Ve),C=function(w,$,U){ve(z({error:$,isValidating:U},n(j.current.data,w)?I:{data:w}))},H=0,ie=function(w){if(w==bt){var $=Date.now();g().revalidateOnFocus&&$>H&&M()&&(H=$+g().focusThrottleInterval,b())}else if(w==xt)g().revalidateOnReconnect&&M()&&b();else if(w==Et)return Q()},oe=_t(d,S,C),W=_t(d,m,ie);return A.current=!1,O.current=d,F.current=!0,k&&ve({data:B,error:re,isValidating:V}),fe()&&(_(B)||Le?b():Ir(b)),function(){A.current=!0,oe(),W()}}},[d,Q]),be(function(){var k;function b(){var H=ee(v)?v(B):v;H&&k!==-1&&(k=setTimeout(C,H))}function C(){!j.current.error&&(s||g().isVisible())&&(c||g().isOnline())?Q(Ve).then(b):b()}return b(),function(){k&&(clearTimeout(k),k=-1)}},[v,s,c,Q]),l.useDebugValue(B),o&&_(B)&&d)throw D.current=r,E.current=t,A.current=!1,_(re)?Q(Ve):re;return{mutate:De,get data(){return de.data=!0,B},get error(){return de.error=!0,re},get isValidating(){return de.isValidating=!0,V}}};ge.defineProperty(Dr,"default",{value:Ot});var Hr=Ar(Mr),Dt={};Object.defineProperty(Dt,"__esModule",{value:!0});var Pr=Dt.default=jr;function jr(e,r){for(const t in e)if(typeof e[t]===r)return e[t]}function kr(e){return(r,t,a)=>{const n=l.useRef(),i=e(r,t,a);l.useEffect(()=>{i.data!==void 0&&(n.current=i.data)},[i.data]);const o=l.useCallback(()=>{n.current=void 0},[]),u=i.data===void 0?n.current:i.data,v=i.data===void 0&&n.current!==void 0;return Object.assign({},i,{data:u,isLagging:v,resetLaggy:o})}}const Wr=(e,r)=>typeof e=="function"?e:()=>Promise.resolve(Array.isArray(e)?e:[{...e,name:"",ratio:r}]),Br=(e,r)=>{const{data:t,displayField:a,searchType:n}=e;switch(n&&n.toLowerCase()){case"startswith":return t.filter(o=>$e(o,a).toLowerCase().startsWith(r.toLowerCase()));case"contains":return t.filter(o=>$e(o,a).toLowerCase().includes(r.toLowerCase()));default:return t}},Vr=(e,r,t)=>{const a=r.map(s=>s.ratio||1),n=a.reduce((s,c)=>s+c,0),i=t/n,o=e.flat().length,u=[];let v=o<t?o:t;for(;v>0;)e=e.map((s,c)=>(u[c]?u[c]<s.length&&(v-=++u[c]):(u[c]=Math.round(a[c]*i),u[c]>s.length&&(u[c]=s.length),v=v-u[c]),s));return e.map((s,c)=>s.slice(0,u[c]))},$e=(e,r)=>{const a=typeof e==="string"&&ue(r)?e:e[r];return ue(a)?Pr(e,"string")||"":a},$r=e=>{const r={use:[kr]};return e?{...r,revalidateIfStale:!1,revalidateOnFocus:!1,revalidateOnReconnect:!1}:r},Ur=(e,r,t,a,n)=>{if(t&&e.length>0&&e.length<a)return[];if(!t&&e.length<a)return[];const i=t&&!e.length;return Wr(i?t:r,n)(e).then(u=>{const v=u.map(s=>typeof s.data=="function"?s.data(e):Promise.resolve(Br(s,e)));return Promise.all(v).then(s=>(s=s.reduce((c,h,m)=>{const{id:S,name:P,displayField:x,searchType:y}=u[m];return[...c,h.map(d=>({value:d,text:$e(d,x),groupIndex:m,groupId:S,groupName:P,searchType:y,displayField:x,defaultListbox:i}))]},[]),s.length&&(s=Vr(s,u,n)),s.flat()))})},Gr=(e,r,t,a,n,i)=>{const o="X";return Hr([e.toLowerCase(),o],v=>Ur(v,t,a,n,i),$r(r))},ce={container:{position:"relative",textAlign:"left"},containerFocus:{position:"relative",textAlign:"left"},query:{position:"relative",zIndex:1,backgroundColor:"transparent"},queryNoTypeahead:{position:"relative"},typeahead:{position:"absolute",zIndex:0,top:0,left:0},clearButton:{zIndex:2},cancelButton:{zIndex:3}};var qr=["textarea","text","search","tel","url","password"],Qr=function(e){return!!(e.setSelectionRange&&~qr.indexOf(e.type))},zr=Qr,Rt=function(e,r){var t=zr(e)&&e===document.activeElement;if(t){var a=e.selectionStart,n=e.selectionEnd;e.value=r,e.setSelectionRange(a,n)}else e.value=r};const Kr=(e,r)=>typeof e!="string"||typeof r!="string"?!1:e.toLowerCase().startsWith(r.toLowerCase()),Jr=e=>{const{dispatch:r}=l.useContext(Z);l.useEffect(()=>{r(qt(e||[]))},[e,r])},Yr=e=>{const{dispatch:r}=l.useContext(Z);l.useEffect(()=>{e&&r(Qt())},[e,r])},Xr=(e,r,t,a)=>{const n=l.useRef(!0);l.useEffect(()=>{const i=!!t.current,o=(()=>{const u=i?t.current.value:"";return!e||!u.startsWith(e)?"":u})();i&&(t.current.value=o),Rt(r.current,e),n.current&&!e||typeof a=="function"&&a(e),n.current=!1},[e,a,r,t])},Zr=(e,r,t,a)=>{l.useEffect(()=>{const n=e&&r&&t.current.value.length>0&&Kr(e.text,t.current.value)?e.text:"",i=tn(t.current.value,n);a.current&&(a.current.value=n),Rt(t.current,i)},[e,r,t,a])},en=(e,r,t,a)=>{const n=l.useRef(!0);l.useEffect(()=>{let i,o;ue(e)?(i=R,o=R):(t.current&&(t.current.value=""),r.current.blur(),i=e.value,o=e.displayField),n.current&&ue(e)||typeof a=="function"&&a(i,o),n.current=!1},[e,a,r,t])},tn=(e,r)=>{const t=r.substring(0,e.length);return t.length>0&&e.toLowerCase()===t.toLowerCase()&&e!==t?t:e},Nt=X.default.forwardRef((e,r)=>{const{autoFocus:t,cancelButton:a,cancelButtonAriaLabel:n,clearButton:i,clearButtonAriaLabel:o,debounceWait:u,defaultListbox:v,defaultListboxIsImmutable:s,disabled:c,enterKeyHint:h,errorMessage:m,id:S,listbox:P,listboxIsImmutable:x,maxItems:y,minQueryLength:d,name:G,noItemsMessage:N,onBlur:F,onChange:A,onEnter:O,onFocus:D,onSelect:E,onTab:g,placeholder:M,styles:T,tabIndex:le,text:Ee,typeahead:B,Cancel:_e,Clear:re}=e,ne=`${S}-listbox`,fe=`${S}-errorbox`,{state:L,dispatch:V}=l.useContext(Z),[ae]=hr(L.query,u),[j,de]=l.useState(!1),[ve,Q]=l.useState(!1),[De,k]=l.useState(!!Ee),b=l.useRef(null),C=l.useRef(null),H=B&&L.items.length>1,ie=i&&!!L.query,oe=a&&j,W=j&&L.canShowListbox,w=!!e.errorMessage&&L.itemsError,$=j?"containerFocus":"container",U=T[$]||T.container,Te=T[$]?R:ce[$],K=T[j?"inputFocus":"input"]||T.input,Se=H?ce.query:ce.queryNoTypeahead,se=(()=>x&&!(v&&!s&&ae.length===0))(),J=Gr(ae?ae.toLowerCase():"",se,P,v,d,y);Jr(J.data),l.useEffect(()=>{var Y;De&&J.data&&((Y=J.data[0])==null?void 0:Y.text)===Ee&&(V(we(J.data[0])),k(!1))},[De,J.data,Ee,V]),Yr(J.error),Xr(L.query,b,C,A),Zr(L.highlighted,j,b,C),en(L.selected,b,C,E);const Ht=Y=>{const qe=L.highlighted&&L.highlighted.index,jt=ue(qe)?R:L.items[qe],kt=Y.toLowerCase()==="enter"?O:g;jt&&V(we(qe)),typeof kt=="function"&&kt(b.current.value,jt)},rn=Y=>{switch(Y.keyCode){case 40:V(Jt());break;case 38:V(Kt());break;case 13:Ht("enter");break;case 9:Ht("tab");break;case 27:Re();break}},Pt=()=>{V(at(b.current.value))},nn=()=>{Q(!0),Re()},an=()=>{Re()},Re=()=>{b.current.value="",B&&C.current&&(C.current.value=""),V(zt()),b.current.focus()},on=()=>{j||(de(!0),L.items&&L.items.length>0&&V(it(0)),typeof D=="function"&&D())},sn=()=>{ve?b.current.focus():(de(!1),typeof F=="function"&&F()),Q(!1)};return l.useImperativeHandle(r,()=>({focus:()=>{b.current.focus()},blur:()=>{b.current.blur()},select:()=>{b.current.select()},clear:()=>{Re()},query:Y=>{typeof Y=="string"&&(b.current.value=Y,b.current.focus(),Pt())}})),p(X.default.Fragment,{children:lt("div",{className:U,style:Te,role:"combobox","aria-expanded":W,"aria-owns":[ne,fe].join(" "),"aria-haspopup":"listbox",children:[p("input",{id:ne,name:G,className:`${K||""} ${T.query||""}`.trim(),style:Se,disabled:c,placeholder:M,type:"text",autoFocus:t,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",tabIndex:le,enterKeyHint:h,ref:b,onKeyDown:rn,onInput:Pt,onFocus:on,onBlur:sn,"aria-autocomplete":"both","aria-controls":[ne,fe].join(" ")}),H&&p("input",{className:`${K||""} ${T.typeahead||""}`.trim(),style:ce.typeahead,disabled:c,type:"text",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",tabIndex:"-1",readOnly:"readonly","aria-hidden":"true",ref:C}),ie&&p("button",{className:T.clearButton,style:ce.clearButton,onMouseDown:nn,tabIndex:-1,"aria-label":o,children:p(re,{})}),oe&&p("button",{className:T.cancelButton,style:ce.cancelButton,onMouseDown:an,tabIndex:-1,"aria-label":n,children:p(_e,{})}),W&&p(cr,{id:ne,items:L.items,noItemsMessage:N,styles:T}),w&&p(lr,{id:fe,errorMessage:m,styles:T})]})})});Nt.displayName="Container";const Ue={autoFocus:!1,cancelButton:!1,cancelButtonAriaLabel:"Cancel",clearButton:!1,clearButtonAriaLabel:"Clear contents",debounceWait:250,defaultListboxIsImmutable:!0,disabled:!1,id:(()=>`turnstone-${(0|Math.random()*604e5).toString(36)}`)(),listboxIsImmutable:!0,matchText:!1,maxItems:10,minQueryLength:1,placeholder:"",styles:{},typeahead:!0,Cancel:()=>"Cancel",Clear:()=>"\xD7"},Ft=(e,r,t,a)=>{const n=Array.isArray(r.plugins)&&r.plugins[t];if(n){const[i,o]=Array.isArray(n)?n:[n];return p(i,{ref:a,...o,Component:e,componentProps:r,pluginIndex:t,render:Ft})}return p(e,{ref:a,...r})},Ge=X.default.forwardRef((e,r)=>{const t={...Ue,...e};return p(X.default.StrictMode,{children:p(ir,{...t,children:Ft(Nt,t,0,r)})})});Ge.displayName="Turnstone";const At=["startswith","contains"],Mt=f.oneOfType([f.arrayOf(f.exact({data:f.oneOfType([f.func,f.array]).isRequired,searchType:f.oneOf(At),displayField:f.oneOfType([f.number,f.string]),id:f.string,name:f.string.isRequired,ratio:f.number})),f.exact({data:f.oneOfType([f.func,f.array]).isRequired,searchType:f.oneOf(At),displayField:f.oneOfType([f.number,f.string])}),f.func]);return Ge.propTypes={autoFocus:f.bool,cancelButton:f.bool,cancelButtonAriaLabel:f.string,cancelButtonText:f.string,clearButton:f.bool,clearButtonAriaLabel:f.string,clearButtonText:f.string,debounceWait:f.number,defaultListbox:Mt,defaultListboxIsImmutable:f.bool,disabled:f.bool,enterKeyHint:f.oneOf(["enter","done","go","next","previous","search","send"]),errorMessage:f.string,id:f.string,listbox:Mt.isRequired,listboxIsImmutable:f.bool,matchText:f.bool,maxItems:f.number,minQueryLength:e=>{if(f.checkPropTypes({minQueryLength:f.number},{minQueryLength:e.minQueryLength},"prop","Turnstone"),e.minQueryLength<Ue.minQueryLength)return new Error(`Prop "minQueryLength" must be a number greater than ${Ue.minQueryLength-1}`)},name:f.string,noItemsMessage:f.string,onBlur:f.func,onChange:f.func,onEnter:f.func,onFocus:f.func,onSelect:f.func,onTab:f.func,placeholder:f.string,plugins:f.array,styles:f.object,tabIndex:f.number,text:f.string,typeahead:f.bool,Cancel:f.elementType,Clear:f.elementType,Item:f.elementType,GroupName:f.elementType},Ge});