tsdf 11.2.2 → 12.2.0

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 CHANGED
@@ -395,21 +395,25 @@ var import_react5 = require("evtmitter/react");
395
395
  function newTSDFDocumentStore({
396
396
  debugName,
397
397
  fetchFn,
398
- initialData,
398
+ getInitialData,
399
399
  disableRefetchOnMount: globalDisableRefetchOnMount,
400
400
  lowPriorityThrottleMs,
401
401
  mediumPriorityThrottleMs,
402
402
  dynamicRealtimeThrottleMs,
403
403
  disableInitialDataInvalidation,
404
- errorNormalizer
404
+ errorNormalizer,
405
+ onInvalidate
405
406
  }) {
406
407
  const store = new import_t_state3.Store({
407
408
  debugName,
408
- state: {
409
- data: initialData ?? null,
410
- error: null,
411
- status: initialData ? "success" : "idle",
412
- refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
409
+ state: () => {
410
+ const initialData = getInitialData?.();
411
+ return {
412
+ data: initialData ?? null,
413
+ error: null,
414
+ status: initialData ? "success" : "idle",
415
+ refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
416
+ };
413
417
  }
414
418
  });
415
419
  async function fetch(fetchCtx, _) {
@@ -480,6 +484,7 @@ function newTSDFDocumentStore({
480
484
  store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
481
485
  invalidationWasTriggered = false;
482
486
  storeEvents.emit("invalidateData", priority);
487
+ onInvalidate?.(priority);
483
488
  }
484
489
  function useDocument({
485
490
  selector,
@@ -648,28 +653,32 @@ function newTSDFCollectionStore({
648
653
  errorNormalizer,
649
654
  disableInitialDataInvalidation,
650
655
  mediumPriorityThrottleMs,
651
- initialStateItems,
656
+ getInitialData,
652
657
  disableRefetchOnMount: globalDisableRefetchOnMount,
653
658
  dynamicRealtimeThrottleMs,
654
- getCollectionItemKey: filterCollectionItemObjKey
659
+ getCollectionItemKey: filterCollectionItemObjKey,
660
+ onInvalidate
655
661
  }) {
656
- const initialState = {};
657
- if (initialStateItems) {
658
- for (const item of initialStateItems) {
659
- const itemKey = getItemKey(item.payload);
660
- initialState[itemKey] = {
661
- data: item.data,
662
- error: null,
663
- status: "success",
664
- payload: item.payload,
665
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
666
- wasLoaded: true
667
- };
668
- }
669
- }
670
662
  const store = new import_t_state4.Store({
671
663
  debugName,
672
- state: initialState
664
+ state: () => {
665
+ const initialState = {};
666
+ const initialStateItems = getInitialData?.();
667
+ if (initialStateItems) {
668
+ for (const item of initialStateItems) {
669
+ const itemKey = getItemKey(item.payload);
670
+ initialState[itemKey] = {
671
+ data: item.data,
672
+ error: null,
673
+ status: "success",
674
+ payload: item.payload,
675
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
676
+ wasLoaded: true
677
+ };
678
+ }
679
+ }
680
+ return initialState;
681
+ }
673
682
  });
674
683
  function getItemKey(params) {
675
684
  return getCacheId(
@@ -808,6 +817,13 @@ function newTSDFCollectionStore({
808
817
  );
809
818
  invalidationWasTriggered.delete(itemKey);
810
819
  storeEvents.emit("invalidateData", { priority, itemKey });
820
+ if (item.data) {
821
+ onInvalidate?.({
822
+ priority,
823
+ payload: item.payload,
824
+ itemState: item.data
825
+ });
826
+ }
811
827
  }
812
828
  }
813
829
  function getItemState(params) {
@@ -1072,6 +1088,31 @@ function findAndMap(arr, findFn) {
1072
1088
  return void 0;
1073
1089
  }
1074
1090
 
1091
+ // src/utils/sortBy.ts
1092
+ function sortBy(arr, getPriority, { order = "asc" } = {}) {
1093
+ return [...arr].sort((a, b) => {
1094
+ const _aPriority = getPriority(a);
1095
+ const _bPriority = getPriority(b);
1096
+ const aPriority = Array.isArray(_aPriority) ? _aPriority : [_aPriority];
1097
+ const bPriority = Array.isArray(_bPriority) ? _bPriority : [_bPriority];
1098
+ for (let i = 0; i < aPriority.length; i++) {
1099
+ const levelOrder = typeof order === "string" ? order : order[i] ?? "asc";
1100
+ const aP = aPriority[i] ?? 0;
1101
+ const bP = bPriority[i] ?? 0;
1102
+ if (aP === bP) {
1103
+ continue;
1104
+ }
1105
+ if (bP === Infinity || aP === -Infinity || aP < bP) {
1106
+ return levelOrder === "asc" ? -1 : 1;
1107
+ }
1108
+ if (aP === Infinity || bP === -Infinity || aP > bP) {
1109
+ return levelOrder === "asc" ? 1 : -1;
1110
+ }
1111
+ }
1112
+ return 0;
1113
+ });
1114
+ }
1115
+
1075
1116
  // src/listQueryStore.ts
1076
1117
  var noFetchFnError = "No fetchItemFn was provided";
1077
1118
  function newTSDFListQueryStore({
@@ -1080,43 +1121,49 @@ function newTSDFListQueryStore({
1080
1121
  fetchItemFn,
1081
1122
  errorNormalizer,
1082
1123
  defaultQuerySize = 50,
1083
- initialData,
1124
+ getInitialData,
1084
1125
  disableRefetchOnMount: globalDisableRefetchOnMount,
1085
1126
  lowPriorityThrottleMs,
1086
1127
  disableInitialDataInvalidation,
1087
1128
  mediumPriorityThrottleMs,
1088
1129
  dynamicRealtimeThrottleMs,
1089
- syncMutationsAndInvalidations
1130
+ syncMutationsAndInvalidations,
1131
+ optimisticListUpdates,
1132
+ onInvalidateItem,
1133
+ onInvalidateQuery
1090
1134
  }) {
1091
- const initialState = { items: {}, queries: {}, itemQueries: {} };
1092
- if (initialData) {
1093
- for (const { payload, data } of initialData.items) {
1094
- const itemKey = getItemKey(payload);
1095
- initialState.items[itemKey] = data;
1096
- initialState.itemQueries[itemKey] = {
1097
- error: null,
1098
- status: "success",
1099
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1100
- wasLoaded: true,
1101
- payload
1102
- };
1103
- }
1104
- for (const { payload, items, hasMore } of initialData.queries) {
1105
- const queryKey = getQueryKey(payload);
1106
- initialState.queries[queryKey] = {
1107
- error: null,
1108
- status: "success",
1109
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1110
- wasLoaded: true,
1111
- payload,
1112
- items,
1113
- hasMore
1114
- };
1115
- }
1116
- }
1117
1135
  const store = new import_t_state5.Store({
1118
1136
  debugName,
1119
- state: initialState
1137
+ state: () => {
1138
+ const initialState = { items: {}, queries: {}, itemQueries: {} };
1139
+ const initialData = getInitialData?.();
1140
+ if (initialData) {
1141
+ for (const { payload, data } of initialData.items) {
1142
+ const itemKey = getItemKey(payload);
1143
+ initialState.items[itemKey] = data;
1144
+ initialState.itemQueries[itemKey] = {
1145
+ error: null,
1146
+ status: "success",
1147
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1148
+ wasLoaded: true,
1149
+ payload
1150
+ };
1151
+ }
1152
+ for (const { payload, items, hasMore } of initialData.queries) {
1153
+ const queryKey = getQueryKey(payload);
1154
+ initialState.queries[queryKey] = {
1155
+ error: null,
1156
+ status: "success",
1157
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1158
+ wasLoaded: true,
1159
+ payload,
1160
+ items,
1161
+ hasMore
1162
+ };
1163
+ }
1164
+ }
1165
+ return initialState;
1166
+ }
1120
1167
  });
1121
1168
  function getQueryKey(params) {
1122
1169
  return getCacheId(params);
@@ -1360,7 +1407,7 @@ function newTSDFListQueryStore({
1360
1407
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1361
1408
  function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1362
1409
  const queriesKey = getQueriesKeyArray(queryPayload);
1363
- for (const { key } of queriesKey) {
1410
+ for (const { key, payload } of queriesKey) {
1364
1411
  const queryState = store.state.queries[key];
1365
1412
  if (!queryState)
1366
1413
  continue;
@@ -1379,6 +1426,7 @@ function newTSDFListQueryStore({
1379
1426
  );
1380
1427
  queryInvalidationWasTriggered.delete(key);
1381
1428
  storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1429
+ onInvalidateQuery?.(payload, priority);
1382
1430
  }
1383
1431
  if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1384
1432
  invalidateItem(
@@ -1662,7 +1710,7 @@ function newTSDFListQueryStore({
1662
1710
  throw new Error(noFetchFnError);
1663
1711
  }
1664
1712
  const itemsKey = getItemsKeyArray(itemId);
1665
- for (const { itemKey } of itemsKey) {
1713
+ for (const { itemKey, payload } of itemsKey) {
1666
1714
  const item = store.state.itemQueries[itemKey];
1667
1715
  if (!item)
1668
1716
  continue;
@@ -1681,6 +1729,16 @@ function newTSDFListQueryStore({
1681
1729
  );
1682
1730
  itemInvalidationWasTriggered.delete(itemKey);
1683
1731
  storeEvents.emit("invalidateItem", { priority, itemKey });
1732
+ if (onInvalidateItem) {
1733
+ const itemState = store.state.items[itemKey];
1734
+ if (itemState) {
1735
+ onInvalidateItem({
1736
+ priority,
1737
+ itemState,
1738
+ payload
1739
+ });
1740
+ }
1741
+ }
1684
1742
  }
1685
1743
  if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1686
1744
  invalidateQuery(
@@ -1913,6 +1971,9 @@ function newTSDFListQueryStore({
1913
1971
  }
1914
1972
  }
1915
1973
  });
1974
+ if (someItemWasUpdated) {
1975
+ applyOptimisticListUpdates(itemKeys.map((i) => i.itemKey));
1976
+ }
1916
1977
  if (ifNothingWasUpdated && !someItemWasUpdated) {
1917
1978
  ifNothingWasUpdated();
1918
1979
  }
@@ -1921,48 +1982,134 @@ function newTSDFListQueryStore({
1921
1982
  );
1922
1983
  return someItemWasUpdated;
1923
1984
  }
1985
+ function applyOptimisticListUpdates(itemKeys) {
1986
+ if (!optimisticListUpdates)
1987
+ return;
1988
+ const queriesToInvalidate = [];
1989
+ store.produceState((draftState) => {
1990
+ for (const itemKey of itemKeys) {
1991
+ const item = draftState.items[itemKey];
1992
+ if (!item)
1993
+ continue;
1994
+ for (const {
1995
+ queries,
1996
+ filterItem,
1997
+ appendNewTo = "end",
1998
+ invalidateQueries,
1999
+ sort
2000
+ } of optimisticListUpdates) {
2001
+ const relatedFilterQueries = getQueriesKeyArray(queries);
2002
+ for (const { key: queryKey, payload } of relatedFilterQueries) {
2003
+ const queryState = draftState.queries[queryKey];
2004
+ if (filterItem) {
2005
+ const itemShouldBeIncluded = filterItem(item);
2006
+ if (itemShouldBeIncluded === null)
2007
+ continue;
2008
+ if (itemShouldBeIncluded) {
2009
+ if (!queryState) {
2010
+ draftState.queries[queryKey] = {
2011
+ status: "success",
2012
+ items: [itemKey],
2013
+ error: null,
2014
+ hasMore: false,
2015
+ payload,
2016
+ refetchOnMount: "lowPriority",
2017
+ wasLoaded: true
2018
+ };
2019
+ continue;
2020
+ }
2021
+ if (queryState.items.includes(itemKey))
2022
+ continue;
2023
+ if (invalidateQueries)
2024
+ queriesToInvalidate.push(payload);
2025
+ if (appendNewTo === "end") {
2026
+ queryState.items.push(itemKey);
2027
+ } else {
2028
+ queryState.items.unshift(itemKey);
2029
+ }
2030
+ } else {
2031
+ if (!queryState)
2032
+ continue;
2033
+ const itemIndex = queryState.items.indexOf(itemKey);
2034
+ if (itemIndex !== -1) {
2035
+ if (invalidateQueries)
2036
+ queriesToInvalidate.push(queryState.payload);
2037
+ queryState.items.splice(itemIndex, 1);
2038
+ }
2039
+ }
2040
+ }
2041
+ if (sort) {
2042
+ if (!queryState)
2043
+ continue;
2044
+ const queryHasItem = queryState.items.includes(itemKey);
2045
+ if (!queryHasItem)
2046
+ continue;
2047
+ queryState.items = sortBy(
2048
+ queryState.items,
2049
+ (itemId) => {
2050
+ const itemState = store.state.items[itemId];
2051
+ const itemPayload = store.state.itemQueries[itemId]?.payload;
2052
+ if (!itemState || !itemPayload)
2053
+ return Infinity;
2054
+ return sort.sortBy(itemState, itemPayload);
2055
+ },
2056
+ {
2057
+ order: sort.order
2058
+ }
2059
+ );
2060
+ }
2061
+ }
2062
+ }
2063
+ }
2064
+ });
2065
+ if (queriesToInvalidate.length)
2066
+ invalidateQuery(queriesToInvalidate);
2067
+ }
1924
2068
  function addItemToState(itemPayload, data, {
1925
2069
  addItemToQueries
1926
2070
  } = {}) {
1927
2071
  const itemKey = getItemKey(itemPayload);
1928
- store.produceState(
1929
- (draftState) => {
1930
- draftState.items[itemKey] = data;
1931
- draftState.itemQueries[itemKey] = {
1932
- status: "success",
1933
- wasLoaded: true,
1934
- refetchOnMount: false,
1935
- error: null,
1936
- payload: (0, import_json2.klona)(itemPayload)
1937
- };
1938
- if (addItemToQueries) {
1939
- const queries = getQueriesKeyArray(addItemToQueries.queries);
1940
- for (const { key } of queries) {
1941
- if (draftState.queries[key]) {
1942
- const queryState = draftState.queries[key];
1943
- if (!queryState)
1944
- continue;
1945
- if (queryState.items.includes(itemKey))
1946
- continue;
1947
- if (addItemToQueries.appendTo === "start") {
1948
- queryState.items.unshift(itemKey);
1949
- } else if (addItemToQueries.appendTo === "end") {
1950
- queryState.items.push(itemKey);
1951
- } else {
1952
- const index = addItemToQueries.appendTo(
1953
- filterAndMap(
1954
- queryState.items,
1955
- (itemKey2, ignore) => draftState.itemQueries[itemKey2]?.payload || ignore
1956
- )
1957
- );
1958
- queryState.items.splice(index, 0, itemKey);
2072
+ store.batch(() => {
2073
+ store.produceState(
2074
+ (draftState) => {
2075
+ draftState.items[itemKey] = data;
2076
+ draftState.itemQueries[itemKey] = {
2077
+ status: "success",
2078
+ wasLoaded: true,
2079
+ refetchOnMount: false,
2080
+ error: null,
2081
+ payload: (0, import_json2.klona)(itemPayload)
2082
+ };
2083
+ if (addItemToQueries) {
2084
+ const queries = getQueriesKeyArray(addItemToQueries.queries);
2085
+ for (const { key } of queries) {
2086
+ if (draftState.queries[key]) {
2087
+ const queryState = draftState.queries[key];
2088
+ if (!queryState)
2089
+ continue;
2090
+ if (queryState.items.includes(itemKey))
2091
+ continue;
2092
+ if (addItemToQueries.appendTo === "start") {
2093
+ queryState.items.unshift(itemKey);
2094
+ } else if (addItemToQueries.appendTo === "end") {
2095
+ queryState.items.push(itemKey);
2096
+ } else {
2097
+ const index = addItemToQueries.appendTo(
2098
+ filterAndMap(
2099
+ queryState.items,
2100
+ (itemKey2, ignore) => draftState.itemQueries[itemKey2]?.payload || ignore
2101
+ )
2102
+ );
2103
+ queryState.items.splice(index, 0, itemKey);
2104
+ }
1959
2105
  }
1960
2106
  }
1961
2107
  }
1962
- }
1963
- },
1964
- { action: { type: "create-item-state", itemPayload } }
1965
- );
2108
+ },
2109
+ { action: { type: "create-item-state", itemPayload } }
2110
+ );
2111
+ applyOptimisticListUpdates([itemKey]);
2112
+ });
1966
2113
  }
1967
2114
  function deleteItemState(itemId) {
1968
2115
  const itemsId = getItemsKeyArray(itemId);
package/dist/main.d.cts CHANGED
@@ -20,16 +20,17 @@ type TSDFUseDocumentReturn<Selected, NError> = {
20
20
  error: NError | null;
21
21
  isLoading: boolean;
22
22
  };
23
- declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, initialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, disableInitialDataInvalidation, errorNormalizer, }: {
23
+ declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, disableInitialDataInvalidation, errorNormalizer, onInvalidate, }: {
24
24
  debugName?: string;
25
25
  fetchFn: () => Promise<State>;
26
- initialData?: State;
26
+ getInitialData?: () => State | undefined;
27
27
  disableInitialDataInvalidation?: boolean;
28
28
  errorNormalizer: (exception: unknown) => NError;
29
29
  disableRefetchOnMount?: boolean;
30
30
  lowPriorityThrottleMs?: number;
31
31
  mediumPriorityThrottleMs?: number;
32
32
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
33
+ onInvalidate?: (priority: FetchType) => void;
33
34
  }): {
34
35
  store: Store<TSDFDocumentStoreState<State, NError>>;
35
36
  reset: () => void;
@@ -77,17 +78,22 @@ type CollectionInitialStateItem<ItemPayload extends ValidPayload, ItemState exte
77
78
  payload: ItemPayload;
78
79
  data: ItemState;
79
80
  };
80
- declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, lowPriorityThrottleMs, errorNormalizer, disableInitialDataInvalidation, mediumPriorityThrottleMs, initialStateItems, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, }: {
81
+ declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, lowPriorityThrottleMs, errorNormalizer, disableInitialDataInvalidation, mediumPriorityThrottleMs, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, onInvalidate, }: {
81
82
  debugName?: string;
82
83
  fetchFn: (params: ItemPayload) => Promise<ItemState>;
83
84
  getCollectionItemKey?: (params: ItemPayload) => ValidPayload | any[];
84
85
  errorNormalizer: (exception: unknown) => NError;
85
86
  disableRefetchOnMount?: boolean;
86
- initialStateItems?: CollectionInitialStateItem<ItemPayload, ItemState>[];
87
+ getInitialData?: () => CollectionInitialStateItem<ItemPayload, ItemState>[] | undefined;
87
88
  disableInitialDataInvalidation?: boolean;
88
89
  lowPriorityThrottleMs?: number;
89
90
  mediumPriorityThrottleMs?: number;
90
91
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
92
+ onInvalidate?: (props: {
93
+ itemState: ItemState;
94
+ payload: ItemPayload;
95
+ priority: FetchType;
96
+ }) => void;
91
97
  }): {
92
98
  store: Store<TSFDCollectionState<ItemState, ItemPayload, NError>>;
93
99
  scheduleFetch: {
@@ -188,13 +194,13 @@ type ListQueryStoreInitialData<ItemState extends ValidStoreState, QueryPayload e
188
194
  hasMore: boolean;
189
195
  }[];
190
196
  };
191
- declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, initialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, disableInitialDataInvalidation, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, syncMutationsAndInvalidations, }: {
197
+ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, disableInitialDataInvalidation, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, syncMutationsAndInvalidations, optimisticListUpdates, onInvalidateItem, onInvalidateQuery, }: {
192
198
  debugName?: string;
193
199
  fetchListFn: (payload: QueryPayload, size: number) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
194
200
  fetchItemFn?: (itemId: ItemPayload) => Promise<ItemState>;
195
201
  errorNormalizer: (exception: unknown) => NError;
196
202
  defaultQuerySize?: number;
197
- initialData?: ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload>;
203
+ getInitialData?: () => ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload> | undefined;
198
204
  disableInitialDataInvalidation?: boolean;
199
205
  syncMutationsAndInvalidations?: {
200
206
  syncQueries: (query1: QueryPayload, query2: QueryPayload) => boolean;
@@ -204,6 +210,24 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
204
210
  lowPriorityThrottleMs?: number;
205
211
  mediumPriorityThrottleMs?: number;
206
212
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
213
+ optimisticListUpdates?: {
214
+ queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
215
+ filterItem?: (item: ItemState) => boolean | null;
216
+ /** @default 'end' */
217
+ appendNewTo?: 'start' | 'end';
218
+ invalidateQueries?: boolean;
219
+ sort?: {
220
+ sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[];
221
+ /** @default 'asc' */
222
+ order?: 'asc' | 'desc' | ('asc' | 'desc')[];
223
+ };
224
+ }[];
225
+ onInvalidateQuery?: (query: QueryPayload, priority: FetchType) => void;
226
+ onInvalidateItem?: (props: {
227
+ itemState: ItemState;
228
+ payload: ItemPayload;
229
+ priority: FetchType;
230
+ }) => void;
207
231
  }): {
208
232
  store: Store<TSFDListQueryState<ItemState, NError, QueryPayload, ItemPayload>>;
209
233
  reset: () => void;
@@ -222,7 +246,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
222
246
  (itemPayload: ItemPayload): ItemState | null | undefined;
223
247
  };
224
248
  loadMore: (params: QueryPayload, size?: number) => ScheduleFetchResults;
225
- invalidateQuery: (queryPayload: QueryPayload | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[], priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
249
+ invalidateQuery: (queryPayload: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean), priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
226
250
  invalidateItem: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[], priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
227
251
  scheduleItemFetch: {
228
252
  (fetchType: FetchType, itemPayload: ItemPayload): ScheduleFetchResults;
@@ -283,7 +307,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
283
307
  }) => readonly TSFDUseListItemReturn<SelectedItem_3, NError, ItemPayload>[];
284
308
  addItemToState: (itemPayload: ItemPayload, data: ItemState, { addItemToQueries, }?: {
285
309
  addItemToQueries?: {
286
- queries: QueryPayload | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[];
310
+ queries: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean);
287
311
  appendTo: "start" | "end" | ((itemsPayload: ItemPayload[]) => number);
288
312
  } | undefined;
289
313
  }) => void;
@@ -291,7 +315,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
291
315
  ifNothingWasUpdated?: (() => void) | undefined;
292
316
  }) => boolean;
293
317
  startItemMutation: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[]) => () => void;
294
- getQueriesState: (params: ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[]) => {
318
+ getQueriesState: (params: QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean)) => {
295
319
  query: TSFDListQuery<NError, QueryPayload>;
296
320
  key: string;
297
321
  }[];
package/dist/main.d.ts CHANGED
@@ -20,16 +20,17 @@ type TSDFUseDocumentReturn<Selected, NError> = {
20
20
  error: NError | null;
21
21
  isLoading: boolean;
22
22
  };
23
- declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, initialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, disableInitialDataInvalidation, errorNormalizer, }: {
23
+ declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, disableInitialDataInvalidation, errorNormalizer, onInvalidate, }: {
24
24
  debugName?: string;
25
25
  fetchFn: () => Promise<State>;
26
- initialData?: State;
26
+ getInitialData?: () => State | undefined;
27
27
  disableInitialDataInvalidation?: boolean;
28
28
  errorNormalizer: (exception: unknown) => NError;
29
29
  disableRefetchOnMount?: boolean;
30
30
  lowPriorityThrottleMs?: number;
31
31
  mediumPriorityThrottleMs?: number;
32
32
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
33
+ onInvalidate?: (priority: FetchType) => void;
33
34
  }): {
34
35
  store: Store<TSDFDocumentStoreState<State, NError>>;
35
36
  reset: () => void;
@@ -77,17 +78,22 @@ type CollectionInitialStateItem<ItemPayload extends ValidPayload, ItemState exte
77
78
  payload: ItemPayload;
78
79
  data: ItemState;
79
80
  };
80
- declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, lowPriorityThrottleMs, errorNormalizer, disableInitialDataInvalidation, mediumPriorityThrottleMs, initialStateItems, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, }: {
81
+ declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, lowPriorityThrottleMs, errorNormalizer, disableInitialDataInvalidation, mediumPriorityThrottleMs, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, onInvalidate, }: {
81
82
  debugName?: string;
82
83
  fetchFn: (params: ItemPayload) => Promise<ItemState>;
83
84
  getCollectionItemKey?: (params: ItemPayload) => ValidPayload | any[];
84
85
  errorNormalizer: (exception: unknown) => NError;
85
86
  disableRefetchOnMount?: boolean;
86
- initialStateItems?: CollectionInitialStateItem<ItemPayload, ItemState>[];
87
+ getInitialData?: () => CollectionInitialStateItem<ItemPayload, ItemState>[] | undefined;
87
88
  disableInitialDataInvalidation?: boolean;
88
89
  lowPriorityThrottleMs?: number;
89
90
  mediumPriorityThrottleMs?: number;
90
91
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
92
+ onInvalidate?: (props: {
93
+ itemState: ItemState;
94
+ payload: ItemPayload;
95
+ priority: FetchType;
96
+ }) => void;
91
97
  }): {
92
98
  store: Store<TSFDCollectionState<ItemState, ItemPayload, NError>>;
93
99
  scheduleFetch: {
@@ -188,13 +194,13 @@ type ListQueryStoreInitialData<ItemState extends ValidStoreState, QueryPayload e
188
194
  hasMore: boolean;
189
195
  }[];
190
196
  };
191
- declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, initialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, disableInitialDataInvalidation, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, syncMutationsAndInvalidations, }: {
197
+ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, disableInitialDataInvalidation, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, syncMutationsAndInvalidations, optimisticListUpdates, onInvalidateItem, onInvalidateQuery, }: {
192
198
  debugName?: string;
193
199
  fetchListFn: (payload: QueryPayload, size: number) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
194
200
  fetchItemFn?: (itemId: ItemPayload) => Promise<ItemState>;
195
201
  errorNormalizer: (exception: unknown) => NError;
196
202
  defaultQuerySize?: number;
197
- initialData?: ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload>;
203
+ getInitialData?: () => ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload> | undefined;
198
204
  disableInitialDataInvalidation?: boolean;
199
205
  syncMutationsAndInvalidations?: {
200
206
  syncQueries: (query1: QueryPayload, query2: QueryPayload) => boolean;
@@ -204,6 +210,24 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
204
210
  lowPriorityThrottleMs?: number;
205
211
  mediumPriorityThrottleMs?: number;
206
212
  dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
213
+ optimisticListUpdates?: {
214
+ queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
215
+ filterItem?: (item: ItemState) => boolean | null;
216
+ /** @default 'end' */
217
+ appendNewTo?: 'start' | 'end';
218
+ invalidateQueries?: boolean;
219
+ sort?: {
220
+ sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[];
221
+ /** @default 'asc' */
222
+ order?: 'asc' | 'desc' | ('asc' | 'desc')[];
223
+ };
224
+ }[];
225
+ onInvalidateQuery?: (query: QueryPayload, priority: FetchType) => void;
226
+ onInvalidateItem?: (props: {
227
+ itemState: ItemState;
228
+ payload: ItemPayload;
229
+ priority: FetchType;
230
+ }) => void;
207
231
  }): {
208
232
  store: Store<TSFDListQueryState<ItemState, NError, QueryPayload, ItemPayload>>;
209
233
  reset: () => void;
@@ -222,7 +246,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
222
246
  (itemPayload: ItemPayload): ItemState | null | undefined;
223
247
  };
224
248
  loadMore: (params: QueryPayload, size?: number) => ScheduleFetchResults;
225
- invalidateQuery: (queryPayload: QueryPayload | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[], priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
249
+ invalidateQuery: (queryPayload: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean), priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
226
250
  invalidateItem: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[], priority?: FetchType, ignoreInvalidationSync?: boolean) => void;
227
251
  scheduleItemFetch: {
228
252
  (fetchType: FetchType, itemPayload: ItemPayload): ScheduleFetchResults;
@@ -283,7 +307,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
283
307
  }) => readonly TSFDUseListItemReturn<SelectedItem_3, NError, ItemPayload>[];
284
308
  addItemToState: (itemPayload: ItemPayload, data: ItemState, { addItemToQueries, }?: {
285
309
  addItemToQueries?: {
286
- queries: QueryPayload | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[];
310
+ queries: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean);
287
311
  appendTo: "start" | "end" | ((itemsPayload: ItemPayload[]) => number);
288
312
  } | undefined;
289
313
  }) => void;
@@ -291,7 +315,7 @@ declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError
291
315
  ifNothingWasUpdated?: (() => void) | undefined;
292
316
  }) => boolean;
293
317
  startItemMutation: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[]) => () => void;
294
- getQueriesState: (params: ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean) | QueryPayload[]) => {
318
+ getQueriesState: (params: QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean)) => {
295
319
  query: TSFDListQuery<NError, QueryPayload>;
296
320
  key: string;
297
321
  }[];
package/dist/main.js CHANGED
@@ -367,21 +367,25 @@ import { useOnEvtmitterEvent as useOnEvtmitterEvent2 } from "evtmitter/react";
367
367
  function newTSDFDocumentStore({
368
368
  debugName,
369
369
  fetchFn,
370
- initialData,
370
+ getInitialData,
371
371
  disableRefetchOnMount: globalDisableRefetchOnMount,
372
372
  lowPriorityThrottleMs,
373
373
  mediumPriorityThrottleMs,
374
374
  dynamicRealtimeThrottleMs,
375
375
  disableInitialDataInvalidation,
376
- errorNormalizer
376
+ errorNormalizer,
377
+ onInvalidate
377
378
  }) {
378
379
  const store = new Store({
379
380
  debugName,
380
- state: {
381
- data: initialData ?? null,
382
- error: null,
383
- status: initialData ? "success" : "idle",
384
- refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
381
+ state: () => {
382
+ const initialData = getInitialData?.();
383
+ return {
384
+ data: initialData ?? null,
385
+ error: null,
386
+ status: initialData ? "success" : "idle",
387
+ refetchOnMount: !!initialData && !disableInitialDataInvalidation ? "lowPriority" : false
388
+ };
385
389
  }
386
390
  });
387
391
  async function fetch(fetchCtx, _) {
@@ -452,6 +456,7 @@ function newTSDFDocumentStore({
452
456
  store.setKey("refetchOnMount", priority, { action: "invalidate-data" });
453
457
  invalidationWasTriggered = false;
454
458
  storeEvents.emit("invalidateData", priority);
459
+ onInvalidate?.(priority);
455
460
  }
456
461
  function useDocument({
457
462
  selector,
@@ -620,28 +625,32 @@ function newTSDFCollectionStore({
620
625
  errorNormalizer,
621
626
  disableInitialDataInvalidation,
622
627
  mediumPriorityThrottleMs,
623
- initialStateItems,
628
+ getInitialData,
624
629
  disableRefetchOnMount: globalDisableRefetchOnMount,
625
630
  dynamicRealtimeThrottleMs,
626
- getCollectionItemKey: filterCollectionItemObjKey
631
+ getCollectionItemKey: filterCollectionItemObjKey,
632
+ onInvalidate
627
633
  }) {
628
- const initialState = {};
629
- if (initialStateItems) {
630
- for (const item of initialStateItems) {
631
- const itemKey = getItemKey(item.payload);
632
- initialState[itemKey] = {
633
- data: item.data,
634
- error: null,
635
- status: "success",
636
- payload: item.payload,
637
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
638
- wasLoaded: true
639
- };
640
- }
641
- }
642
634
  const store = new Store2({
643
635
  debugName,
644
- state: initialState
636
+ state: () => {
637
+ const initialState = {};
638
+ const initialStateItems = getInitialData?.();
639
+ if (initialStateItems) {
640
+ for (const item of initialStateItems) {
641
+ const itemKey = getItemKey(item.payload);
642
+ initialState[itemKey] = {
643
+ data: item.data,
644
+ error: null,
645
+ status: "success",
646
+ payload: item.payload,
647
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
648
+ wasLoaded: true
649
+ };
650
+ }
651
+ }
652
+ return initialState;
653
+ }
645
654
  });
646
655
  function getItemKey(params) {
647
656
  return getCacheId(
@@ -780,6 +789,13 @@ function newTSDFCollectionStore({
780
789
  );
781
790
  invalidationWasTriggered.delete(itemKey);
782
791
  storeEvents.emit("invalidateData", { priority, itemKey });
792
+ if (item.data) {
793
+ onInvalidate?.({
794
+ priority,
795
+ payload: item.payload,
796
+ itemState: item.data
797
+ });
798
+ }
783
799
  }
784
800
  }
785
801
  function getItemState(params) {
@@ -1044,6 +1060,31 @@ function findAndMap(arr, findFn) {
1044
1060
  return void 0;
1045
1061
  }
1046
1062
 
1063
+ // src/utils/sortBy.ts
1064
+ function sortBy(arr, getPriority, { order = "asc" } = {}) {
1065
+ return [...arr].sort((a, b) => {
1066
+ const _aPriority = getPriority(a);
1067
+ const _bPriority = getPriority(b);
1068
+ const aPriority = Array.isArray(_aPriority) ? _aPriority : [_aPriority];
1069
+ const bPriority = Array.isArray(_bPriority) ? _bPriority : [_bPriority];
1070
+ for (let i = 0; i < aPriority.length; i++) {
1071
+ const levelOrder = typeof order === "string" ? order : order[i] ?? "asc";
1072
+ const aP = aPriority[i] ?? 0;
1073
+ const bP = bPriority[i] ?? 0;
1074
+ if (aP === bP) {
1075
+ continue;
1076
+ }
1077
+ if (bP === Infinity || aP === -Infinity || aP < bP) {
1078
+ return levelOrder === "asc" ? -1 : 1;
1079
+ }
1080
+ if (aP === Infinity || bP === -Infinity || aP > bP) {
1081
+ return levelOrder === "asc" ? 1 : -1;
1082
+ }
1083
+ }
1084
+ return 0;
1085
+ });
1086
+ }
1087
+
1047
1088
  // src/listQueryStore.ts
1048
1089
  var noFetchFnError = "No fetchItemFn was provided";
1049
1090
  function newTSDFListQueryStore({
@@ -1052,43 +1093,49 @@ function newTSDFListQueryStore({
1052
1093
  fetchItemFn,
1053
1094
  errorNormalizer,
1054
1095
  defaultQuerySize = 50,
1055
- initialData,
1096
+ getInitialData,
1056
1097
  disableRefetchOnMount: globalDisableRefetchOnMount,
1057
1098
  lowPriorityThrottleMs,
1058
1099
  disableInitialDataInvalidation,
1059
1100
  mediumPriorityThrottleMs,
1060
1101
  dynamicRealtimeThrottleMs,
1061
- syncMutationsAndInvalidations
1102
+ syncMutationsAndInvalidations,
1103
+ optimisticListUpdates,
1104
+ onInvalidateItem,
1105
+ onInvalidateQuery
1062
1106
  }) {
1063
- const initialState = { items: {}, queries: {}, itemQueries: {} };
1064
- if (initialData) {
1065
- for (const { payload, data } of initialData.items) {
1066
- const itemKey = getItemKey(payload);
1067
- initialState.items[itemKey] = data;
1068
- initialState.itemQueries[itemKey] = {
1069
- error: null,
1070
- status: "success",
1071
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1072
- wasLoaded: true,
1073
- payload
1074
- };
1075
- }
1076
- for (const { payload, items, hasMore } of initialData.queries) {
1077
- const queryKey = getQueryKey(payload);
1078
- initialState.queries[queryKey] = {
1079
- error: null,
1080
- status: "success",
1081
- refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1082
- wasLoaded: true,
1083
- payload,
1084
- items,
1085
- hasMore
1086
- };
1087
- }
1088
- }
1089
1107
  const store = new Store3({
1090
1108
  debugName,
1091
- state: initialState
1109
+ state: () => {
1110
+ const initialState = { items: {}, queries: {}, itemQueries: {} };
1111
+ const initialData = getInitialData?.();
1112
+ if (initialData) {
1113
+ for (const { payload, data } of initialData.items) {
1114
+ const itemKey = getItemKey(payload);
1115
+ initialState.items[itemKey] = data;
1116
+ initialState.itemQueries[itemKey] = {
1117
+ error: null,
1118
+ status: "success",
1119
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1120
+ wasLoaded: true,
1121
+ payload
1122
+ };
1123
+ }
1124
+ for (const { payload, items, hasMore } of initialData.queries) {
1125
+ const queryKey = getQueryKey(payload);
1126
+ initialState.queries[queryKey] = {
1127
+ error: null,
1128
+ status: "success",
1129
+ refetchOnMount: disableInitialDataInvalidation ? false : "lowPriority",
1130
+ wasLoaded: true,
1131
+ payload,
1132
+ items,
1133
+ hasMore
1134
+ };
1135
+ }
1136
+ }
1137
+ return initialState;
1138
+ }
1092
1139
  });
1093
1140
  function getQueryKey(params) {
1094
1141
  return getCacheId(params);
@@ -1332,7 +1379,7 @@ function newTSDFListQueryStore({
1332
1379
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
1333
1380
  function invalidateQuery(queryPayload, priority = "highPriority", ignoreInvalidationSync = false) {
1334
1381
  const queriesKey = getQueriesKeyArray(queryPayload);
1335
- for (const { key } of queriesKey) {
1382
+ for (const { key, payload } of queriesKey) {
1336
1383
  const queryState = store.state.queries[key];
1337
1384
  if (!queryState)
1338
1385
  continue;
@@ -1351,6 +1398,7 @@ function newTSDFListQueryStore({
1351
1398
  );
1352
1399
  queryInvalidationWasTriggered.delete(key);
1353
1400
  storeEvents.emit("invalidateQuery", { priority, queryKey: key });
1401
+ onInvalidateQuery?.(payload, priority);
1354
1402
  }
1355
1403
  if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1356
1404
  invalidateItem(
@@ -1634,7 +1682,7 @@ function newTSDFListQueryStore({
1634
1682
  throw new Error(noFetchFnError);
1635
1683
  }
1636
1684
  const itemsKey = getItemsKeyArray(itemId);
1637
- for (const { itemKey } of itemsKey) {
1685
+ for (const { itemKey, payload } of itemsKey) {
1638
1686
  const item = store.state.itemQueries[itemKey];
1639
1687
  if (!item)
1640
1688
  continue;
@@ -1653,6 +1701,16 @@ function newTSDFListQueryStore({
1653
1701
  );
1654
1702
  itemInvalidationWasTriggered.delete(itemKey);
1655
1703
  storeEvents.emit("invalidateItem", { priority, itemKey });
1704
+ if (onInvalidateItem) {
1705
+ const itemState = store.state.items[itemKey];
1706
+ if (itemState) {
1707
+ onInvalidateItem({
1708
+ priority,
1709
+ itemState,
1710
+ payload
1711
+ });
1712
+ }
1713
+ }
1656
1714
  }
1657
1715
  if (syncMutationsAndInvalidations && !ignoreInvalidationSync) {
1658
1716
  invalidateQuery(
@@ -1885,6 +1943,9 @@ function newTSDFListQueryStore({
1885
1943
  }
1886
1944
  }
1887
1945
  });
1946
+ if (someItemWasUpdated) {
1947
+ applyOptimisticListUpdates(itemKeys.map((i) => i.itemKey));
1948
+ }
1888
1949
  if (ifNothingWasUpdated && !someItemWasUpdated) {
1889
1950
  ifNothingWasUpdated();
1890
1951
  }
@@ -1893,48 +1954,134 @@ function newTSDFListQueryStore({
1893
1954
  );
1894
1955
  return someItemWasUpdated;
1895
1956
  }
1957
+ function applyOptimisticListUpdates(itemKeys) {
1958
+ if (!optimisticListUpdates)
1959
+ return;
1960
+ const queriesToInvalidate = [];
1961
+ store.produceState((draftState) => {
1962
+ for (const itemKey of itemKeys) {
1963
+ const item = draftState.items[itemKey];
1964
+ if (!item)
1965
+ continue;
1966
+ for (const {
1967
+ queries,
1968
+ filterItem,
1969
+ appendNewTo = "end",
1970
+ invalidateQueries,
1971
+ sort
1972
+ } of optimisticListUpdates) {
1973
+ const relatedFilterQueries = getQueriesKeyArray(queries);
1974
+ for (const { key: queryKey, payload } of relatedFilterQueries) {
1975
+ const queryState = draftState.queries[queryKey];
1976
+ if (filterItem) {
1977
+ const itemShouldBeIncluded = filterItem(item);
1978
+ if (itemShouldBeIncluded === null)
1979
+ continue;
1980
+ if (itemShouldBeIncluded) {
1981
+ if (!queryState) {
1982
+ draftState.queries[queryKey] = {
1983
+ status: "success",
1984
+ items: [itemKey],
1985
+ error: null,
1986
+ hasMore: false,
1987
+ payload,
1988
+ refetchOnMount: "lowPriority",
1989
+ wasLoaded: true
1990
+ };
1991
+ continue;
1992
+ }
1993
+ if (queryState.items.includes(itemKey))
1994
+ continue;
1995
+ if (invalidateQueries)
1996
+ queriesToInvalidate.push(payload);
1997
+ if (appendNewTo === "end") {
1998
+ queryState.items.push(itemKey);
1999
+ } else {
2000
+ queryState.items.unshift(itemKey);
2001
+ }
2002
+ } else {
2003
+ if (!queryState)
2004
+ continue;
2005
+ const itemIndex = queryState.items.indexOf(itemKey);
2006
+ if (itemIndex !== -1) {
2007
+ if (invalidateQueries)
2008
+ queriesToInvalidate.push(queryState.payload);
2009
+ queryState.items.splice(itemIndex, 1);
2010
+ }
2011
+ }
2012
+ }
2013
+ if (sort) {
2014
+ if (!queryState)
2015
+ continue;
2016
+ const queryHasItem = queryState.items.includes(itemKey);
2017
+ if (!queryHasItem)
2018
+ continue;
2019
+ queryState.items = sortBy(
2020
+ queryState.items,
2021
+ (itemId) => {
2022
+ const itemState = store.state.items[itemId];
2023
+ const itemPayload = store.state.itemQueries[itemId]?.payload;
2024
+ if (!itemState || !itemPayload)
2025
+ return Infinity;
2026
+ return sort.sortBy(itemState, itemPayload);
2027
+ },
2028
+ {
2029
+ order: sort.order
2030
+ }
2031
+ );
2032
+ }
2033
+ }
2034
+ }
2035
+ }
2036
+ });
2037
+ if (queriesToInvalidate.length)
2038
+ invalidateQuery(queriesToInvalidate);
2039
+ }
1896
2040
  function addItemToState(itemPayload, data, {
1897
2041
  addItemToQueries
1898
2042
  } = {}) {
1899
2043
  const itemKey = getItemKey(itemPayload);
1900
- store.produceState(
1901
- (draftState) => {
1902
- draftState.items[itemKey] = data;
1903
- draftState.itemQueries[itemKey] = {
1904
- status: "success",
1905
- wasLoaded: true,
1906
- refetchOnMount: false,
1907
- error: null,
1908
- payload: klona2(itemPayload)
1909
- };
1910
- if (addItemToQueries) {
1911
- const queries = getQueriesKeyArray(addItemToQueries.queries);
1912
- for (const { key } of queries) {
1913
- if (draftState.queries[key]) {
1914
- const queryState = draftState.queries[key];
1915
- if (!queryState)
1916
- continue;
1917
- if (queryState.items.includes(itemKey))
1918
- continue;
1919
- if (addItemToQueries.appendTo === "start") {
1920
- queryState.items.unshift(itemKey);
1921
- } else if (addItemToQueries.appendTo === "end") {
1922
- queryState.items.push(itemKey);
1923
- } else {
1924
- const index = addItemToQueries.appendTo(
1925
- filterAndMap(
1926
- queryState.items,
1927
- (itemKey2, ignore) => draftState.itemQueries[itemKey2]?.payload || ignore
1928
- )
1929
- );
1930
- queryState.items.splice(index, 0, itemKey);
2044
+ store.batch(() => {
2045
+ store.produceState(
2046
+ (draftState) => {
2047
+ draftState.items[itemKey] = data;
2048
+ draftState.itemQueries[itemKey] = {
2049
+ status: "success",
2050
+ wasLoaded: true,
2051
+ refetchOnMount: false,
2052
+ error: null,
2053
+ payload: klona2(itemPayload)
2054
+ };
2055
+ if (addItemToQueries) {
2056
+ const queries = getQueriesKeyArray(addItemToQueries.queries);
2057
+ for (const { key } of queries) {
2058
+ if (draftState.queries[key]) {
2059
+ const queryState = draftState.queries[key];
2060
+ if (!queryState)
2061
+ continue;
2062
+ if (queryState.items.includes(itemKey))
2063
+ continue;
2064
+ if (addItemToQueries.appendTo === "start") {
2065
+ queryState.items.unshift(itemKey);
2066
+ } else if (addItemToQueries.appendTo === "end") {
2067
+ queryState.items.push(itemKey);
2068
+ } else {
2069
+ const index = addItemToQueries.appendTo(
2070
+ filterAndMap(
2071
+ queryState.items,
2072
+ (itemKey2, ignore) => draftState.itemQueries[itemKey2]?.payload || ignore
2073
+ )
2074
+ );
2075
+ queryState.items.splice(index, 0, itemKey);
2076
+ }
1931
2077
  }
1932
2078
  }
1933
2079
  }
1934
- }
1935
- },
1936
- { action: { type: "create-item-state", itemPayload } }
1937
- );
2080
+ },
2081
+ { action: { type: "create-item-state", itemPayload } }
2082
+ );
2083
+ applyOptimisticListUpdates([itemKey]);
2084
+ });
1938
2085
  }
1939
2086
  function deleteItemState(itemId) {
1940
2087
  const itemsId = getItemsKeyArray(itemId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "11.2.2",
3
+ "version": "12.2.0",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "MIT",
6
6
  "author": "Lucas Santos",
@@ -22,19 +22,6 @@
22
22
  "engines": {
23
23
  "node": ">=16.0.0"
24
24
  },
25
- "scripts": {
26
- "test": "vitest --ui --mode development",
27
- "test:changed": "vitest --changed --ui --mode development",
28
- "lint": "pnpm tsc && pnpm eslint && pnpm format",
29
- "eslint": "CI=true eslint --color --ext .jsx,.js,.ts,.tsx src/ test/",
30
- "format": "prettier --write src/**/*.ts",
31
- "tsc": "tsc -p tsconfig.prod.json",
32
- "tsc:watch": "tsc -p tsconfig.prod.json --watch",
33
- "test:run": "vitest run",
34
- "build": "pnpm test:run && pnpm lint && pnpm build:no-test",
35
- "build:no-test": "tsup --dts",
36
- "npm-publish": "./scripts/check-if-is-sync.sh && pnpm build && npm publish"
37
- },
38
25
  "devDependencies": {
39
26
  "@lucasols/eslint-plugin-extended-lint": "^0.10.0",
40
27
  "@testing-library/jest-dom": "^5.17.0",
@@ -72,5 +59,18 @@
72
59
  "peerDependencies": {
73
60
  "react": "^18.0.0",
74
61
  "react-dom": "^18.0.0"
62
+ },
63
+ "scripts": {
64
+ "test": "vitest --ui --mode development",
65
+ "test:changed": "vitest --changed --ui --mode development",
66
+ "lint": "pnpm tsc && pnpm eslint && pnpm format",
67
+ "eslint": "CI=true eslint --color --ext .jsx,.js,.ts,.tsx src/ test/",
68
+ "format": "prettier --write src/**/*.ts",
69
+ "tsc": "tsc -p tsconfig.prod.json",
70
+ "tsc:watch": "tsc -p tsconfig.prod.json --watch",
71
+ "test:run": "vitest run",
72
+ "build": "pnpm test:run && pnpm lint && pnpm build:no-test",
73
+ "build:no-test": "tsup --dts",
74
+ "pre-publish": "./scripts/check-if-is-sync.sh && pnpm build"
75
75
  }
76
- }
76
+ }