@promoboxx/use-filter 1.0.2 → 1.0.5

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/src/useFilter.ts DELETED
@@ -1,280 +0,0 @@
1
- import { useEffect, useRef, useCallback, useState } from 'react'
2
-
3
- import buildDefaultFilterInfo from './lib/buildDefaultFilterInfo'
4
- import getOffsetFromPage from './lib/getOffsetFromPage'
5
- import getPageFromOffset from './lib/getPageFromOffset'
6
- import shallowEqual from './lib/shallowEqual'
7
- import { getFilterStore } from './store'
8
-
9
- type MaybePromise<T> = T | Promise<T>
10
-
11
- interface UseFilterOptions<TFilter, TResult> {
12
- defaultFilterInfo?: Partial<FilterInfo<TFilter>>
13
- shouldForceRunOnMount?: boolean
14
- onChange: (
15
- filterInfo: FilterInfo<TFilter>,
16
- ) => MaybePromise<UseFilterOnChangeResult<TFilter, TResult>>
17
- debounceDuration?: number
18
- }
19
-
20
- function useFilter<T>(namespace: string, options: UseFilterOptions<T, any>) {
21
- const [filterInfo, setFilterInfoState] = useState<
22
- FilterInfo<T> | null | undefined
23
- >(() => getFilterStore().getFilter(namespace))
24
-
25
- const setFilterInfo = useCallback(
26
- (filterInfo: FilterInfo<T>, skipFetch = false) => {
27
- setFilterInfoState((previousFilterInfo) => {
28
- let lastRefreshAt: number | undefined
29
-
30
- if (skipFetch) {
31
- lastRefreshAt = previousFilterInfo?.lastRefreshAt
32
- } else {
33
- lastRefreshAt = new Date().getTime()
34
- }
35
-
36
- if (!lastRefreshAt) {
37
- throw new Error()
38
- }
39
-
40
- return {
41
- ...filterInfo,
42
- lastRefreshAt,
43
- }
44
- })
45
- },
46
- [],
47
- )
48
-
49
- const ctxRef = useRef<
50
- Pick<
51
- UseFilterOptions<T, any>,
52
- 'onChange' | 'debounceDuration' | 'defaultFilterInfo'
53
- > & { namespace: typeof namespace }
54
- >({
55
- namespace,
56
- onChange: options.onChange,
57
- debounceDuration: options.debounceDuration,
58
- defaultFilterInfo: options.defaultFilterInfo,
59
- })
60
-
61
- const [isLoading, setIsLoading] = useState(!filterInfo)
62
- const doesFilterExist = useRef(!!filterInfo)
63
- const lastRefreshAtRef = useRef(
64
- // if shouldForceRunOnMount is set, always use -1
65
- // otherwise, try grabbing lastRefreshAt
66
- // then, just use -1 cause there's no other option
67
- options.shouldForceRunOnMount
68
- ? -1
69
- : filterInfo
70
- ? filterInfo.lastRefreshAt
71
- : -1,
72
- )
73
-
74
- // Call onChange when data changes.
75
- useEffect(() => {
76
- setIsLoading(true)
77
-
78
- // If there is no existing filter info, set it to the defaults and return.
79
- // This same effect will trigger next go.
80
- if (!filterInfo) {
81
- setFilterInfo(buildDefaultFilterInfo(ctxRef.current.defaultFilterInfo))
82
- return
83
- }
84
-
85
- // If the lastRefreshAt hasn't changed, don't make a request.
86
- if (lastRefreshAtRef.current === filterInfo.lastRefreshAt) {
87
- setIsLoading(false)
88
- return
89
- }
90
-
91
- const timeout = setTimeout(
92
- () => {
93
- lastRefreshAtRef.current = filterInfo.lastRefreshAt
94
- const response = ctxRef.current.onChange(filterInfo)
95
- getFilterStore().saveFilter(namespace, filterInfo)
96
-
97
- if (!response) {
98
- setIsLoading(false)
99
- return
100
- }
101
-
102
- function handleResponse(response?: UseFilterOnChangeResult<T, any>) {
103
- if (!filterInfo) {
104
- return
105
- }
106
-
107
- if (!response) {
108
- return
109
- }
110
-
111
- if (response.filterInfo) {
112
- const extra: Partial<FilterInfo<T>> = {}
113
- const {
114
- page,
115
- offset,
116
- totalResults,
117
- pageSize,
118
- ...filterInfoFromResponse
119
- } = response.filterInfo
120
-
121
- const pageSizeNumber = Number(pageSize || filterInfo.pageSize)
122
-
123
- if (page != null && offset == null) {
124
- extra.offset = getOffsetFromPage(page, pageSizeNumber)
125
- extra.page = page
126
- // If there's an offset but no page, set the page.
127
- } else if (page == null && offset != null) {
128
- const offsetNumber = Number(offset)
129
- extra.offset = offsetNumber
130
- extra.page = getPageFromOffset(offsetNumber, pageSizeNumber)
131
- }
132
-
133
- if (totalResults) {
134
- extra.totalResults = Number(totalResults)
135
- extra.totalPages = Math.ceil(extra.totalResults / pageSizeNumber)
136
- }
137
-
138
- // TODO Don't do anther request here????
139
- setFilterInfo(
140
- {
141
- ...filterInfo,
142
- ...filterInfoFromResponse,
143
- ...extra,
144
- },
145
- true,
146
- )
147
- }
148
- }
149
-
150
- if (isPromise(response)) {
151
- response.then(handleResponse).finally(() => setIsLoading(false))
152
- } else {
153
- handleResponse(response)
154
- setIsLoading(false)
155
- }
156
- },
157
- ctxRef.current.debounceDuration != null
158
- ? ctxRef.current.debounceDuration
159
- : 500,
160
- )
161
-
162
- return () => {
163
- if (timeout) {
164
- clearTimeout(timeout)
165
- }
166
- }
167
- }, [filterInfo, setFilterInfo, namespace])
168
-
169
- return {
170
- isLoading,
171
- doesFilterExist: doesFilterExist.current,
172
- filterInfo: filterInfo || buildDefaultFilterInfo(options.defaultFilterInfo),
173
-
174
- updateFilter(filter: T) {
175
- if (!filterInfo) {
176
- throw new Error()
177
- }
178
-
179
- const nextFilter = {
180
- ...filterInfo.filter,
181
- ...filter,
182
- }
183
-
184
- if (shallowEqual(filterInfo.filter, nextFilter)) {
185
- return
186
- }
187
-
188
- setFilterInfo({
189
- ...filterInfo,
190
- offset: 0,
191
- page: 1,
192
- totalResults: 1,
193
- totalPages: 1,
194
- filter: nextFilter,
195
- })
196
- },
197
-
198
- resetFilter() {
199
- setFilterInfo(buildDefaultFilterInfo(options.defaultFilterInfo))
200
- },
201
-
202
- setOffset(offset: number | string) {
203
- if (!filterInfo) {
204
- throw new Error()
205
- }
206
-
207
- const offsetNumber = Number(offset)
208
-
209
- setFilterInfo({
210
- ...filterInfo,
211
- offset: offsetNumber,
212
- page: getPageFromOffset(offsetNumber, filterInfo.pageSize),
213
- })
214
- },
215
-
216
- setPage(page: number | string) {
217
- if (!filterInfo) {
218
- throw new Error()
219
- }
220
-
221
- const pageNumber = Number(page)
222
-
223
- setFilterInfo({
224
- ...filterInfo,
225
- offset: getOffsetFromPage(pageNumber, filterInfo.pageSize),
226
- page: pageNumber,
227
- })
228
- },
229
-
230
- setSort(sort: string | undefined) {
231
- if (!filterInfo) {
232
- throw new Error()
233
- }
234
-
235
- setFilterInfo({
236
- ...filterInfo,
237
- sort,
238
- })
239
- },
240
-
241
- forceRefresh() {
242
- if (!filterInfo) {
243
- throw new Error()
244
- }
245
-
246
- setFilterInfo({
247
- ...filterInfo,
248
- lastRefreshAt: new Date().getTime(),
249
- })
250
- },
251
- }
252
- }
253
-
254
- export default useFilter
255
-
256
- export interface FilterInfo<TFilter> {
257
- filter: TFilter
258
- offset: number
259
- page: number
260
- sort?: string
261
- pageSize: number
262
- lastRefreshAt: number
263
- totalResults: number
264
- totalPages: number
265
- }
266
-
267
- type UseFilterOnChangeResult<TFilter, TResult> = void | {
268
- filterInfo?: Partial<
269
- Omit<FilterInfo<TFilter>, 'totalResults' | 'offset' | 'pageSize'> & {
270
- totalResults: string | number
271
- offset: string | number
272
- pageSize: string | number
273
- }
274
- >
275
- data?: TResult
276
- }
277
-
278
- function isPromise(t?: any): t is Promise<any> {
279
- return !!t?.then
280
- }
package/tsconfig.json DELETED
@@ -1,75 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig.json to read more about this file */
4
-
5
- /* Basic Options */
6
- // "incremental": true, /* Enable incremental compilation */
7
- "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
8
- "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
9
- "lib": [
10
- "DOM",
11
- "es2018"
12
- ] /* Specify library files to be included in the compilation. */,
13
- // "allowJs": true, /* Allow javascript files to be compiled. */
14
- // "checkJs": true, /* Report errors in .js files. */
15
- "jsx": "react" /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */,
16
- // "declaration": true, /* Generates corresponding '.d.ts' file. */
17
- // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
18
- // "sourceMap": true, /* Generates corresponding '.map' file. */
19
- // "outFile": "./", /* Concatenate and emit output to single file. */
20
- "outDir": "./dist" /* Redirect output structure to the directory. */,
21
- "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
22
- // "composite": true, /* Enable project compilation */
23
- // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
24
- // "removeComments": true, /* Do not emit comments to output. */
25
- // "noEmit": true, /* Do not emit outputs. */
26
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
27
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
28
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
29
-
30
- /* Strict Type-Checking Options */
31
- "strict": true /* Enable all strict type-checking options. */,
32
- // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
33
- // "strictNullChecks": true, /* Enable strict null checks. */
34
- // "strictFunctionTypes": true, /* Enable strict checking of function types. */
35
- // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
36
- // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
37
- // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
38
- // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
39
-
40
- /* Additional Checks */
41
- // "noUnusedLocals": true, /* Report errors on unused locals. */
42
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
43
- // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
44
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
45
- // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
46
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
47
- // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
48
-
49
- /* Module Resolution Options */
50
- // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
51
- // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
52
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
53
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
54
- // "typeRoots": [], /* List of folders to include type definitions from. */
55
- // "types": [], /* Type declaration files to be included in compilation. */
56
- // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
57
- "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
58
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
59
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
60
-
61
- /* Source Map Options */
62
- // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
63
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
64
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
65
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
66
-
67
- /* Experimental Options */
68
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
69
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
70
-
71
- /* Advanced Options */
72
- "skipLibCheck": true /* Skip type checking of declaration files. */,
73
- "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
74
- }
75
- }