tsdf 8.0.0-beta.2 → 8.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.cjs +1761 -1
- package/dist/main.d.ts +5 -5
- package/dist/main.js +1726 -1
- package/package.json +2 -2
package/dist/main.js
CHANGED
|
@@ -1 +1,1726 @@
|
|
|
1
|
-
import ke from"immer";import Ue from"mitt";import{useCallback as We,useEffect as je}from"react";import{Store as ze,useSubscribeToStore as _e}from"t-state";function ye({fetchFn:l,on:f,mediumPriorityThrottleMs:P=10,lowPriorityThrottleMs:I=200,dynamicRealtimeThrottleMs:M}){let m={e:null,r:null,t:null},V=0,C=0,O=!1,d=0,E=0,y=[],Q=!1,z=0;function H(n){E=n}function k(n){d=n}function U(){if(m.r){f?.("scheduled-fetch-started");let n=m.r.params;m.r=null,w(n,Date.now())}}function W(){O=!0,z=C,m.e=null;let n=Ie();return V=n,()=>re(n)}function re(n){return n===V?(O=!1,y.length>0&&(y.forEach(a=>a()),y=[]),U(),!0):!1}function oe(){return m}async function w(n,a){if(m.e)throw new Error("[tsdf] Fetch already in progress");let t=Ie();C=t,Q=!1,m.e={startTime:a,onEnd:[]};let p=d;d=a;function g(){let G=t!==C||O||t<=z;return Q=G,G}let S=await l({shouldAbort:g,getStartTime:()=>a},n),b=oe();if(!b.e)return d=p,!1;S&&(E=Date.now()-a),b.t&&(clearTimeout(b.t.timeoutId),m.t=null);let N=b.e.onEnd;return b.e=null,N.length>0&&N.forEach(G=>G()),U(),!0}function v(n,a){let t=Date.now();return M&&n==="realtimeUpdate"&&X(t,a)?"rt-scheduled":_(n,t)?"skipped":B(n,a)?"scheduled":(w(a,t),"started")}function _(n,a){return!!(n==="highPriority"&&m.e&&a-m.e.startTime<P||n==="lowPriority"&&(m.e||m.r||O||d&&a-d<I))}function B(n,a){let t=(()=>n==="lowPriority"?!1:!!m.e||!!O)();return t&&(m.r={params:a}),t}function J(n,a){if(!M)return!1;let t=n-(d+E),p=M(E);if(t>=p)return!1;let g=p-t;return m.t={timeoutId:window.setTimeout(()=>{m.t=null,f?.("scheduled-rt-fetch-started"),w(a,Date.now())},g)},!0}function X(n,a){return!E||!d||!M?!1:m.t?!0:m.e?(m.e.onEnd.push(()=>{J(Date.now(),a)}),!0):O?(y.push(()=>{J(Date.now(),a)||(f?.("scheduled-rt-fetch-started"),v("highPriority",a))}),!0):!!J(n,a)}function se(n){m.e&&m.e.onEnd.push(n)}async function i(n){return v("highPriority",n),m.e&&await new Promise(a=>{se(()=>a(!0))}),Q}return{scheduleFetch:v,awaitFetch:i,startMutation:W,get hasPendingFetch(){return!!m.e||!!m.r||!!m.t},get fetchIsInProgress(){return!!m.e},get mutationIsInProgress(){return O},setLastFetchDurantion:H,setLastFetchStartTime:k}}var Oe=0;function Ie(){return++Oe}import Ae from"mitt";import{useMemo as Ke,useState as Ve}from"react";import{useEffect as be,useLayoutEffect as Fe,useMemo as qe,useRef as ie}from"react";import{deepEqual as xe,shallowEqual as Re}from"t-state";function Ce(l,f=xe){let P=ie(),I=ie(0);return f(l,P.current)||(P.current=l,I.current+=1),[I.current]}function le(l,f){return qe(l,Ce(f))}function ve(l){let f=ie({insideEffect:l,insideMemo:l});return f.current.insideMemo=l,Fe(()=>{f.current.insideEffect=l}),f.current}function te(l,f,P){let I=ve(P);Fe(()=>{let M=m=>{I.insideEffect(m)};return l.on(f,M),()=>{l.off(f,M)}},[l,f,I])}function Ne(l,f){let P=ie(f);return be(()=>{P.current=l}),P.current}function Te(l,f,{equalityFn:P=Re,callOnMount:I,layoutEffect:M}={}){let m=M?Fe:be,V=Ne(l,I?void 0:l);m(()=>{if(!P(l,V))return f({prev:V,current:l})})}function he(l){let f=ie();return f.current===void 0&&(f.current=l()),f.current}function ae(l,f,P){let I=he(()=>Ae()),[M,m]=Ve(!0);Te(l&&M&&f,({current:C})=>{C&&P()},{callOnMount:!0}),te(I,"isLoaded",C=>{l&&f&&C&&m(!1)});function V(C){return Ke(()=>{if(l){let O=f&&M?"loading":C.status;return{...C,isLoading:O==="loading",status:O}}return C},[l,M,C])}return[V,I.emit]}function Je({debugName:l,fetchFn:f,initialData:P,disableRefetchOnWindowFocus:I,disableRefetchOnMount:M,lowPriorityThrottleMs:m,mediumPriorityThrottleMs:V,dynamicRealtimeThrottleMs:C,errorNormalizer:O}){let d=new ze({debugName:l,state:{data:P??null,error:null,status:P?"success":"idle",refetchOnMount:!1}});async function E(w,v){d.setPartialState({status:d.state.status==="success"?"refetching":"loading",error:null,refetchOnMount:!1},{action:d.state.status==="success"?"fetch-start-refetching":"fetch-start-loading"});try{let _=await f();return w.shouldAbort()?!1:(d.setPartialState({data:_,status:"success"},{action:"fetch-success"}),!0)}catch(_){return w.shouldAbort()||d.setPartialState({error:O(_),status:"error"},{action:"fetch-error"}),!1}}let y=ye({fetchFn:E,lowPriorityThrottleMs:m,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:V});function Q(w){return y.scheduleFetch(w,null)}async function z(){return await y.awaitFetch(null)?{data:null,error:O(new Error("Aborted"))}:d.state.data?d.state.error?{data:null,error:d.state.error}:{data:d.state.data,error:null}:{data:null,error:O(new Error("No data"))}}let H=Ue(),k=!1;function U(w="highPriority"){d.setKey("refetchOnMount",w,{action:"invalidate-data"}),k=!1,H.emit("invalidateData",w)}function W({selector:w,disabled:v,returnRefetchingStatus:_,disableRefetchOnMount:B=M,returnIdleStatus:J=!!v,ensureIsLoaded:X}={}){let se=We(t=>{let{error:p}=t,g=w?w(t.data):t.data,S=t.status;return!J&&S==="idle"&&(S="loading"),!_&&S==="refetching"&&(S="success"),{data:g,error:p,status:S,isLoading:S==="loading"}},[_,J,w]),i=d.useSelector(se,{useExternalDeps:!0});te(H,"invalidateData",t=>{k||(Q(t),k=!0)}),je(()=>{v||(B?(d.state.refetchOnMount||d.state.status==="idle")&&Q(d.state.refetchOnMount||"lowPriority"):Q("lowPriority"))},[B,v]);let[n,a]=ae(X,!v,()=>{Q("highPriority")});return _e(d,({observe:t})=>{t.ifSelector(p=>p.status).change.then(({current:p})=>{(p==="success"||p==="error")&&a("isLoaded",!0)})}),n(i)}function re(w){d.setKey("data",v=>v&&ke(v,w),{action:"update-state"})}if(!I){let w=function(){U("lowPriority")};var oe=w;window.addEventListener("focus",w),window.addEventListener("visibilitychange",w)}return{store:d,awaitFetch:z,scheduleFetch:Q,invalidateData:U,useDocument:W,updateState:re,startMutation:y.startMutation}}import Ge from"mitt";import{useCallback as Ee,useEffect as He,useMemo as Me}from"react";import{deepEqual as Qe,Store as Xe,useSubscribeToStore as Ye}from"t-state";function ce(l){let f=new Map;function P(I){return f.has(I)||f.set(I,ye(l)),f.get(I)}return{get:P}}var Pe=Symbol();function ee(l,f){let P=[],I=0;for(let M of l){let m=f(M,Pe,I);m!==Pe&&P.push(m),I++}return P}function we(l){return typeof l=="object"&&l!==null&&!Array.isArray(l)}function Se(l){return typeof l=="string"?l:JSON.stringify(l&&we(l)?Be(l):l)}function Be(l){return ee(Object.keys(l).sort(),(f,P)=>l[f]===void 0?P:{[f]:l[f]})}function de(l){return JSON.parse(JSON.stringify(l))}function Ze({debugName:l,fetchFn:f,disableRefetchOnWindowFocus:P,lowPriorityThrottleMs:I,errorNormalizer:M,mediumPriorityThrottleMs:m,disableRefetchOnMount:V,dynamicRealtimeThrottleMs:C,getCollectionItemKey:O}){let d=new Xe({debugName:l,state:{}});function E(i){return Se(O?O(i):i)}async function y(i,n){let a=E(n),t=de(n),p=d.state[a];d.produceState(g=>{let S=g[a];if(!S){g[a]={data:null,error:null,status:"loading",payload:t,refetchOnMount:!1,wasLoaded:!1};return}S.status=S.data!==null?"refetching":"loading",S.payload=t,S.error=null,S.refetchOnMount=!1},{equalityCheck:Qe,action:{type:p?.data?"fetch-start-refetching":"fetch-start-loading",payload:t}});try{let g=await f(t);return i.shouldAbort()?!1:(d.produceState(S=>{let b=S[a];!b||(b.data=g,b.status="success",b.wasLoaded=!0)},{action:{type:"fetch-success",payload:t}}),!0)}catch(g){if(i.shouldAbort())return!1;let S=M(g);return d.produceState(b=>{let N=b[a];!N||(N.error=S,N.status="error")},{action:{type:"fetch-error",payload:t,error:S}}),!1}}let Q=ce({fetchFn:y,lowPriorityThrottleMs:I,dynamicRealtimeThrottleMs:C,mediumPriorityThrottleMs:m});function z(i,n){let a=Array.isArray(n),t=a?n:[n],p=[];for(let g of t){let S=E(g);p.push(Q.get(S).scheduleFetch(i,g))}return a?p:p[0]}async function H(i){let n=E(i);if(await Q.get(n).awaitFetch(i))return{data:null,error:M(new Error("Aborted"))};let t=d.state[n];return t?.data?t.error?{data:null,error:t.error}:{data:t.data,error:null}:{data:null,error:M(new Error("Not found"))}}function k(i){let n=d.state;return Array.isArray(i)?i.map(E):typeof i=="function"?ee(Object.entries(n),([a,t],p)=>t&&i(t.payload,t.data)?a:p):[E(i)]}let U=Ge(),W=new Set;function re(i,n="highPriority"){let a=k(i);for(let t of a)d.produceState(p=>{let g=p[t];!g||(g.refetchOnMount=n)},{action:{type:"invalidate-data",itemKey:t}}),W.delete(t),U.emit("invalidateData",{priority:n,itemKey:t})}function oe(i){if(typeof i=="function"||Array.isArray(i)){let n=k(i);return ee(n,(a,t)=>d.state[a]||t)}return d.state[E(i)]}function w(i,{selector:n,omitPayload:a,returnIdleStatus:t,returnRefetchingStatus:p,disableRefetchOnMount:g=V}={}){let S=le(()=>i.map(q=>({itemKey:E(q),payload:q})),[i]),b=Ee(q=>n?n(q):q,[]),N=Ee(q=>S.map(({itemKey:A,payload:Y})=>{let Z=q[A];if(Z===null)return{itemStateKey:A,status:"deleted",data:b(null),error:null,payload:a?void 0:Y,isLoading:!1};if(!Z)return{itemStateKey:A,status:t?"idle":"loading",data:b(null),error:null,payload:a?void 0:Y,isLoading:!t};let ue=Z.status;return!p&&Z.status==="refetching"&&(ue="success"),{itemStateKey:A,status:ue,data:b(Z.data),error:Z.error,isLoading:ue==="loading",payload:a?void 0:Z.payload}}),[b,a,S,t,p]),G=d.useSelector(N,{equalityFn:Qe,useExternalDeps:!0});return te(U,"invalidateData",q=>{for(let{itemKey:A,payload:Y}of S)A===q.itemKey&&(W.has(A)||(z(q.priority,Y),W.add(A)))}),He(()=>{for(let{itemKey:q,payload:A}of S)if(q)if(g){let Y=oe(A);if(!Y?.wasLoaded||Y.refetchOnMount){z(Y?.refetchOnMount||"lowPriority",A);return}}else z("lowPriority",A)},[g,S]),G}function v(i,n={}){let{selector:a,ensureIsLoaded:t}=n,p=Me(()=>i===!1||i===null||i===void 0?[]:[i],[i]),g=w(p,n),S=Me(()=>g[0]??{payload:void 0,data:a?a(null):null,error:null,status:"idle",itemStateKey:"",isLoading:!1},[g]),[b,N]=ae(t,!!i,()=>{i&&z("highPriority",i)});return Ye(d,({observe:G})=>{!t||G.ifSelector(q=>q[S.itemStateKey]?.status).change.then(({current:q})=>{(q==="success"||q==="error")&&N("isLoaded",!0)})}),b(S)}function _(i){let n=k(i),a=[];for(let t of n)a.push(Q.get(t).startMutation());return()=>{for(let t of a)t()}}function B(i,n){let a=E(i);d.produceState(t=>{t[a]={data:n,status:"success",wasLoaded:!0,refetchOnMount:!1,error:null,payload:de(i)}},{action:{type:"create-item-state",payload:i}})}function J(i){let n=k(i);d.produceState(a=>{for(let t of n)a[t]=null},{action:{type:"delete-item-state",payload:i}})}function X(i,n,a){let t=k(i),p=!1;return d.batch(()=>{d.produceState(g=>{for(let S of t){let b=g[S];if(!!b&&b.data){p=!0;let N=n(b.data,b);N&&(b.data=N)}}}),a&&!p&&a()},{type:"update-item-state",item:t}),p}if(!P){let i=function(){re(()=>!0,"lowPriority")};var se=i;window.addEventListener("focus",i),window.addEventListener("visibilitychange",i)}return{store:d,scheduleFetch:z,awaitFetch:H,useMultipleItems:w,useItem:v,getItemKey:E,getItemState:oe,startMutation:_,invalidateItem:re,updateItemState:X,addItemToState:B,deleteItemState:J}}import $e from"mitt";import{useCallback as fe,useEffect as De,useMemo as pe}from"react";import{deepEqual as ge,Store as et,useSubscribeToStore as Le}from"t-state";var me="No fetchItemFn was provided";function tt({debugName:l,fetchListFn:f,fetchItemFn:P,errorNormalizer:I,defaultQuerySize:M=50,disableRefetchOnWindowFocus:m,disableRefetchOnMount:V,lowPriorityThrottleMs:C,mediumPriorityThrottleMs:O,dynamicRealtimeThrottleMs:d,syncMutationsAndInvalidations:E}){let y=new et({debugName:l,state:{items:{},queries:{},itemQueries:{}}});function Q(e){return Se(e)}async function z(e,[o,s,u=M]){let r=de(s),c=Q(r),h=y.state.queries[c],x=!h?.wasLoaded;y.produceState(F=>{let L=F.queries[c];if(!L){F.queries[c]={error:null,status:"loading",wasLoaded:!1,payload:r,refetchOnMount:!1,hasMore:!1,items:[]};return}L.status=L.wasLoaded?o==="loadMore"?"loadingMore":"refetching":"loading",L.error=null,L.refetchOnMount=!1},{equalityCheck:ge,action:{type:x?"fetch-query-start-loading":o==="loadMore"?"fetch-query-loading-more":"refetching-query-start",payload:r}});let K=h?.items.length??0,D=(()=>o==="loadMore"?K+u:x?u:Math.max(K,u))();try{let{items:F,hasMore:L}=await f(r,D);if(e.shouldAbort())return!1;y.produceState(R=>{let T=R.queries[c];if(!!T){T.status="success",T.wasLoaded=!0,T.hasMore=L,T.items=[];for(let{data:$,id:j}of F){R.items[j]=$,T.items.push(String(j));let ne=R.itemQueries[j];(!ne||ne.status!=="loading"&&ne.status!=="refetching")&&(R.itemQueries[j]={error:null,refetchOnMount:!1,status:"success",wasLoaded:!0})}}},{action:{type:"fetch-query-success",payload:r}});for(let{id:R}of F){let T=t?.get(String(R));T&&T.setLastFetchStartTime(e.getStartTime())}return!0}catch(F){if(e.shouldAbort())return!1;let L=I(F);return y.produceState(R=>{let T=R.queries[c];!T||(T.status="error",T.error=L)},{action:{type:"fetch-query-error",payload:r,error:L}}),!1}}function H(e){return y.state.queries[Q(e)]}function k(e){if(typeof e=="string")return y.state.items[e];let o=g(e);return ee(o,(s,u)=>{let r=y.state.items[s];return r?{id:s,data:r}:u})}let U=ce({fetchFn:z,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:d,mediumPriorityThrottleMs:O});function W(e,o,s){let u=Array.isArray(o),c=(u?o:[o]).map(h=>U.get(Q(h)).scheduleFetch(e,["load",h,s]));return u?c:c[0]}function re(e,o){let s=H(e);return!s||!s.hasMore?"skipped":U.get(Q(e)).scheduleFetch("highPriority",["loadMore",e,o])}function oe(e,o){return ee(e.items,(s,u)=>{let r=y.state.items[s];return r?o(r,s):u})}async function w(e,o=M){let s=Q(e);if(await U.get(s).awaitFetch(["load",e,o]))return{items:[],error:I(new Error("Aborted")),hasMore:!1};let r=y.state.queries[s];return r?r.error?{items:[],error:r.error,hasMore:r.hasMore}:{items:oe(r,(c,h)=>({data:c,id:h})),error:null,hasMore:r.hasMore}:{items:[],error:I(new Error("Not found")),hasMore:!1}}async function v(e){if(!t)throw new Error(me);if(await t.get(e).awaitFetch(e))return{data:null,error:I(new Error("Aborted"))};let s=y.state.items[e],u=y.state.itemQueries[e];return!u||!s?{data:null,error:I(new Error("Not found"))}:u.error?{data:null,error:u.error}:{data:s,error:null}}function _(e){return Array.isArray(e)?e.map(o=>({key:Q(o),payload:o})):typeof e=="function"?ee(Object.entries(y.state.queries),([o,s],u)=>e(s.payload,s,o)?{key:o,payload:s.payload}:u):[{key:Q(e),payload:e}]}let B=$e(),J=new Set;function X(e,o="highPriority",s=!1){let u=_(e);for(let{key:r}of u)y.produceState(c=>{let h=c.queries[r];!h||(h.refetchOnMount=o)},{action:{type:"invalidate-data",key:r}}),J.delete(r),B.emit("invalidateQuery",{priority:o,queryKey:r});E&&!s&&(b((r,c)=>u.some(({payload:h})=>E.syncItemAndQuery(c,h)),o,!0),X((r,c,h)=>u.some(x=>h!==x.key&&E.syncQueries(x.payload,r)),o,!0))}function se(e,o){return{id:o,data:e}}function i(e,{itemSelector:o=se,omitPayload:s,returnIdleStatus:u,returnRefetchingStatus:r,loadSize:c,disableRefetchOnMount:h=V}={}){let x=le(()=>e.map(R=>({key:Q(R),payload:R})),[e]),K=fe(o,[]),D=fe(R=>x.map(({key:T,payload:$})=>{let j=R.queries[T];if(!j)return{queryKey:T,status:u?"idle":"loading",items:[],error:null,hasMore:!1,payload:s?void 0:$,isLoading:!u};let ne=j.status;return!r&&j.status==="refetching"&&(ne="success"),{queryKey:T,status:ne,items:oe(j,K),error:j.error,hasMore:j.hasMore,isLoading:ne==="loading",payload:s?void 0:j.payload}}),[K,s,x,u,r]),F=y.useSelector(D,{equalityFn:ge,useExternalDeps:!0});te(B,"invalidateQuery",R=>{for(let{key:T,payload:$}of x)T===R.queryKey&&(J.has(T)||(W(R.priority,$),J.add(T)))});let L=he(()=>c);return De(()=>{for(let{key:R,payload:T}of x)if(R)if(h){let $=H(T);if(!$||!$.wasLoaded||$.refetchOnMount){W($?.refetchOnMount||"lowPriority",T,L);return}}else W("lowPriority",T,L)},[h,L,x]),F}function n(e,o={}){let{ensureIsLoaded:s}=o,u=pe(()=>e===!1||e===null||e===void 0?[]:[e],[e]),r=i(u,o),c=pe(()=>r[0]??{payload:void 0,error:null,hasMore:!1,isLoading:!1,status:"idle",queryKey:"",items:[]},[r]),[h,x]=ae(s,!!e,()=>{e&&W("highPriority",e)});return Le(y,({observe:K})=>{!s||K.ifSelector(D=>D.queries[c.queryKey]?.status).change.then(({current:D})=>{(D==="success"||D==="error")&&x("isLoaded",!0)})}),h(c)}async function a(e,o){if(!t)throw new Error(me);let s=!y.state.itemQueries[o]?.wasLoaded;y.produceState(u=>{let r=u.itemQueries[o];if(!r){u.itemQueries[o]={status:"loading",error:null,wasLoaded:!1,refetchOnMount:!1};return}r.status=r.wasLoaded?"refetching":"loading",r.error=null,r.refetchOnMount=!1},{action:{type:s?"fetch-item-start":"fetch-item-refetch-start",itemId:o}});try{let u=await P(o);return e.shouldAbort()?!1:(y.produceState(r=>{let c=r.itemQueries[o];!c||(c.status="success",c.wasLoaded=!0,r.items[o]=u)},{action:{type:"fetch-item-success",itemId:o}}),!0)}catch(u){if(e.shouldAbort())return!1;let r=I(u);return y.produceState(c=>{let h=c.itemQueries[o];!h||(h.status="error",h.error=r)},{action:{type:"fetch-item-error",itemId:o}}),!1}}let t=P&&ce({fetchFn:a,lowPriorityThrottleMs:C,dynamicRealtimeThrottleMs:d,mediumPriorityThrottleMs:O});function p(e,o){if(!t)throw new Error(me);let s=Array.isArray(o),r=(s?o:[o]).map(c=>t.get(c).scheduleFetch(e,c));return s?r:r[0]}function g(e){return Array.isArray(e)?e:typeof e=="function"?ee(Object.entries(y.state.items),([o,s],u)=>s===null?u:e(s,o)?o:u):[e]}let S=new Set;function b(e,o="highPriority",s=!1){if(!t)throw new Error(me);let u=g(e);for(let r of u)y.produceState(c=>{let h=c.itemQueries[r];!h||(h.refetchOnMount=o)},{action:{type:"invalidate-item",queryKey:r}}),S.delete(r),B.emit("invalidateItem",{priority:o,itemId:r});E&&!s&&X(r=>u.some(c=>E.syncItemAndQuery(c,r)),o,!0)}function N(e){if(!t)throw new Error(me);let o=g(e),s=[];for(let u of o)if(s.push(t.get(u).startMutation()),E)for(let[r,c]of Object.entries(y.state.queries))E.syncItemAndQuery(u,c.payload)&&s.push(U.get(r).startMutation());return()=>{for(let u of s)u()}}function G(e){return e}function q(e,{selector:o=G,returnIdleStatus:s,returnRefetchingStatus:u,disableRefetchOnMount:r}={}){let c=fe(o,[]),h=le(()=>e,[e]),x=fe(D=>h.map(F=>{let L=D.itemQueries[F],R=D.items[F];if(L===null)return{status:"deleted",error:null,isLoading:!1,itemId:F,data:c(null,F)};if(!L)return{status:s?"idle":"loading",error:null,isLoading:!s,itemId:F,data:c(null,F)};let T=L.status;return!u&&L.status==="refetching"&&(T="success"),{status:T,error:L.error,isLoading:T==="loading",data:c(R??null,F),itemId:F}}),[c,h,s,u]),K=y.useSelector(x,{equalityFn:ge,useExternalDeps:!0});return te(B,"invalidateItem",D=>{for(let F of h)F===D.itemId&&(S.has(F)||(p(D.priority,F),S.add(F)))}),De(()=>{for(let D of h)if(D)if(r){let F=y.state.itemQueries[D];if(!F||!F.wasLoaded||F.refetchOnMount){p(F?.refetchOnMount||"lowPriority",D);return}}else p("lowPriority",D)},[r,h]),K}function A(e,o={}){let{ensureIsLoaded:s}=o,u=pe(()=>e===!1||e===null||e===void 0?[]:[e],[e]),r=q(u,o),c=fe(o.selector??G,[]),h=pe(()=>r[0]??{error:null,isLoading:!1,status:"idle",data:c(null,e||""),itemId:e||""},[e,c,r]),[x,K]=ae(s,!!e,()=>{e&&p("highPriority",e)});return Le(y,({observe:D})=>{!s||!e||D.ifSelector(F=>F.itemQueries[e]?.status).change.then(({current:F})=>{(F==="success"||F==="error")&&K("isLoaded",!0)})}),x(h)}function Y(e,o,s){let u=g(e),r=!1;return y.batch(()=>{y.produceState(c=>{for(let h of u){let x=c.items[h];if(!x)continue;r=!0;let K=o(x,h);K&&(c.items[h]=K)}}),s&&!r&&s()},{type:"update-item-state",item:u}),r}function Z(e,o){y.produceState(s=>{s.items[e]=o,s.itemQueries[e]={status:"success",wasLoaded:!0,refetchOnMount:!1,error:null}},{action:{type:"create-item-state",itemId:e}})}function ue(e){let o=g(e);y.produceState(s=>{for(let u of o){s.items[u]=null,s.itemQueries[u]=null;for(let r of Object.values(s.queries))r.items.includes(u)&&(r.items=r.items.filter(c=>c!==u))}},{action:{type:"delete-item-state",itemId:e}})}if(!m){let e=function(){X(()=>!0,"lowPriority"),b(()=>!0,"lowPriority")};var yr=e;window.addEventListener("focus",e),window.addEventListener("visibilitychange",e)}return{store:y,scheduleListQueryFetch:W,getQueryState:H,getQueryKey:Q,deleteItemState:ue,getItemState:k,loadMore:re,invalidateQuery:X,invalidateItem:b,scheduleItemFetch:p,awaitItemFetch:v,awaitListQueryFetch:w,useMultipleListQueries:i,useListQuery:n,useItem:A,useMultipleItems:q,addItemToState:Z,updateItemState:Y,startItemMutation:N}}export{Ze as newTSDFCollectionStore,Je as newTSDFDocumentStore,tt as newTSDFListQueryStore};
|
|
1
|
+
// src/documentStore.ts
|
|
2
|
+
import produce from "immer";
|
|
3
|
+
import mitt2 from "mitt";
|
|
4
|
+
import { useCallback, useEffect as useEffect2 } from "react";
|
|
5
|
+
import { Store, useSubscribeToStore } from "t-state";
|
|
6
|
+
|
|
7
|
+
// src/fetchOrquestrator.ts
|
|
8
|
+
function createFetchOrquestrator({
|
|
9
|
+
fetchFn,
|
|
10
|
+
on,
|
|
11
|
+
mediumPriorityThrottleMs = 10,
|
|
12
|
+
lowPriorityThrottleMs = 200,
|
|
13
|
+
dynamicRealtimeThrottleMs
|
|
14
|
+
}) {
|
|
15
|
+
const fetchs = {
|
|
16
|
+
a: null,
|
|
17
|
+
c: null,
|
|
18
|
+
b: null
|
|
19
|
+
};
|
|
20
|
+
let lastMutationIdStarted = 0;
|
|
21
|
+
let lastFetchIdStarted = 0;
|
|
22
|
+
let mutationIsInProgress = false;
|
|
23
|
+
let lastFetchStartTime = 0;
|
|
24
|
+
let lastFetchDuration = 0;
|
|
25
|
+
let onMutationEnd = [];
|
|
26
|
+
let lastFetchWasAborted = false;
|
|
27
|
+
let abortFetchsBeforeOrEqual = 0;
|
|
28
|
+
function setLastFetchDurantion(duration) {
|
|
29
|
+
lastFetchDuration = duration;
|
|
30
|
+
}
|
|
31
|
+
function setLastFetchStartTime(startTime) {
|
|
32
|
+
lastFetchStartTime = startTime;
|
|
33
|
+
}
|
|
34
|
+
function flushScheduledFetch() {
|
|
35
|
+
if (fetchs.c) {
|
|
36
|
+
on?.("scheduled-fetch-started");
|
|
37
|
+
const params = fetchs.c.params;
|
|
38
|
+
fetchs.c = null;
|
|
39
|
+
startFetch(params, Date.now());
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function startMutation() {
|
|
43
|
+
mutationIsInProgress = true;
|
|
44
|
+
abortFetchsBeforeOrEqual = lastFetchIdStarted;
|
|
45
|
+
fetchs.a = null;
|
|
46
|
+
const id = getAutoIncrementId();
|
|
47
|
+
lastMutationIdStarted = id;
|
|
48
|
+
return () => endMutation(id);
|
|
49
|
+
}
|
|
50
|
+
function endMutation(id) {
|
|
51
|
+
if (id === lastMutationIdStarted) {
|
|
52
|
+
mutationIsInProgress = false;
|
|
53
|
+
if (onMutationEnd.length > 0) {
|
|
54
|
+
onMutationEnd.forEach((cb) => cb());
|
|
55
|
+
onMutationEnd = [];
|
|
56
|
+
}
|
|
57
|
+
flushScheduledFetch();
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
function getFetchs() {
|
|
63
|
+
return fetchs;
|
|
64
|
+
}
|
|
65
|
+
async function startFetch(params, startTime) {
|
|
66
|
+
if (fetchs.a) {
|
|
67
|
+
throw new Error("[tsdf] Fetch already in progress");
|
|
68
|
+
}
|
|
69
|
+
const id = getAutoIncrementId();
|
|
70
|
+
lastFetchIdStarted = id;
|
|
71
|
+
lastFetchWasAborted = false;
|
|
72
|
+
fetchs.a = { startTime, onEnd: [] };
|
|
73
|
+
const prevFetchStartTime = lastFetchStartTime;
|
|
74
|
+
lastFetchStartTime = startTime;
|
|
75
|
+
function shouldAbort() {
|
|
76
|
+
const abort = id !== lastFetchIdStarted || mutationIsInProgress || id <= abortFetchsBeforeOrEqual;
|
|
77
|
+
lastFetchWasAborted = abort;
|
|
78
|
+
return abort;
|
|
79
|
+
}
|
|
80
|
+
const success = await fetchFn(
|
|
81
|
+
{
|
|
82
|
+
shouldAbort,
|
|
83
|
+
getStartTime: () => startTime
|
|
84
|
+
},
|
|
85
|
+
params
|
|
86
|
+
);
|
|
87
|
+
const currentFetchs = getFetchs();
|
|
88
|
+
if (!currentFetchs.a) {
|
|
89
|
+
lastFetchStartTime = prevFetchStartTime;
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
if (success) {
|
|
93
|
+
lastFetchDuration = Date.now() - startTime;
|
|
94
|
+
}
|
|
95
|
+
if (currentFetchs.b) {
|
|
96
|
+
clearTimeout(currentFetchs.b.timeoutId);
|
|
97
|
+
fetchs.b = null;
|
|
98
|
+
}
|
|
99
|
+
const onEnd = currentFetchs.a.onEnd;
|
|
100
|
+
currentFetchs.a = null;
|
|
101
|
+
if (onEnd.length > 0) {
|
|
102
|
+
onEnd.forEach((cb) => cb());
|
|
103
|
+
}
|
|
104
|
+
flushScheduledFetch();
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
function scheduleFetch(fetchType, params) {
|
|
108
|
+
const startTime = Date.now();
|
|
109
|
+
if (dynamicRealtimeThrottleMs && fetchType === "realtimeUpdate") {
|
|
110
|
+
if (scheduleRTU(startTime, params)) {
|
|
111
|
+
return "rt-scheduled";
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (shouldSkipFetch(fetchType, startTime)) {
|
|
115
|
+
return "skipped";
|
|
116
|
+
}
|
|
117
|
+
if (shouldScheduleFetch(fetchType, params)) {
|
|
118
|
+
return "scheduled";
|
|
119
|
+
}
|
|
120
|
+
startFetch(params, startTime);
|
|
121
|
+
return "started";
|
|
122
|
+
}
|
|
123
|
+
function shouldSkipFetch(fetchType, startTime) {
|
|
124
|
+
if (fetchType === "highPriority") {
|
|
125
|
+
if (fetchs.a) {
|
|
126
|
+
const timeSinceLastFetch = startTime - fetchs.a.startTime;
|
|
127
|
+
if (timeSinceLastFetch < mediumPriorityThrottleMs) {
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (fetchType === "lowPriority") {
|
|
133
|
+
if (fetchs.a || fetchs.c || mutationIsInProgress) {
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
if (lastFetchStartTime) {
|
|
137
|
+
const timeSinceLastFetch = startTime - lastFetchStartTime;
|
|
138
|
+
if (timeSinceLastFetch < lowPriorityThrottleMs) {
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
function shouldScheduleFetch(priority, params) {
|
|
146
|
+
const shouldSchedule = (() => {
|
|
147
|
+
if (priority === "lowPriority") {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
return !!fetchs.a || !!mutationIsInProgress;
|
|
151
|
+
})();
|
|
152
|
+
if (shouldSchedule) {
|
|
153
|
+
fetchs.c = { params };
|
|
154
|
+
}
|
|
155
|
+
return shouldSchedule;
|
|
156
|
+
}
|
|
157
|
+
function addDelayedRTU(startTime, params) {
|
|
158
|
+
if (!dynamicRealtimeThrottleMs)
|
|
159
|
+
return false;
|
|
160
|
+
const timeSinceLastFetch = startTime - (lastFetchStartTime + lastFetchDuration);
|
|
161
|
+
const minimumRealtimeInterval = dynamicRealtimeThrottleMs(lastFetchDuration);
|
|
162
|
+
if (timeSinceLastFetch >= minimumRealtimeInterval)
|
|
163
|
+
return false;
|
|
164
|
+
const delay = minimumRealtimeInterval - timeSinceLastFetch;
|
|
165
|
+
fetchs.b = {
|
|
166
|
+
timeoutId: window.setTimeout(() => {
|
|
167
|
+
fetchs.b = null;
|
|
168
|
+
on?.("scheduled-rt-fetch-started");
|
|
169
|
+
startFetch(params, Date.now());
|
|
170
|
+
}, delay)
|
|
171
|
+
};
|
|
172
|
+
return true;
|
|
173
|
+
}
|
|
174
|
+
function scheduleRTU(startTime, params) {
|
|
175
|
+
if (!lastFetchDuration || !lastFetchStartTime || !dynamicRealtimeThrottleMs) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (fetchs.b) {
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
if (fetchs.a) {
|
|
182
|
+
fetchs.a.onEnd.push(() => {
|
|
183
|
+
addDelayedRTU(Date.now(), params);
|
|
184
|
+
});
|
|
185
|
+
return true;
|
|
186
|
+
} else if (mutationIsInProgress) {
|
|
187
|
+
onMutationEnd.push(() => {
|
|
188
|
+
const added = addDelayedRTU(Date.now(), params);
|
|
189
|
+
if (!added) {
|
|
190
|
+
on?.("scheduled-rt-fetch-started");
|
|
191
|
+
scheduleFetch("highPriority", params);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
return true;
|
|
195
|
+
} else {
|
|
196
|
+
if (!addDelayedRTU(startTime, params)) {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
function addOnFetchEnd(cb) {
|
|
203
|
+
if (fetchs.a) {
|
|
204
|
+
fetchs.a.onEnd.push(cb);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async function awaitFetch(params) {
|
|
208
|
+
scheduleFetch("highPriority", params);
|
|
209
|
+
if (fetchs.a) {
|
|
210
|
+
await new Promise((resolve) => {
|
|
211
|
+
addOnFetchEnd(() => resolve(true));
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return lastFetchWasAborted;
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
scheduleFetch,
|
|
218
|
+
awaitFetch,
|
|
219
|
+
startMutation,
|
|
220
|
+
get hasPendingFetch() {
|
|
221
|
+
return !!fetchs.a || !!fetchs.c || !!fetchs.b;
|
|
222
|
+
},
|
|
223
|
+
get fetchIsInProgress() {
|
|
224
|
+
return !!fetchs.a;
|
|
225
|
+
},
|
|
226
|
+
get mutationIsInProgress() {
|
|
227
|
+
return mutationIsInProgress;
|
|
228
|
+
},
|
|
229
|
+
setLastFetchDurantion,
|
|
230
|
+
setLastFetchStartTime
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
var autoIncrementId = 0;
|
|
234
|
+
function getAutoIncrementId() {
|
|
235
|
+
return ++autoIncrementId;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/useEnsureIsLoaded.ts
|
|
239
|
+
import mitt from "mitt";
|
|
240
|
+
import { useMemo as useMemo2, useState } from "react";
|
|
241
|
+
|
|
242
|
+
// src/utils/hooks.ts
|
|
243
|
+
import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
|
|
244
|
+
import { deepEqual, shallowEqual } from "t-state";
|
|
245
|
+
function useDeepCompareMemoize(value, equalityFn = deepEqual) {
|
|
246
|
+
const ref = useRef();
|
|
247
|
+
const signalRef = useRef(0);
|
|
248
|
+
if (!equalityFn(value, ref.current)) {
|
|
249
|
+
ref.current = value;
|
|
250
|
+
signalRef.current += 1;
|
|
251
|
+
}
|
|
252
|
+
return [signalRef.current];
|
|
253
|
+
}
|
|
254
|
+
function useDeepMemo(callback, deeps) {
|
|
255
|
+
return useMemo(callback, useDeepCompareMemoize(deeps));
|
|
256
|
+
}
|
|
257
|
+
function useLatestValue(value) {
|
|
258
|
+
const ref = useRef({ insideEffect: value, insideMemo: value });
|
|
259
|
+
ref.current.insideMemo = value;
|
|
260
|
+
useLayoutEffect(() => {
|
|
261
|
+
ref.current.insideEffect = value;
|
|
262
|
+
});
|
|
263
|
+
return ref.current;
|
|
264
|
+
}
|
|
265
|
+
function useOnMittEvent(mitt5, event, callback) {
|
|
266
|
+
const latestCallback = useLatestValue(callback);
|
|
267
|
+
useLayoutEffect(() => {
|
|
268
|
+
const cb = (payload) => {
|
|
269
|
+
latestCallback.insideEffect(payload);
|
|
270
|
+
};
|
|
271
|
+
mitt5.on(event, cb);
|
|
272
|
+
return () => {
|
|
273
|
+
mitt5.off(event, cb);
|
|
274
|
+
};
|
|
275
|
+
}, [mitt5, event, latestCallback]);
|
|
276
|
+
}
|
|
277
|
+
function usePrevious(value, initial) {
|
|
278
|
+
const ref = useRef(initial);
|
|
279
|
+
useEffect(() => {
|
|
280
|
+
ref.current = value;
|
|
281
|
+
});
|
|
282
|
+
return ref.current;
|
|
283
|
+
}
|
|
284
|
+
function useOnChange(value, callBack, {
|
|
285
|
+
equalityFn: areEqual = shallowEqual,
|
|
286
|
+
callOnMount,
|
|
287
|
+
layoutEffect
|
|
288
|
+
} = {}) {
|
|
289
|
+
const useEffectFn = layoutEffect ? useLayoutEffect : useEffect;
|
|
290
|
+
const prev = usePrevious(value, !callOnMount ? value : void 0);
|
|
291
|
+
useEffectFn(() => {
|
|
292
|
+
if (!areEqual(value, prev)) {
|
|
293
|
+
return callBack({ prev, current: value });
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
function useConst(getValue) {
|
|
298
|
+
const store = useRef();
|
|
299
|
+
if (store.current === void 0) {
|
|
300
|
+
store.current = getValue();
|
|
301
|
+
}
|
|
302
|
+
return store.current;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// src/useEnsureIsLoaded.ts
|
|
306
|
+
function useEnsureIsLoaded(ensureIsLoaded, enabled, forceFetch) {
|
|
307
|
+
const isLoadedEvtEmitter = useConst(() => mitt());
|
|
308
|
+
const [isForceLoading, setIsForceLoading] = useState(true);
|
|
309
|
+
useOnChange(
|
|
310
|
+
ensureIsLoaded && isForceLoading && enabled,
|
|
311
|
+
({ current }) => {
|
|
312
|
+
if (current) {
|
|
313
|
+
forceFetch();
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
{ callOnMount: true }
|
|
317
|
+
);
|
|
318
|
+
useOnMittEvent(isLoadedEvtEmitter, "isLoaded", (isLoaded) => {
|
|
319
|
+
if (ensureIsLoaded && enabled && isLoaded) {
|
|
320
|
+
setIsForceLoading(false);
|
|
321
|
+
}
|
|
322
|
+
});
|
|
323
|
+
function useModifyResult(result) {
|
|
324
|
+
return useMemo2(() => {
|
|
325
|
+
if (ensureIsLoaded) {
|
|
326
|
+
const newStatus = enabled && isForceLoading ? "loading" : result.status;
|
|
327
|
+
return {
|
|
328
|
+
...result,
|
|
329
|
+
isLoading: newStatus === "loading",
|
|
330
|
+
status: newStatus
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
return result;
|
|
334
|
+
}, [ensureIsLoaded, isForceLoading, result]);
|
|
335
|
+
}
|
|
336
|
+
return [useModifyResult, isLoadedEvtEmitter.emit];
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/documentStore.ts
|
|
340
|
+
function newTSDFDocumentStore({
|
|
341
|
+
debugName,
|
|
342
|
+
fetchFn,
|
|
343
|
+
initialData,
|
|
344
|
+
disableRefetchOnWindowFocus,
|
|
345
|
+
disableRefetchOnMount: globalDisableRefetchOnMount,
|
|
346
|
+
lowPriorityThrottleMs,
|
|
347
|
+
mediumPriorityThrottleMs,
|
|
348
|
+
dynamicRealtimeThrottleMs,
|
|
349
|
+
errorNormalizer
|
|
350
|
+
}) {
|
|
351
|
+
const store = new Store({
|
|
352
|
+
debugName,
|
|
353
|
+
state: {
|
|
354
|
+
data: initialData ?? null,
|
|
355
|
+
error: null,
|
|
356
|
+
status: initialData ? "success" : "idle",
|
|
357
|
+
refetchOnMount: false
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
async function fetch(fetchCtx, _) {
|
|
361
|
+
store.setPartialState(
|
|
362
|
+
{
|
|
363
|
+
status: store.state.status === "success" ? "refetching" : "loading",
|
|
364
|
+
error: null,
|
|
365
|
+
refetchOnMount: false
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
action: store.state.status === "success" ? "fetch-start-refetching" : "fetch-start-loading"
|
|
369
|
+
}
|
|
370
|
+
);
|
|
371
|
+
try {
|
|
372
|
+
const data = await fetchFn();
|
|
373
|
+
if (fetchCtx.shouldAbort())
|
|
374
|
+
return false;
|
|
375
|
+
store.setPartialState(
|
|
376
|
+
{
|
|
377
|
+
data,
|
|
378
|
+
status: "success"
|
|
379
|
+
},
|
|
380
|
+
{ action: "fetch-success" }
|
|
381
|
+
);
|
|
382
|
+
return true;
|
|
383
|
+
} catch (exception) {
|
|
384
|
+
if (fetchCtx.shouldAbort())
|
|
385
|
+
return false;
|
|
386
|
+
store.setPartialState(
|
|
387
|
+
{
|
|
388
|
+
error: errorNormalizer(exception),
|
|
389
|
+
status: "error"
|
|
390
|
+
},
|
|
391
|
+
{ action: "fetch-error" }
|
|
392
|
+
);
|
|
393
|
+
return false;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
const fetchOrquestrator = createFetchOrquestrator({
|
|
397
|
+
fetchFn: fetch,
|
|
398
|
+
lowPriorityThrottleMs,
|
|
399
|
+
dynamicRealtimeThrottleMs,
|
|
400
|
+
mediumPriorityThrottleMs
|
|
401
|
+
});
|
|
402
|
+
function scheduleFetch(fetchType) {
|
|
403
|
+
return fetchOrquestrator.scheduleFetch(fetchType, null);
|
|
404
|
+
}
|
|
405
|
+
async function awaitFetch() {
|
|
406
|
+
const wasAborted = await fetchOrquestrator.awaitFetch(null);
|
|
407
|
+
if (wasAborted) {
|
|
408
|
+
return { data: null, error: errorNormalizer(new Error("Aborted")) };
|
|
409
|
+
}
|
|
410
|
+
if (!store.state.data) {
|
|
411
|
+
return { data: null, error: errorNormalizer(new Error("No data")) };
|
|
412
|
+
}
|
|
413
|
+
return store.state.error ? { data: null, error: store.state.error } : { data: store.state.data, error: null };
|
|
414
|
+
}
|
|
415
|
+
const storeEvents = mitt2();
|
|
416
|
+
let invalidationWasTriggered = false;
|
|
417
|
+
function invalidateData(priority = "highPriority") {
|
|
418
|
+
store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
|
|
419
|
+
invalidationWasTriggered = false;
|
|
420
|
+
storeEvents.emit("invalidateData", priority);
|
|
421
|
+
}
|
|
422
|
+
function useDocument({
|
|
423
|
+
selector,
|
|
424
|
+
disabled,
|
|
425
|
+
returnRefetchingStatus,
|
|
426
|
+
disableRefetchOnMount = globalDisableRefetchOnMount,
|
|
427
|
+
returnIdleStatus = !!disabled,
|
|
428
|
+
ensureIsLoaded
|
|
429
|
+
} = {}) {
|
|
430
|
+
const storeStateSelector = useCallback(
|
|
431
|
+
(state) => {
|
|
432
|
+
const { error } = state;
|
|
433
|
+
const data = selector ? selector(state.data) : state.data;
|
|
434
|
+
let status = state.status;
|
|
435
|
+
if (!returnIdleStatus && status === "idle") {
|
|
436
|
+
status = "loading";
|
|
437
|
+
}
|
|
438
|
+
if (!returnRefetchingStatus && status === "refetching") {
|
|
439
|
+
status = "success";
|
|
440
|
+
}
|
|
441
|
+
return {
|
|
442
|
+
data,
|
|
443
|
+
error,
|
|
444
|
+
status,
|
|
445
|
+
isLoading: status === "loading"
|
|
446
|
+
};
|
|
447
|
+
},
|
|
448
|
+
[returnRefetchingStatus, returnIdleStatus, selector]
|
|
449
|
+
);
|
|
450
|
+
const storeState = store.useSelector(storeStateSelector, {
|
|
451
|
+
useExternalDeps: true
|
|
452
|
+
});
|
|
453
|
+
useOnMittEvent(storeEvents, "invalidateData", (priority) => {
|
|
454
|
+
if (!invalidationWasTriggered) {
|
|
455
|
+
scheduleFetch(priority);
|
|
456
|
+
invalidationWasTriggered = true;
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
useEffect2(() => {
|
|
460
|
+
if (disabled)
|
|
461
|
+
return;
|
|
462
|
+
if (disableRefetchOnMount) {
|
|
463
|
+
const shouldFetch = store.state.refetchOnMount || store.state.status === "idle";
|
|
464
|
+
if (shouldFetch) {
|
|
465
|
+
scheduleFetch(store.state.refetchOnMount || "lowPriority");
|
|
466
|
+
}
|
|
467
|
+
} else {
|
|
468
|
+
scheduleFetch("lowPriority");
|
|
469
|
+
}
|
|
470
|
+
}, [disableRefetchOnMount, disabled]);
|
|
471
|
+
const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
|
|
472
|
+
ensureIsLoaded,
|
|
473
|
+
!disabled,
|
|
474
|
+
() => {
|
|
475
|
+
scheduleFetch("highPriority");
|
|
476
|
+
}
|
|
477
|
+
);
|
|
478
|
+
useSubscribeToStore(store, ({ observe }) => {
|
|
479
|
+
observe.ifSelector((state) => state.status).change.then(({ current }) => {
|
|
480
|
+
if (current === "success" || current === "error") {
|
|
481
|
+
emitIsLoadedEvt("isLoaded", true);
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
});
|
|
485
|
+
return useModifyResult(storeState);
|
|
486
|
+
}
|
|
487
|
+
function updateState(produceNewData) {
|
|
488
|
+
store.setKey(
|
|
489
|
+
"data",
|
|
490
|
+
(current) => {
|
|
491
|
+
if (!current)
|
|
492
|
+
return current;
|
|
493
|
+
return produce(current, produceNewData);
|
|
494
|
+
},
|
|
495
|
+
{ action: "update-state" }
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
if (!disableRefetchOnWindowFocus) {
|
|
499
|
+
let handleFocus2 = function() {
|
|
500
|
+
invalidateData("lowPriority");
|
|
501
|
+
};
|
|
502
|
+
var handleFocus = handleFocus2;
|
|
503
|
+
window.addEventListener("focus", handleFocus2);
|
|
504
|
+
window.addEventListener("visibilitychange", handleFocus2);
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
store,
|
|
508
|
+
awaitFetch,
|
|
509
|
+
scheduleFetch,
|
|
510
|
+
invalidateData,
|
|
511
|
+
useDocument,
|
|
512
|
+
updateState,
|
|
513
|
+
startMutation: fetchOrquestrator.startMutation
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// src/collectionStore.ts
|
|
518
|
+
import mitt3 from "mitt";
|
|
519
|
+
import { useCallback as useCallback2, useEffect as useEffect3, useMemo as useMemo3 } from "react";
|
|
520
|
+
import { deepEqual as deepEqual2, Store as Store2, useSubscribeToStore as useSubscribeToStore2 } from "t-state";
|
|
521
|
+
|
|
522
|
+
// src/collectionFetchOrquestrator.ts
|
|
523
|
+
function createCollectionFetchOrquestrator(props) {
|
|
524
|
+
const fetchOrquestrators = /* @__PURE__ */ new Map();
|
|
525
|
+
function getFetchOrquestrator(key) {
|
|
526
|
+
if (!fetchOrquestrators.has(key)) {
|
|
527
|
+
fetchOrquestrators.set(key, createFetchOrquestrator(props));
|
|
528
|
+
}
|
|
529
|
+
return fetchOrquestrators.get(key);
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
get: getFetchOrquestrator
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// src/utils/filterAndMap.ts
|
|
537
|
+
var ignore = Symbol();
|
|
538
|
+
function filterAndMap(arr, fn) {
|
|
539
|
+
const result = [];
|
|
540
|
+
let i = 0;
|
|
541
|
+
for (const item of arr) {
|
|
542
|
+
const mappedItem = fn(item, ignore, i);
|
|
543
|
+
if (mappedItem !== ignore) {
|
|
544
|
+
result.push(mappedItem);
|
|
545
|
+
}
|
|
546
|
+
i++;
|
|
547
|
+
}
|
|
548
|
+
return result;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// src/utils/isObject.ts
|
|
552
|
+
function isObject(value) {
|
|
553
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// src/utils/getCacheId.ts
|
|
557
|
+
function getCacheId(input) {
|
|
558
|
+
return typeof input === "string" ? input : JSON.stringify(input && isObject(input) ? orderedProps(input) : input);
|
|
559
|
+
}
|
|
560
|
+
function orderedProps(obj) {
|
|
561
|
+
return filterAndMap(Object.keys(obj).sort(), (k, ignore2) => {
|
|
562
|
+
const value = obj[k];
|
|
563
|
+
if (value === void 0)
|
|
564
|
+
return ignore2;
|
|
565
|
+
return { [k]: obj[k] };
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// src/utils/serializableClone.ts
|
|
570
|
+
function serializableClone(input) {
|
|
571
|
+
return JSON.parse(JSON.stringify(input));
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// src/collectionStore.ts
|
|
575
|
+
function newTSDFCollectionStore({
|
|
576
|
+
debugName,
|
|
577
|
+
fetchFn,
|
|
578
|
+
disableRefetchOnWindowFocus,
|
|
579
|
+
lowPriorityThrottleMs,
|
|
580
|
+
errorNormalizer,
|
|
581
|
+
mediumPriorityThrottleMs,
|
|
582
|
+
disableRefetchOnMount: globalDisableRefetchOnMount,
|
|
583
|
+
dynamicRealtimeThrottleMs,
|
|
584
|
+
getCollectionItemKey: filterCollectionItemObjKey
|
|
585
|
+
}) {
|
|
586
|
+
const store = new Store2({
|
|
587
|
+
debugName,
|
|
588
|
+
state: {}
|
|
589
|
+
});
|
|
590
|
+
function getItemKey(params) {
|
|
591
|
+
return getCacheId(
|
|
592
|
+
filterCollectionItemObjKey ? filterCollectionItemObjKey(params) : params
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
async function fetch(fetchCtx, itemPayload) {
|
|
596
|
+
const itemId = getItemKey(itemPayload);
|
|
597
|
+
const payload = serializableClone(itemPayload);
|
|
598
|
+
const itemState = store.state[itemId];
|
|
599
|
+
store.produceState(
|
|
600
|
+
(draft) => {
|
|
601
|
+
const item = draft[itemId];
|
|
602
|
+
if (!item) {
|
|
603
|
+
draft[itemId] = {
|
|
604
|
+
data: null,
|
|
605
|
+
error: null,
|
|
606
|
+
status: "loading",
|
|
607
|
+
payload,
|
|
608
|
+
refetchOnMount: false,
|
|
609
|
+
wasLoaded: false
|
|
610
|
+
};
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
item.status = item.data !== null ? "refetching" : "loading";
|
|
614
|
+
item.payload = payload;
|
|
615
|
+
item.error = null;
|
|
616
|
+
item.refetchOnMount = false;
|
|
617
|
+
},
|
|
618
|
+
{
|
|
619
|
+
equalityCheck: deepEqual2,
|
|
620
|
+
action: {
|
|
621
|
+
type: !itemState?.data ? "fetch-start-loading" : "fetch-start-refetching",
|
|
622
|
+
payload
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
);
|
|
626
|
+
try {
|
|
627
|
+
const data = await fetchFn(payload);
|
|
628
|
+
if (fetchCtx.shouldAbort())
|
|
629
|
+
return false;
|
|
630
|
+
store.produceState(
|
|
631
|
+
(draft) => {
|
|
632
|
+
const item = draft[itemId];
|
|
633
|
+
if (!item)
|
|
634
|
+
return;
|
|
635
|
+
item.data = data;
|
|
636
|
+
item.status = "success";
|
|
637
|
+
item.wasLoaded = true;
|
|
638
|
+
},
|
|
639
|
+
{ action: { type: "fetch-success", payload } }
|
|
640
|
+
);
|
|
641
|
+
return true;
|
|
642
|
+
} catch (exception) {
|
|
643
|
+
if (fetchCtx.shouldAbort())
|
|
644
|
+
return false;
|
|
645
|
+
const error = errorNormalizer(exception);
|
|
646
|
+
store.produceState(
|
|
647
|
+
(draft) => {
|
|
648
|
+
const item = draft[itemId];
|
|
649
|
+
if (!item)
|
|
650
|
+
return;
|
|
651
|
+
item.error = error;
|
|
652
|
+
item.status = "error";
|
|
653
|
+
},
|
|
654
|
+
{ action: { type: "fetch-error", payload, error } }
|
|
655
|
+
);
|
|
656
|
+
return false;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const fetchOrquestrator = createCollectionFetchOrquestrator({
|
|
660
|
+
fetchFn: fetch,
|
|
661
|
+
lowPriorityThrottleMs,
|
|
662
|
+
dynamicRealtimeThrottleMs,
|
|
663
|
+
mediumPriorityThrottleMs
|
|
664
|
+
});
|
|
665
|
+
function scheduleFetch(fetchType, payload) {
|
|
666
|
+
const multiplePayloads = Array.isArray(payload);
|
|
667
|
+
const payloads = multiplePayloads ? payload : [payload];
|
|
668
|
+
const results = [];
|
|
669
|
+
for (const param of payloads) {
|
|
670
|
+
const itemKey = getItemKey(param);
|
|
671
|
+
results.push(
|
|
672
|
+
fetchOrquestrator.get(itemKey).scheduleFetch(fetchType, param)
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
return multiplePayloads ? results : results[0];
|
|
676
|
+
}
|
|
677
|
+
async function awaitFetch(params) {
|
|
678
|
+
const itemId = getItemKey(params);
|
|
679
|
+
const wasAborted = await fetchOrquestrator.get(itemId).awaitFetch(params);
|
|
680
|
+
if (wasAborted) {
|
|
681
|
+
return { data: null, error: errorNormalizer(new Error("Aborted")) };
|
|
682
|
+
}
|
|
683
|
+
const item = store.state[itemId];
|
|
684
|
+
if (!item?.data) {
|
|
685
|
+
return { data: null, error: errorNormalizer(new Error("Not found")) };
|
|
686
|
+
}
|
|
687
|
+
return item.error ? { data: null, error: item.error } : { data: item.data, error: null };
|
|
688
|
+
}
|
|
689
|
+
function getItemsKeyArray(params) {
|
|
690
|
+
const items = store.state;
|
|
691
|
+
if (Array.isArray(params)) {
|
|
692
|
+
return params.map(getItemKey);
|
|
693
|
+
} else if (typeof params === "function") {
|
|
694
|
+
return filterAndMap(Object.entries(items), ([itemKey, item], ignore2) => {
|
|
695
|
+
return item && params(item.payload, item.data) ? itemKey : ignore2;
|
|
696
|
+
});
|
|
697
|
+
} else {
|
|
698
|
+
return [getItemKey(params)];
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const storeEvents = mitt3();
|
|
702
|
+
const invalidationWasTriggered = /* @__PURE__ */ new Set();
|
|
703
|
+
function invalidateItem(itemPayload, priority = "highPriority") {
|
|
704
|
+
const itemsKey = getItemsKeyArray(itemPayload);
|
|
705
|
+
for (const itemKey of itemsKey) {
|
|
706
|
+
store.produceState(
|
|
707
|
+
(draft) => {
|
|
708
|
+
const item = draft[itemKey];
|
|
709
|
+
if (!item)
|
|
710
|
+
return;
|
|
711
|
+
item.refetchOnMount = priority;
|
|
712
|
+
},
|
|
713
|
+
{ action: { type: "invalidate-data", itemKey } }
|
|
714
|
+
);
|
|
715
|
+
invalidationWasTriggered.delete(itemKey);
|
|
716
|
+
storeEvents.emit("invalidateData", { priority, itemKey });
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
function getItemState(params) {
|
|
720
|
+
if (typeof params === "function" || Array.isArray(params)) {
|
|
721
|
+
const itemsId = getItemsKeyArray(params);
|
|
722
|
+
return filterAndMap(itemsId, (itemId, ignore2) => {
|
|
723
|
+
return store.state[itemId] || ignore2;
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
return store.state[getItemKey(params)];
|
|
727
|
+
}
|
|
728
|
+
function useMultipleItems(queries, {
|
|
729
|
+
selector,
|
|
730
|
+
omitPayload,
|
|
731
|
+
returnIdleStatus,
|
|
732
|
+
returnRefetchingStatus,
|
|
733
|
+
disableRefetchOnMount = globalDisableRefetchOnMount
|
|
734
|
+
} = {}) {
|
|
735
|
+
const queriesWithId = useDeepMemo(() => {
|
|
736
|
+
return queries.map((payload) => {
|
|
737
|
+
return { itemKey: getItemKey(payload), payload };
|
|
738
|
+
});
|
|
739
|
+
}, [queries]);
|
|
740
|
+
const dataSelector = useCallback2((itemState) => {
|
|
741
|
+
if (selector)
|
|
742
|
+
return selector(itemState);
|
|
743
|
+
return itemState;
|
|
744
|
+
}, []);
|
|
745
|
+
const resultSelector = useCallback2(
|
|
746
|
+
(state) => {
|
|
747
|
+
return queriesWithId.map(
|
|
748
|
+
({
|
|
749
|
+
itemKey,
|
|
750
|
+
payload
|
|
751
|
+
}) => {
|
|
752
|
+
const item = state[itemKey];
|
|
753
|
+
if (item === null) {
|
|
754
|
+
return {
|
|
755
|
+
itemStateKey: itemKey,
|
|
756
|
+
status: "deleted",
|
|
757
|
+
data: dataSelector(null),
|
|
758
|
+
error: null,
|
|
759
|
+
payload: omitPayload ? void 0 : payload,
|
|
760
|
+
isLoading: false
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
if (!item) {
|
|
764
|
+
return {
|
|
765
|
+
itemStateKey: itemKey,
|
|
766
|
+
status: returnIdleStatus ? "idle" : "loading",
|
|
767
|
+
data: dataSelector(null),
|
|
768
|
+
error: null,
|
|
769
|
+
payload: omitPayload ? void 0 : payload,
|
|
770
|
+
isLoading: returnIdleStatus ? false : true
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
let status = item.status;
|
|
774
|
+
if (!returnRefetchingStatus && item.status === "refetching") {
|
|
775
|
+
status = "success";
|
|
776
|
+
}
|
|
777
|
+
return {
|
|
778
|
+
itemStateKey: itemKey,
|
|
779
|
+
status,
|
|
780
|
+
data: dataSelector(item.data),
|
|
781
|
+
error: item.error,
|
|
782
|
+
isLoading: status === "loading",
|
|
783
|
+
payload: omitPayload ? void 0 : item.payload
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
);
|
|
787
|
+
},
|
|
788
|
+
[
|
|
789
|
+
dataSelector,
|
|
790
|
+
omitPayload,
|
|
791
|
+
queriesWithId,
|
|
792
|
+
returnIdleStatus,
|
|
793
|
+
returnRefetchingStatus
|
|
794
|
+
]
|
|
795
|
+
);
|
|
796
|
+
const storeState = store.useSelector(resultSelector, {
|
|
797
|
+
equalityFn: deepEqual2,
|
|
798
|
+
useExternalDeps: true
|
|
799
|
+
});
|
|
800
|
+
useOnMittEvent(storeEvents, "invalidateData", (event) => {
|
|
801
|
+
for (const { itemKey, payload } of queriesWithId) {
|
|
802
|
+
if (itemKey !== event.itemKey)
|
|
803
|
+
continue;
|
|
804
|
+
if (!invalidationWasTriggered.has(itemKey)) {
|
|
805
|
+
scheduleFetch(event.priority, payload);
|
|
806
|
+
invalidationWasTriggered.add(itemKey);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
useEffect3(() => {
|
|
811
|
+
for (const { itemKey: itemId, payload } of queriesWithId) {
|
|
812
|
+
if (itemId) {
|
|
813
|
+
if (disableRefetchOnMount) {
|
|
814
|
+
const itemState = getItemState(payload);
|
|
815
|
+
const shouldFetch = !itemState?.wasLoaded || itemState.refetchOnMount;
|
|
816
|
+
if (shouldFetch) {
|
|
817
|
+
scheduleFetch(
|
|
818
|
+
itemState?.refetchOnMount || "lowPriority",
|
|
819
|
+
payload
|
|
820
|
+
);
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
} else {
|
|
824
|
+
scheduleFetch("lowPriority", payload);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}, [disableRefetchOnMount, queriesWithId]);
|
|
829
|
+
return storeState;
|
|
830
|
+
}
|
|
831
|
+
function useItem(payload, options = {}) {
|
|
832
|
+
const { selector, ensureIsLoaded } = options;
|
|
833
|
+
const query = useMemo3(
|
|
834
|
+
() => payload === false || payload === null || payload === void 0 ? [] : [payload],
|
|
835
|
+
[payload]
|
|
836
|
+
);
|
|
837
|
+
const item = useMultipleItems(query, options);
|
|
838
|
+
const result = useMemo3(
|
|
839
|
+
() => item[0] ?? {
|
|
840
|
+
payload: void 0,
|
|
841
|
+
data: selector ? selector(null) : null,
|
|
842
|
+
error: null,
|
|
843
|
+
status: "idle",
|
|
844
|
+
itemStateKey: "",
|
|
845
|
+
isLoading: false
|
|
846
|
+
},
|
|
847
|
+
[item]
|
|
848
|
+
);
|
|
849
|
+
const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
|
|
850
|
+
ensureIsLoaded,
|
|
851
|
+
!!payload,
|
|
852
|
+
() => {
|
|
853
|
+
if (payload) {
|
|
854
|
+
scheduleFetch("highPriority", payload);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
);
|
|
858
|
+
useSubscribeToStore2(store, ({ observe }) => {
|
|
859
|
+
if (!ensureIsLoaded)
|
|
860
|
+
return;
|
|
861
|
+
observe.ifSelector((state) => state[result.itemStateKey]?.status).change.then(({ current }) => {
|
|
862
|
+
if (current === "success" || current === "error") {
|
|
863
|
+
emitIsLoadedEvt("isLoaded", true);
|
|
864
|
+
}
|
|
865
|
+
});
|
|
866
|
+
});
|
|
867
|
+
return useModifyResult(result);
|
|
868
|
+
}
|
|
869
|
+
function startMutation(fetchParams) {
|
|
870
|
+
const itemKeys = getItemsKeyArray(fetchParams);
|
|
871
|
+
const endMutations = [];
|
|
872
|
+
for (const itemKey of itemKeys) {
|
|
873
|
+
endMutations.push(fetchOrquestrator.get(itemKey).startMutation());
|
|
874
|
+
}
|
|
875
|
+
return () => {
|
|
876
|
+
for (const endMutation of endMutations) {
|
|
877
|
+
endMutation();
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
function addItemToState(fetchParams, data) {
|
|
882
|
+
const itemKey = getItemKey(fetchParams);
|
|
883
|
+
store.produceState(
|
|
884
|
+
(draftState) => {
|
|
885
|
+
draftState[itemKey] = {
|
|
886
|
+
data,
|
|
887
|
+
status: "success",
|
|
888
|
+
wasLoaded: true,
|
|
889
|
+
refetchOnMount: false,
|
|
890
|
+
error: null,
|
|
891
|
+
payload: serializableClone(fetchParams)
|
|
892
|
+
};
|
|
893
|
+
},
|
|
894
|
+
{ action: { type: "create-item-state", payload: fetchParams } }
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
function deleteItemState(fetchParams) {
|
|
898
|
+
const itemKeys = getItemsKeyArray(fetchParams);
|
|
899
|
+
store.produceState(
|
|
900
|
+
(draftState) => {
|
|
901
|
+
for (const itemKey of itemKeys) {
|
|
902
|
+
draftState[itemKey] = null;
|
|
903
|
+
}
|
|
904
|
+
},
|
|
905
|
+
{ action: { type: "delete-item-state", payload: fetchParams } }
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
function updateItemState(fetchParams, produceNewData, ifNothingWasUpdated) {
|
|
909
|
+
const itemKeys = getItemsKeyArray(fetchParams);
|
|
910
|
+
let someItemWasUpdated = false;
|
|
911
|
+
store.batch(
|
|
912
|
+
() => {
|
|
913
|
+
store.produceState((draftState) => {
|
|
914
|
+
for (const itemKey of itemKeys) {
|
|
915
|
+
const item = draftState[itemKey];
|
|
916
|
+
if (!item)
|
|
917
|
+
continue;
|
|
918
|
+
if (item.data) {
|
|
919
|
+
someItemWasUpdated = true;
|
|
920
|
+
const newData = produceNewData(item.data, item);
|
|
921
|
+
if (newData) {
|
|
922
|
+
item.data = newData;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
});
|
|
927
|
+
if (ifNothingWasUpdated && !someItemWasUpdated) {
|
|
928
|
+
ifNothingWasUpdated();
|
|
929
|
+
}
|
|
930
|
+
},
|
|
931
|
+
{ type: "update-item-state", item: itemKeys }
|
|
932
|
+
);
|
|
933
|
+
return someItemWasUpdated;
|
|
934
|
+
}
|
|
935
|
+
if (!disableRefetchOnWindowFocus) {
|
|
936
|
+
let handleFocus2 = function() {
|
|
937
|
+
invalidateItem(() => true, "lowPriority");
|
|
938
|
+
};
|
|
939
|
+
var handleFocus = handleFocus2;
|
|
940
|
+
window.addEventListener("focus", handleFocus2);
|
|
941
|
+
window.addEventListener("visibilitychange", handleFocus2);
|
|
942
|
+
}
|
|
943
|
+
return {
|
|
944
|
+
store,
|
|
945
|
+
scheduleFetch,
|
|
946
|
+
awaitFetch,
|
|
947
|
+
useMultipleItems,
|
|
948
|
+
useItem,
|
|
949
|
+
getItemKey,
|
|
950
|
+
getItemState,
|
|
951
|
+
startMutation,
|
|
952
|
+
invalidateItem,
|
|
953
|
+
updateItemState,
|
|
954
|
+
addItemToState,
|
|
955
|
+
deleteItemState
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// src/listQueryStore.ts
|
|
960
|
+
import mitt4 from "mitt";
|
|
961
|
+
import { useCallback as useCallback3, useEffect as useEffect4, useMemo as useMemo4 } from "react";
|
|
962
|
+
import { deepEqual as deepEqual3, Store as Store3, useSubscribeToStore as useSubscribeToStore3 } from "t-state";
|
|
963
|
+
var noFetchFnError = "No fetchItemFn was provided";
|
|
964
|
+
function newTSDFListQueryStore({
|
|
965
|
+
debugName,
|
|
966
|
+
fetchListFn,
|
|
967
|
+
fetchItemFn,
|
|
968
|
+
errorNormalizer,
|
|
969
|
+
defaultQuerySize = 50,
|
|
970
|
+
disableRefetchOnWindowFocus,
|
|
971
|
+
disableRefetchOnMount: globalDisableRefetchOnMount,
|
|
972
|
+
lowPriorityThrottleMs,
|
|
973
|
+
mediumPriorityThrottleMs,
|
|
974
|
+
dynamicRealtimeThrottleMs,
|
|
975
|
+
syncMutationsAndInvalidations
|
|
976
|
+
}) {
|
|
977
|
+
const store = new Store3({
|
|
978
|
+
debugName,
|
|
979
|
+
state: { items: {}, queries: {}, itemQueries: {} }
|
|
980
|
+
});
|
|
981
|
+
function getQueryKey(params) {
|
|
982
|
+
return getCacheId(params);
|
|
983
|
+
}
|
|
984
|
+
async function fetchQuery(fetchCtx, [fetchType, queryPayload, size = defaultQuerySize]) {
|
|
985
|
+
const payload = serializableClone(queryPayload);
|
|
986
|
+
const queryKey = getQueryKey(payload);
|
|
987
|
+
const queryState = store.state.queries[queryKey];
|
|
988
|
+
const isLoading = !queryState?.wasLoaded;
|
|
989
|
+
store.produceState(
|
|
990
|
+
(draft) => {
|
|
991
|
+
const query = draft.queries[queryKey];
|
|
992
|
+
if (!query) {
|
|
993
|
+
draft.queries[queryKey] = {
|
|
994
|
+
error: null,
|
|
995
|
+
status: "loading",
|
|
996
|
+
wasLoaded: false,
|
|
997
|
+
payload,
|
|
998
|
+
refetchOnMount: false,
|
|
999
|
+
hasMore: false,
|
|
1000
|
+
items: []
|
|
1001
|
+
};
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
query.status = query.wasLoaded ? fetchType === "loadMore" ? "loadingMore" : "refetching" : "loading";
|
|
1005
|
+
query.error = null;
|
|
1006
|
+
query.refetchOnMount = false;
|
|
1007
|
+
},
|
|
1008
|
+
{
|
|
1009
|
+
equalityCheck: deepEqual3,
|
|
1010
|
+
action: {
|
|
1011
|
+
type: isLoading ? "fetch-query-start-loading" : fetchType === "loadMore" ? "fetch-query-loading-more" : "refetching-query-start",
|
|
1012
|
+
payload
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
);
|
|
1016
|
+
const currentQuerySize = queryState?.items.length ?? 0;
|
|
1017
|
+
const querySize = (() => {
|
|
1018
|
+
if (fetchType === "loadMore") {
|
|
1019
|
+
return currentQuerySize + size;
|
|
1020
|
+
}
|
|
1021
|
+
if (isLoading)
|
|
1022
|
+
return size;
|
|
1023
|
+
return Math.max(currentQuerySize, size);
|
|
1024
|
+
})();
|
|
1025
|
+
try {
|
|
1026
|
+
const { items, hasMore } = await fetchListFn(payload, querySize);
|
|
1027
|
+
if (fetchCtx.shouldAbort())
|
|
1028
|
+
return false;
|
|
1029
|
+
store.produceState(
|
|
1030
|
+
(draft) => {
|
|
1031
|
+
const query = draft.queries[queryKey];
|
|
1032
|
+
if (!query)
|
|
1033
|
+
return;
|
|
1034
|
+
query.status = "success";
|
|
1035
|
+
query.wasLoaded = true;
|
|
1036
|
+
query.hasMore = hasMore;
|
|
1037
|
+
query.items = [];
|
|
1038
|
+
for (const { data, id } of items) {
|
|
1039
|
+
draft.items[id] = data;
|
|
1040
|
+
query.items.push(String(id));
|
|
1041
|
+
const itemQuery = draft.itemQueries[id];
|
|
1042
|
+
if (!itemQuery || itemQuery.status !== "loading" && itemQuery.status !== "refetching") {
|
|
1043
|
+
draft.itemQueries[id] = {
|
|
1044
|
+
error: null,
|
|
1045
|
+
refetchOnMount: false,
|
|
1046
|
+
status: "success",
|
|
1047
|
+
wasLoaded: true
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
},
|
|
1052
|
+
{
|
|
1053
|
+
action: { type: "fetch-query-success", payload }
|
|
1054
|
+
}
|
|
1055
|
+
);
|
|
1056
|
+
for (const { id } of items) {
|
|
1057
|
+
const itemFetchOrquestrator = fetchItemOrquestrator?.get(String(id));
|
|
1058
|
+
if (itemFetchOrquestrator) {
|
|
1059
|
+
itemFetchOrquestrator.setLastFetchStartTime(fetchCtx.getStartTime());
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
return true;
|
|
1063
|
+
} catch (exception) {
|
|
1064
|
+
if (fetchCtx.shouldAbort())
|
|
1065
|
+
return false;
|
|
1066
|
+
const error = errorNormalizer(exception);
|
|
1067
|
+
store.produceState(
|
|
1068
|
+
(draft) => {
|
|
1069
|
+
const query = draft.queries[queryKey];
|
|
1070
|
+
if (!query)
|
|
1071
|
+
return;
|
|
1072
|
+
query.status = "error";
|
|
1073
|
+
query.error = error;
|
|
1074
|
+
},
|
|
1075
|
+
{
|
|
1076
|
+
action: { type: "fetch-query-error", payload, error }
|
|
1077
|
+
}
|
|
1078
|
+
);
|
|
1079
|
+
return false;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
function getQueryState(params) {
|
|
1083
|
+
return store.state.queries[getQueryKey(params)];
|
|
1084
|
+
}
|
|
1085
|
+
function getItemState(id) {
|
|
1086
|
+
if (typeof id === "string") {
|
|
1087
|
+
return store.state.items[id];
|
|
1088
|
+
}
|
|
1089
|
+
const itemsId = getItemsIdArray(id);
|
|
1090
|
+
return filterAndMap(itemsId, (itemId, ignore2) => {
|
|
1091
|
+
const item = store.state.items[itemId];
|
|
1092
|
+
return !item ? ignore2 : { id: itemId, data: item };
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
const fetchQueryOrquestrator = createCollectionFetchOrquestrator({
|
|
1096
|
+
fetchFn: fetchQuery,
|
|
1097
|
+
lowPriorityThrottleMs,
|
|
1098
|
+
dynamicRealtimeThrottleMs,
|
|
1099
|
+
mediumPriorityThrottleMs
|
|
1100
|
+
});
|
|
1101
|
+
function scheduleListQueryFetch(fetchType, payload, size) {
|
|
1102
|
+
const multiplePayloads = Array.isArray(payload);
|
|
1103
|
+
const payloads = multiplePayloads ? payload : [payload];
|
|
1104
|
+
const results = payloads.map((param) => {
|
|
1105
|
+
return fetchQueryOrquestrator.get(getQueryKey(param)).scheduleFetch(fetchType, ["load", param, size]);
|
|
1106
|
+
});
|
|
1107
|
+
return multiplePayloads ? results : results[0];
|
|
1108
|
+
}
|
|
1109
|
+
function loadMore(params, size) {
|
|
1110
|
+
const queryState = getQueryState(params);
|
|
1111
|
+
if (!queryState || !queryState.hasMore)
|
|
1112
|
+
return "skipped";
|
|
1113
|
+
return fetchQueryOrquestrator.get(getQueryKey(params)).scheduleFetch("highPriority", ["loadMore", params, size]);
|
|
1114
|
+
}
|
|
1115
|
+
function getQueryItems(query, itemDataSelector) {
|
|
1116
|
+
return filterAndMap(query.items, (itemId, ignore2) => {
|
|
1117
|
+
const data = store.state.items[itemId];
|
|
1118
|
+
return data ? itemDataSelector(data, itemId) : ignore2;
|
|
1119
|
+
});
|
|
1120
|
+
}
|
|
1121
|
+
async function awaitListQueryFetch(params, size = defaultQuerySize) {
|
|
1122
|
+
const queryKey = getQueryKey(params);
|
|
1123
|
+
const wasAborted = await fetchQueryOrquestrator.get(queryKey).awaitFetch(["load", params, size]);
|
|
1124
|
+
if (wasAborted) {
|
|
1125
|
+
return {
|
|
1126
|
+
items: [],
|
|
1127
|
+
error: errorNormalizer(new Error("Aborted")),
|
|
1128
|
+
hasMore: false
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
const query = store.state.queries[queryKey];
|
|
1132
|
+
if (!query) {
|
|
1133
|
+
return {
|
|
1134
|
+
items: [],
|
|
1135
|
+
error: errorNormalizer(new Error("Not found")),
|
|
1136
|
+
hasMore: false
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
1139
|
+
return query.error ? { items: [], error: query.error, hasMore: query.hasMore } : {
|
|
1140
|
+
items: getQueryItems(query, (data, id) => ({ data, id })),
|
|
1141
|
+
error: null,
|
|
1142
|
+
hasMore: query.hasMore
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
async function awaitItemFetch(itemId) {
|
|
1146
|
+
if (!fetchItemOrquestrator)
|
|
1147
|
+
throw new Error(noFetchFnError);
|
|
1148
|
+
const wasAborted = await fetchItemOrquestrator.get(itemId).awaitFetch(itemId);
|
|
1149
|
+
if (wasAborted) {
|
|
1150
|
+
return { data: null, error: errorNormalizer(new Error("Aborted")) };
|
|
1151
|
+
}
|
|
1152
|
+
const itemData = store.state.items[itemId];
|
|
1153
|
+
const itemQuery = store.state.itemQueries[itemId];
|
|
1154
|
+
if (!itemQuery || !itemData) {
|
|
1155
|
+
return { data: null, error: errorNormalizer(new Error("Not found")) };
|
|
1156
|
+
}
|
|
1157
|
+
return itemQuery.error ? { data: null, error: itemQuery.error } : { data: itemData, error: null };
|
|
1158
|
+
}
|
|
1159
|
+
function getQueriesKeyArray(payloads) {
|
|
1160
|
+
if (Array.isArray(payloads)) {
|
|
1161
|
+
return payloads.map((payload) => ({
|
|
1162
|
+
key: getQueryKey(payload),
|
|
1163
|
+
payload
|
|
1164
|
+
}));
|
|
1165
|
+
} else if (typeof payloads === "function") {
|
|
1166
|
+
return filterAndMap(
|
|
1167
|
+
Object.entries(store.state.queries),
|
|
1168
|
+
([queryKey, query], ignore2) => {
|
|
1169
|
+
return payloads(query.payload, query, queryKey) ? {
|
|
1170
|
+
key: queryKey,
|
|
1171
|
+
payload: query.payload
|
|
1172
|
+
} : ignore2;
|
|
1173
|
+
}
|
|
1174
|
+
);
|
|
1175
|
+
} else {
|
|
1176
|
+
return [{ key: getQueryKey(payloads), payload: payloads }];
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
const storeEvents = mitt4();
|
|
1180
|
+
const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
|
|
1181
|
+
function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
|
|
1182
|
+
const queriesKey = getQueriesKeyArray(queryPayload);
|
|
1183
|
+
for (const { key } of queriesKey) {
|
|
1184
|
+
store.produceState(
|
|
1185
|
+
(draft) => {
|
|
1186
|
+
const query = draft.queries[key];
|
|
1187
|
+
if (!query)
|
|
1188
|
+
return;
|
|
1189
|
+
query.refetchOnMount = priority;
|
|
1190
|
+
},
|
|
1191
|
+
{ action: { type: "invalidate-data", key } }
|
|
1192
|
+
);
|
|
1193
|
+
queryInvalidationWasTriggered.delete(key);
|
|
1194
|
+
storeEvents.emit("invalidateQuery", { priority, queryKey: key });
|
|
1195
|
+
}
|
|
1196
|
+
if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
|
|
1197
|
+
invalidateItem(
|
|
1198
|
+
(_, itemId) => queriesKey.some(({ payload }) => {
|
|
1199
|
+
return syncMutationsAndInvalidations.syncItemAndQuery(
|
|
1200
|
+
itemId,
|
|
1201
|
+
payload
|
|
1202
|
+
);
|
|
1203
|
+
}),
|
|
1204
|
+
priority,
|
|
1205
|
+
true
|
|
1206
|
+
);
|
|
1207
|
+
invalidateQuery(
|
|
1208
|
+
(queryToInvalidatePayload, _, queryToInvalidateKey) => queriesKey.some((alreadyInvalidatedQueryPayload) => {
|
|
1209
|
+
return queryToInvalidateKey !== alreadyInvalidatedQueryPayload.key && syncMutationsAndInvalidations.syncQueries(
|
|
1210
|
+
alreadyInvalidatedQueryPayload.payload,
|
|
1211
|
+
queryToInvalidatePayload
|
|
1212
|
+
);
|
|
1213
|
+
}),
|
|
1214
|
+
priority,
|
|
1215
|
+
true
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
function defaultItemSelector(data, id) {
|
|
1220
|
+
return { id, data };
|
|
1221
|
+
}
|
|
1222
|
+
function useMultipleListQueries(queries, {
|
|
1223
|
+
itemSelector = defaultItemSelector,
|
|
1224
|
+
omitPayload,
|
|
1225
|
+
returnIdleStatus,
|
|
1226
|
+
returnRefetchingStatus,
|
|
1227
|
+
loadSize,
|
|
1228
|
+
disableRefetchOnMount = globalDisableRefetchOnMount
|
|
1229
|
+
} = {}) {
|
|
1230
|
+
const queriesWithId = useDeepMemo(() => {
|
|
1231
|
+
return queries.map((payload) => {
|
|
1232
|
+
return {
|
|
1233
|
+
key: getQueryKey(payload),
|
|
1234
|
+
payload
|
|
1235
|
+
};
|
|
1236
|
+
});
|
|
1237
|
+
}, [queries]);
|
|
1238
|
+
const dataSelector = useCallback3(itemSelector, []);
|
|
1239
|
+
const resultSelector = useCallback3(
|
|
1240
|
+
(state) => {
|
|
1241
|
+
return queriesWithId.map(
|
|
1242
|
+
({
|
|
1243
|
+
key: queryKey,
|
|
1244
|
+
payload
|
|
1245
|
+
}) => {
|
|
1246
|
+
const query = state.queries[queryKey];
|
|
1247
|
+
if (!query) {
|
|
1248
|
+
return {
|
|
1249
|
+
queryKey,
|
|
1250
|
+
status: returnIdleStatus ? "idle" : "loading",
|
|
1251
|
+
items: [],
|
|
1252
|
+
error: null,
|
|
1253
|
+
hasMore: false,
|
|
1254
|
+
payload: omitPayload ? void 0 : payload,
|
|
1255
|
+
isLoading: returnIdleStatus ? false : true
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
let status = query.status;
|
|
1259
|
+
if (!returnRefetchingStatus && query.status === "refetching") {
|
|
1260
|
+
status = "success";
|
|
1261
|
+
}
|
|
1262
|
+
return {
|
|
1263
|
+
queryKey,
|
|
1264
|
+
status,
|
|
1265
|
+
items: getQueryItems(query, dataSelector),
|
|
1266
|
+
error: query.error,
|
|
1267
|
+
hasMore: query.hasMore,
|
|
1268
|
+
isLoading: status === "loading",
|
|
1269
|
+
payload: omitPayload ? void 0 : query.payload
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
);
|
|
1273
|
+
},
|
|
1274
|
+
[
|
|
1275
|
+
dataSelector,
|
|
1276
|
+
omitPayload,
|
|
1277
|
+
queriesWithId,
|
|
1278
|
+
returnIdleStatus,
|
|
1279
|
+
returnRefetchingStatus
|
|
1280
|
+
]
|
|
1281
|
+
);
|
|
1282
|
+
const storeState = store.useSelector(resultSelector, {
|
|
1283
|
+
equalityFn: deepEqual3,
|
|
1284
|
+
useExternalDeps: true
|
|
1285
|
+
});
|
|
1286
|
+
useOnMittEvent(storeEvents, "invalidateQuery", (event) => {
|
|
1287
|
+
for (const { key, payload } of queriesWithId) {
|
|
1288
|
+
if (key !== event.queryKey)
|
|
1289
|
+
continue;
|
|
1290
|
+
if (!queryInvalidationWasTriggered.has(key)) {
|
|
1291
|
+
scheduleListQueryFetch(event.priority, payload);
|
|
1292
|
+
queryInvalidationWasTriggered.add(key);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
});
|
|
1296
|
+
const loadSizeConst = useConst(() => loadSize);
|
|
1297
|
+
useEffect4(() => {
|
|
1298
|
+
for (const { key: itemId, payload: fetchParams } of queriesWithId) {
|
|
1299
|
+
if (itemId) {
|
|
1300
|
+
if (disableRefetchOnMount) {
|
|
1301
|
+
const itemState = getQueryState(fetchParams);
|
|
1302
|
+
const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
|
|
1303
|
+
if (shouldFetch) {
|
|
1304
|
+
scheduleListQueryFetch(
|
|
1305
|
+
itemState?.refetchOnMount || "lowPriority",
|
|
1306
|
+
fetchParams,
|
|
1307
|
+
loadSizeConst
|
|
1308
|
+
);
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
} else {
|
|
1312
|
+
scheduleListQueryFetch("lowPriority", fetchParams, loadSizeConst);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
}, [disableRefetchOnMount, loadSizeConst, queriesWithId]);
|
|
1317
|
+
return storeState;
|
|
1318
|
+
}
|
|
1319
|
+
function useListQuery(payload, options = {}) {
|
|
1320
|
+
const { ensureIsLoaded } = options;
|
|
1321
|
+
const query = useMemo4(
|
|
1322
|
+
() => payload === false || payload === null || payload === void 0 ? [] : [payload],
|
|
1323
|
+
[payload]
|
|
1324
|
+
);
|
|
1325
|
+
const queryResult = useMultipleListQueries(query, options);
|
|
1326
|
+
const result = useMemo4(
|
|
1327
|
+
() => queryResult[0] ?? {
|
|
1328
|
+
payload: void 0,
|
|
1329
|
+
error: null,
|
|
1330
|
+
hasMore: false,
|
|
1331
|
+
isLoading: false,
|
|
1332
|
+
status: "idle",
|
|
1333
|
+
queryKey: "",
|
|
1334
|
+
items: []
|
|
1335
|
+
},
|
|
1336
|
+
[queryResult]
|
|
1337
|
+
);
|
|
1338
|
+
const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
|
|
1339
|
+
ensureIsLoaded,
|
|
1340
|
+
!!payload,
|
|
1341
|
+
() => {
|
|
1342
|
+
if (payload) {
|
|
1343
|
+
scheduleListQueryFetch("highPriority", payload);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
);
|
|
1347
|
+
useSubscribeToStore3(store, ({ observe }) => {
|
|
1348
|
+
if (!ensureIsLoaded)
|
|
1349
|
+
return;
|
|
1350
|
+
observe.ifSelector((state) => state.queries[result.queryKey]?.status).change.then(({ current }) => {
|
|
1351
|
+
if (current === "success" || current === "error") {
|
|
1352
|
+
emitIsLoadedEvt("isLoaded", true);
|
|
1353
|
+
}
|
|
1354
|
+
});
|
|
1355
|
+
});
|
|
1356
|
+
return useModifyResult(result);
|
|
1357
|
+
}
|
|
1358
|
+
async function fetchItem(fetchCtx, itemId) {
|
|
1359
|
+
if (!fetchItemOrquestrator) {
|
|
1360
|
+
throw new Error(noFetchFnError);
|
|
1361
|
+
}
|
|
1362
|
+
const isLoaded = !store.state.itemQueries[itemId]?.wasLoaded;
|
|
1363
|
+
store.produceState(
|
|
1364
|
+
(draft) => {
|
|
1365
|
+
const itemQuery = draft.itemQueries[itemId];
|
|
1366
|
+
if (!itemQuery) {
|
|
1367
|
+
draft.itemQueries[itemId] = {
|
|
1368
|
+
status: "loading",
|
|
1369
|
+
error: null,
|
|
1370
|
+
wasLoaded: false,
|
|
1371
|
+
refetchOnMount: false
|
|
1372
|
+
};
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
itemQuery.status = itemQuery.wasLoaded ? "refetching" : "loading";
|
|
1376
|
+
itemQuery.error = null;
|
|
1377
|
+
itemQuery.refetchOnMount = false;
|
|
1378
|
+
},
|
|
1379
|
+
{
|
|
1380
|
+
action: {
|
|
1381
|
+
type: isLoaded ? "fetch-item-start" : "fetch-item-refetch-start",
|
|
1382
|
+
itemId
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
);
|
|
1386
|
+
try {
|
|
1387
|
+
const item = await fetchItemFn(itemId);
|
|
1388
|
+
if (fetchCtx.shouldAbort())
|
|
1389
|
+
return false;
|
|
1390
|
+
store.produceState(
|
|
1391
|
+
(draft) => {
|
|
1392
|
+
const itemQuery = draft.itemQueries[itemId];
|
|
1393
|
+
if (!itemQuery)
|
|
1394
|
+
return;
|
|
1395
|
+
itemQuery.status = "success";
|
|
1396
|
+
itemQuery.wasLoaded = true;
|
|
1397
|
+
draft.items[itemId] = item;
|
|
1398
|
+
},
|
|
1399
|
+
{
|
|
1400
|
+
action: { type: "fetch-item-success", itemId }
|
|
1401
|
+
}
|
|
1402
|
+
);
|
|
1403
|
+
return true;
|
|
1404
|
+
} catch (exception) {
|
|
1405
|
+
if (fetchCtx.shouldAbort())
|
|
1406
|
+
return false;
|
|
1407
|
+
const error = errorNormalizer(exception);
|
|
1408
|
+
store.produceState(
|
|
1409
|
+
(draft) => {
|
|
1410
|
+
const itemQuery = draft.itemQueries[itemId];
|
|
1411
|
+
if (!itemQuery)
|
|
1412
|
+
return;
|
|
1413
|
+
itemQuery.status = "error";
|
|
1414
|
+
itemQuery.error = error;
|
|
1415
|
+
},
|
|
1416
|
+
{
|
|
1417
|
+
action: { type: "fetch-item-error", itemId }
|
|
1418
|
+
}
|
|
1419
|
+
);
|
|
1420
|
+
return false;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
const fetchItemOrquestrator = fetchItemFn && createCollectionFetchOrquestrator({
|
|
1424
|
+
fetchFn: fetchItem,
|
|
1425
|
+
lowPriorityThrottleMs,
|
|
1426
|
+
dynamicRealtimeThrottleMs,
|
|
1427
|
+
mediumPriorityThrottleMs
|
|
1428
|
+
});
|
|
1429
|
+
function scheduleItemFetch(fetchType, itemId) {
|
|
1430
|
+
if (!fetchItemOrquestrator) {
|
|
1431
|
+
throw new Error(noFetchFnError);
|
|
1432
|
+
}
|
|
1433
|
+
const fetchMultiple = Array.isArray(itemId);
|
|
1434
|
+
const itemsId = fetchMultiple ? itemId : [itemId];
|
|
1435
|
+
const results = itemsId.map((id) => {
|
|
1436
|
+
return fetchItemOrquestrator.get(id).scheduleFetch(fetchType, id);
|
|
1437
|
+
});
|
|
1438
|
+
return fetchMultiple ? results : results[0];
|
|
1439
|
+
}
|
|
1440
|
+
function getItemsIdArray(itemId) {
|
|
1441
|
+
if (Array.isArray(itemId)) {
|
|
1442
|
+
return itemId;
|
|
1443
|
+
}
|
|
1444
|
+
if (typeof itemId === "function") {
|
|
1445
|
+
return filterAndMap(
|
|
1446
|
+
Object.entries(store.state.items),
|
|
1447
|
+
([id, item], ignore2) => {
|
|
1448
|
+
if (item === null)
|
|
1449
|
+
return ignore2;
|
|
1450
|
+
return itemId(item, id) ? id : ignore2;
|
|
1451
|
+
}
|
|
1452
|
+
);
|
|
1453
|
+
}
|
|
1454
|
+
return [itemId];
|
|
1455
|
+
}
|
|
1456
|
+
const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
|
|
1457
|
+
function invalidateItem(itemId, priority = "highPriority", ignoreInvalidationSync = false) {
|
|
1458
|
+
if (!fetchItemOrquestrator) {
|
|
1459
|
+
throw new Error(noFetchFnError);
|
|
1460
|
+
}
|
|
1461
|
+
const itemsId = getItemsIdArray(itemId);
|
|
1462
|
+
for (const id of itemsId) {
|
|
1463
|
+
store.produceState(
|
|
1464
|
+
(draft) => {
|
|
1465
|
+
const query = draft.itemQueries[id];
|
|
1466
|
+
if (!query)
|
|
1467
|
+
return;
|
|
1468
|
+
query.refetchOnMount = priority;
|
|
1469
|
+
},
|
|
1470
|
+
{ action: { type: "invalidate-item", queryKey: id } }
|
|
1471
|
+
);
|
|
1472
|
+
itemInvalidationWasTriggered.delete(id);
|
|
1473
|
+
storeEvents.emit("invalidateItem", { priority, itemId: id });
|
|
1474
|
+
}
|
|
1475
|
+
if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
|
|
1476
|
+
invalidateQuery(
|
|
1477
|
+
(query) => itemsId.some(
|
|
1478
|
+
(id) => syncMutationsAndInvalidations.syncItemAndQuery(id, query)
|
|
1479
|
+
),
|
|
1480
|
+
priority,
|
|
1481
|
+
true
|
|
1482
|
+
);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
function startItemMutation(itemId) {
|
|
1486
|
+
if (!fetchItemOrquestrator)
|
|
1487
|
+
throw new Error(noFetchFnError);
|
|
1488
|
+
const itemsId = getItemsIdArray(itemId);
|
|
1489
|
+
const endMutations = [];
|
|
1490
|
+
for (const id of itemsId) {
|
|
1491
|
+
endMutations.push(fetchItemOrquestrator.get(id).startMutation());
|
|
1492
|
+
if (syncMutationsAndInvalidations) {
|
|
1493
|
+
for (const [queryKey, query] of Object.entries(store.state.queries)) {
|
|
1494
|
+
if (syncMutationsAndInvalidations.syncItemAndQuery(id, query.payload)) {
|
|
1495
|
+
endMutations.push(
|
|
1496
|
+
fetchQueryOrquestrator.get(queryKey).startMutation()
|
|
1497
|
+
);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
return () => {
|
|
1503
|
+
for (const endMutation of endMutations) {
|
|
1504
|
+
endMutation();
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
function defaultItemDataSelector(data) {
|
|
1509
|
+
return data;
|
|
1510
|
+
}
|
|
1511
|
+
function useMultipleItems(itemIds, {
|
|
1512
|
+
selector = defaultItemDataSelector,
|
|
1513
|
+
returnIdleStatus,
|
|
1514
|
+
returnRefetchingStatus,
|
|
1515
|
+
disableRefetchOnMount
|
|
1516
|
+
} = {}) {
|
|
1517
|
+
const dataSelector = useCallback3(selector, []);
|
|
1518
|
+
const memoizedItemIds = useDeepMemo(() => itemIds, [itemIds]);
|
|
1519
|
+
const resultSelector = useCallback3(
|
|
1520
|
+
(state) => {
|
|
1521
|
+
return memoizedItemIds.map(
|
|
1522
|
+
(itemId) => {
|
|
1523
|
+
const itemQuery = state.itemQueries[itemId];
|
|
1524
|
+
const itemState = state.items[itemId];
|
|
1525
|
+
if (itemQuery === null) {
|
|
1526
|
+
return {
|
|
1527
|
+
status: "deleted",
|
|
1528
|
+
error: null,
|
|
1529
|
+
isLoading: false,
|
|
1530
|
+
itemId,
|
|
1531
|
+
data: dataSelector(null, itemId)
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
if (!itemQuery) {
|
|
1535
|
+
return {
|
|
1536
|
+
status: returnIdleStatus ? "idle" : "loading",
|
|
1537
|
+
error: null,
|
|
1538
|
+
isLoading: returnIdleStatus ? false : true,
|
|
1539
|
+
itemId,
|
|
1540
|
+
data: dataSelector(null, itemId)
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
let status = itemQuery.status;
|
|
1544
|
+
if (!returnRefetchingStatus && itemQuery.status === "refetching") {
|
|
1545
|
+
status = "success";
|
|
1546
|
+
}
|
|
1547
|
+
return {
|
|
1548
|
+
status,
|
|
1549
|
+
error: itemQuery.error,
|
|
1550
|
+
isLoading: status === "loading",
|
|
1551
|
+
data: dataSelector(itemState ?? null, itemId),
|
|
1552
|
+
itemId
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
);
|
|
1556
|
+
},
|
|
1557
|
+
[dataSelector, memoizedItemIds, returnIdleStatus, returnRefetchingStatus]
|
|
1558
|
+
);
|
|
1559
|
+
const storeState = store.useSelector(resultSelector, {
|
|
1560
|
+
equalityFn: deepEqual3,
|
|
1561
|
+
useExternalDeps: true
|
|
1562
|
+
});
|
|
1563
|
+
useOnMittEvent(storeEvents, "invalidateItem", (event) => {
|
|
1564
|
+
for (const itemId of memoizedItemIds) {
|
|
1565
|
+
if (itemId !== event.itemId)
|
|
1566
|
+
continue;
|
|
1567
|
+
if (!itemInvalidationWasTriggered.has(itemId)) {
|
|
1568
|
+
scheduleItemFetch(event.priority, itemId);
|
|
1569
|
+
itemInvalidationWasTriggered.add(itemId);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
});
|
|
1573
|
+
useEffect4(() => {
|
|
1574
|
+
for (const itemId of memoizedItemIds) {
|
|
1575
|
+
if (itemId) {
|
|
1576
|
+
if (disableRefetchOnMount) {
|
|
1577
|
+
const itemState = store.state.itemQueries[itemId];
|
|
1578
|
+
const shouldFetch = !itemState || !itemState.wasLoaded || itemState.refetchOnMount;
|
|
1579
|
+
if (shouldFetch) {
|
|
1580
|
+
scheduleItemFetch(
|
|
1581
|
+
itemState?.refetchOnMount || "lowPriority",
|
|
1582
|
+
itemId
|
|
1583
|
+
);
|
|
1584
|
+
return;
|
|
1585
|
+
}
|
|
1586
|
+
} else {
|
|
1587
|
+
scheduleItemFetch("lowPriority", itemId);
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}, [disableRefetchOnMount, memoizedItemIds]);
|
|
1592
|
+
return storeState;
|
|
1593
|
+
}
|
|
1594
|
+
function useItem(itemId, options = {}) {
|
|
1595
|
+
const { ensureIsLoaded } = options;
|
|
1596
|
+
const query = useMemo4(
|
|
1597
|
+
() => itemId === false || itemId === null || itemId === void 0 ? [] : [itemId],
|
|
1598
|
+
[itemId]
|
|
1599
|
+
);
|
|
1600
|
+
const queryResult = useMultipleItems(query, options);
|
|
1601
|
+
const memoizedSelector = useCallback3(
|
|
1602
|
+
options.selector ?? defaultItemDataSelector,
|
|
1603
|
+
[]
|
|
1604
|
+
);
|
|
1605
|
+
const result = useMemo4(
|
|
1606
|
+
() => queryResult[0] ?? {
|
|
1607
|
+
error: null,
|
|
1608
|
+
isLoading: false,
|
|
1609
|
+
status: "idle",
|
|
1610
|
+
data: memoizedSelector(null, itemId || ""),
|
|
1611
|
+
itemId: itemId || ""
|
|
1612
|
+
},
|
|
1613
|
+
[itemId, memoizedSelector, queryResult]
|
|
1614
|
+
);
|
|
1615
|
+
const [useModifyResult, emitIsLoadedEvt] = useEnsureIsLoaded(
|
|
1616
|
+
ensureIsLoaded,
|
|
1617
|
+
!!itemId,
|
|
1618
|
+
() => {
|
|
1619
|
+
if (itemId) {
|
|
1620
|
+
scheduleItemFetch("highPriority", itemId);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
);
|
|
1624
|
+
useSubscribeToStore3(store, ({ observe }) => {
|
|
1625
|
+
if (!ensureIsLoaded || !itemId)
|
|
1626
|
+
return;
|
|
1627
|
+
observe.ifSelector((state) => state.itemQueries[itemId]?.status).change.then(({ current }) => {
|
|
1628
|
+
if (current === "success" || current === "error") {
|
|
1629
|
+
emitIsLoadedEvt("isLoaded", true);
|
|
1630
|
+
}
|
|
1631
|
+
});
|
|
1632
|
+
});
|
|
1633
|
+
return useModifyResult(result);
|
|
1634
|
+
}
|
|
1635
|
+
function updateItemState(itemIds, produceNewData, ifNothingWasUpdated) {
|
|
1636
|
+
const itemKeys = getItemsIdArray(itemIds);
|
|
1637
|
+
let someItemWasUpdated = false;
|
|
1638
|
+
store.batch(
|
|
1639
|
+
() => {
|
|
1640
|
+
store.produceState((draftState) => {
|
|
1641
|
+
for (const itemId of itemKeys) {
|
|
1642
|
+
const item = draftState.items[itemId];
|
|
1643
|
+
if (!item)
|
|
1644
|
+
continue;
|
|
1645
|
+
someItemWasUpdated = true;
|
|
1646
|
+
const newData = produceNewData(item, itemId);
|
|
1647
|
+
if (newData) {
|
|
1648
|
+
draftState.items[itemId] = newData;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
});
|
|
1652
|
+
if (ifNothingWasUpdated && !someItemWasUpdated) {
|
|
1653
|
+
ifNothingWasUpdated();
|
|
1654
|
+
}
|
|
1655
|
+
},
|
|
1656
|
+
{ type: "update-item-state", item: itemKeys }
|
|
1657
|
+
);
|
|
1658
|
+
return someItemWasUpdated;
|
|
1659
|
+
}
|
|
1660
|
+
function addItemToState(itemId, data) {
|
|
1661
|
+
store.produceState(
|
|
1662
|
+
(draftState) => {
|
|
1663
|
+
draftState.items[itemId] = data;
|
|
1664
|
+
draftState.itemQueries[itemId] = {
|
|
1665
|
+
status: "success",
|
|
1666
|
+
wasLoaded: true,
|
|
1667
|
+
refetchOnMount: false,
|
|
1668
|
+
error: null
|
|
1669
|
+
};
|
|
1670
|
+
},
|
|
1671
|
+
{ action: { type: "create-item-state", itemId } }
|
|
1672
|
+
);
|
|
1673
|
+
}
|
|
1674
|
+
function deleteItemState(itemId) {
|
|
1675
|
+
const itemsId = getItemsIdArray(itemId);
|
|
1676
|
+
store.produceState(
|
|
1677
|
+
(draftState) => {
|
|
1678
|
+
for (const itemKey of itemsId) {
|
|
1679
|
+
draftState.items[itemKey] = null;
|
|
1680
|
+
draftState.itemQueries[itemKey] = null;
|
|
1681
|
+
for (const query of Object.values(draftState.queries)) {
|
|
1682
|
+
if (query.items.includes(itemKey)) {
|
|
1683
|
+
query.items = query.items.filter((i) => i !== itemKey);
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
},
|
|
1688
|
+
{ action: { type: "delete-item-state", itemId } }
|
|
1689
|
+
);
|
|
1690
|
+
}
|
|
1691
|
+
if (!disableRefetchOnWindowFocus) {
|
|
1692
|
+
let handleFocus2 = function() {
|
|
1693
|
+
invalidateQuery(() => true, "lowPriority");
|
|
1694
|
+
invalidateItem(() => true, "lowPriority");
|
|
1695
|
+
};
|
|
1696
|
+
var handleFocus = handleFocus2;
|
|
1697
|
+
window.addEventListener("focus", handleFocus2);
|
|
1698
|
+
window.addEventListener("visibilitychange", handleFocus2);
|
|
1699
|
+
}
|
|
1700
|
+
return {
|
|
1701
|
+
store,
|
|
1702
|
+
scheduleListQueryFetch,
|
|
1703
|
+
getQueryState,
|
|
1704
|
+
getQueryKey,
|
|
1705
|
+
deleteItemState,
|
|
1706
|
+
getItemState,
|
|
1707
|
+
loadMore,
|
|
1708
|
+
invalidateQuery,
|
|
1709
|
+
invalidateItem,
|
|
1710
|
+
scheduleItemFetch,
|
|
1711
|
+
awaitItemFetch,
|
|
1712
|
+
awaitListQueryFetch,
|
|
1713
|
+
useMultipleListQueries,
|
|
1714
|
+
useListQuery,
|
|
1715
|
+
useItem,
|
|
1716
|
+
useMultipleItems,
|
|
1717
|
+
addItemToState,
|
|
1718
|
+
updateItemState,
|
|
1719
|
+
startItemMutation
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
export {
|
|
1723
|
+
newTSDFCollectionStore,
|
|
1724
|
+
newTSDFDocumentStore,
|
|
1725
|
+
newTSDFListQueryStore
|
|
1726
|
+
};
|