@promoboxx/use-filter 1.0.2
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/.eslintrc.js +19 -0
- package/.github/workflows/main.yml +32 -0
- package/.vscode/settings.json +3 -0
- package/CHANGELOG.md +12 -0
- package/Makefile +31 -0
- package/jest.config.js +196 -0
- package/package.json +25 -0
- package/prettier.config.js +1 -0
- package/src/lib/buildDefaultFilterInfo.ts +35 -0
- package/src/lib/getOffsetFromPage.ts +5 -0
- package/src/lib/getPageFromOffset.ts +5 -0
- package/src/lib/shallowEqual.test.ts +71 -0
- package/src/lib/shallowEqual.ts +26 -0
- package/src/store/index.ts +21 -0
- package/src/store/memoryStore.ts +19 -0
- package/src/useFilter.test.tsx +449 -0
- package/src/useFilter.ts +280 -0
- package/tsconfig.json +75 -0
package/.eslintrc.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
extends: [
|
|
3
|
+
// Base config applies to all projects.
|
|
4
|
+
'@promoboxx/eslint-config',
|
|
5
|
+
// If the project uses prettier:
|
|
6
|
+
'@promoboxx/eslint-config/prettier',
|
|
7
|
+
// If the project uses jest:
|
|
8
|
+
'@promoboxx/eslint-config/jest',
|
|
9
|
+
// If the project uses react:
|
|
10
|
+
'@promoboxx/eslint-config/react',
|
|
11
|
+
// If the project uses graphql:
|
|
12
|
+
// '@promoboxx/eslint-config/graphql',
|
|
13
|
+
],
|
|
14
|
+
parserOptions: {
|
|
15
|
+
// If the project uses graphql, set the path/url to your schema below.
|
|
16
|
+
// skipGraphQLConfig: true,
|
|
17
|
+
// schema: 'node_modules/@promoboxx/graphql-server-types/graphql.schema.json',
|
|
18
|
+
},
|
|
19
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
on: push
|
|
3
|
+
|
|
4
|
+
jobs:
|
|
5
|
+
ci:
|
|
6
|
+
runs-on: ubuntu-latest
|
|
7
|
+
|
|
8
|
+
steps:
|
|
9
|
+
- uses: actions/checkout@v2
|
|
10
|
+
|
|
11
|
+
- name: Cache node modules
|
|
12
|
+
uses: actions/cache@v2
|
|
13
|
+
with:
|
|
14
|
+
path: |
|
|
15
|
+
~/.npm
|
|
16
|
+
**/node_modules
|
|
17
|
+
key: ${{ runner.os }}-node-modules-${{ hashFiles('**/package-lock.json') }}
|
|
18
|
+
|
|
19
|
+
# https://github.community/t/github-actions-bot-email-address/17204/5
|
|
20
|
+
- name: Prep for git push
|
|
21
|
+
run: |
|
|
22
|
+
git config --local user.name "${{secrets.GH_BOT_NAME}}"
|
|
23
|
+
git config --local user.email "41898282+${{secrets.GH_BOT_NAME}}@users.noreply.github.com"
|
|
24
|
+
git remote set-url origin "https://${{secrets.GH_BOT_NAME}}:${{secrets.GH_TOKEN}}@github.com/${GITHUB_REPOSITORY}.git"
|
|
25
|
+
|
|
26
|
+
- name: Prep NPM
|
|
27
|
+
run: npm config set '//registry.npmjs.org/:_authToken' "${{secrets.NPM_TOKEN}}"
|
|
28
|
+
|
|
29
|
+
- run: make prepare-env
|
|
30
|
+
- run: make test
|
|
31
|
+
- run: make build
|
|
32
|
+
- run: make deploy
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
|
4
|
+
|
|
5
|
+
### 1.0.2 (2021-07-16)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
### Bug Fixes
|
|
9
|
+
|
|
10
|
+
* proper secrets syntax ([afc9fe9](https://github.com/promoboxx/use-filter/commit/afc9fe9b177dda2961d82858ef43cc481f762950))
|
|
11
|
+
|
|
12
|
+
### 1.0.1 (2021-07-16)
|
package/Makefile
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
prepare-env:
|
|
2
|
+
ifeq ($(CI),true)
|
|
3
|
+
npm ci --ignore-scripts
|
|
4
|
+
else
|
|
5
|
+
npm install
|
|
6
|
+
endif
|
|
7
|
+
|
|
8
|
+
prepare-when-local:
|
|
9
|
+
ifneq ($(CI),true)
|
|
10
|
+
$(MAKE) prepare-env
|
|
11
|
+
endif
|
|
12
|
+
|
|
13
|
+
start: test
|
|
14
|
+
|
|
15
|
+
build: prepare-when-local
|
|
16
|
+
rm -rf dist/
|
|
17
|
+
npx tsc
|
|
18
|
+
|
|
19
|
+
test: prepare-when-local
|
|
20
|
+
ifeq ($(CI),true)
|
|
21
|
+
npx jest --ci
|
|
22
|
+
else
|
|
23
|
+
npx jest --watch
|
|
24
|
+
endif
|
|
25
|
+
|
|
26
|
+
deploy:
|
|
27
|
+
ifeq ($(GITHUB_REF),refs/heads/main)
|
|
28
|
+
npx standard-version
|
|
29
|
+
git push origin --tags HEAD
|
|
30
|
+
npm publish
|
|
31
|
+
endif
|
package/jest.config.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* For a detailed explanation regarding each configuration property and type check, visit:
|
|
3
|
+
* https://jestjs.io/docs/configuration
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const config = {
|
|
7
|
+
// All imported modules in your tests should be mocked automatically
|
|
8
|
+
// automock: false,
|
|
9
|
+
|
|
10
|
+
// Stop running tests after `n` failures
|
|
11
|
+
// bail: 0,
|
|
12
|
+
|
|
13
|
+
// The directory where Jest should store its cached dependency information
|
|
14
|
+
// cacheDirectory: "/tmp/jest_rs",
|
|
15
|
+
|
|
16
|
+
// Automatically clear mock calls and instances between every test
|
|
17
|
+
clearMocks: true,
|
|
18
|
+
|
|
19
|
+
// Indicates whether the coverage information should be collected while executing the test
|
|
20
|
+
// collectCoverage: false,
|
|
21
|
+
|
|
22
|
+
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
|
23
|
+
// collectCoverageFrom: undefined,
|
|
24
|
+
|
|
25
|
+
// The directory where Jest should output its coverage files
|
|
26
|
+
// coverageDirectory: undefined,
|
|
27
|
+
|
|
28
|
+
// An array of regexp pattern strings used to skip coverage collection
|
|
29
|
+
// coveragePathIgnorePatterns: [
|
|
30
|
+
// "/node_modules/"
|
|
31
|
+
// ],
|
|
32
|
+
|
|
33
|
+
// Indicates which provider should be used to instrument code for coverage
|
|
34
|
+
coverageProvider: 'v8',
|
|
35
|
+
|
|
36
|
+
// A list of reporter names that Jest uses when writing coverage reports
|
|
37
|
+
// coverageReporters: [
|
|
38
|
+
// "json",
|
|
39
|
+
// "text",
|
|
40
|
+
// "lcov",
|
|
41
|
+
// "clover"
|
|
42
|
+
// ],
|
|
43
|
+
|
|
44
|
+
// An object that configures minimum threshold enforcement for coverage results
|
|
45
|
+
// coverageThreshold: undefined,
|
|
46
|
+
|
|
47
|
+
// A path to a custom dependency extractor
|
|
48
|
+
// dependencyExtractor: undefined,
|
|
49
|
+
|
|
50
|
+
// Make calling deprecated APIs throw helpful error messages
|
|
51
|
+
// errorOnDeprecated: false,
|
|
52
|
+
|
|
53
|
+
// Force coverage collection from ignored files using an array of glob patterns
|
|
54
|
+
// forceCoverageMatch: [],
|
|
55
|
+
|
|
56
|
+
// A path to a module which exports an async function that is triggered once before all test suites
|
|
57
|
+
// globalSetup: undefined,
|
|
58
|
+
|
|
59
|
+
// A path to a module which exports an async function that is triggered once after all test suites
|
|
60
|
+
// globalTeardown: undefined,
|
|
61
|
+
|
|
62
|
+
// A set of global variables that need to be available in all test environments
|
|
63
|
+
// globals: {},
|
|
64
|
+
|
|
65
|
+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
|
66
|
+
// maxWorkers: "50%",
|
|
67
|
+
|
|
68
|
+
// An array of directory names to be searched recursively up from the requiring module's location
|
|
69
|
+
// moduleDirectories: [
|
|
70
|
+
// "node_modules"
|
|
71
|
+
// ],
|
|
72
|
+
|
|
73
|
+
// An array of file extensions your modules use
|
|
74
|
+
// moduleFileExtensions: [
|
|
75
|
+
// "js",
|
|
76
|
+
// "jsx",
|
|
77
|
+
// "ts",
|
|
78
|
+
// "tsx",
|
|
79
|
+
// "json",
|
|
80
|
+
// "node"
|
|
81
|
+
// ],
|
|
82
|
+
|
|
83
|
+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
|
84
|
+
// moduleNameMapper: {},
|
|
85
|
+
|
|
86
|
+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
|
87
|
+
// modulePathIgnorePatterns: [],
|
|
88
|
+
|
|
89
|
+
// Activates notifications for test results
|
|
90
|
+
// notify: false,
|
|
91
|
+
|
|
92
|
+
// An enum that specifies notification mode. Requires { notify: true }
|
|
93
|
+
// notifyMode: "failure-change",
|
|
94
|
+
|
|
95
|
+
// A preset that is used as a base for Jest's configuration
|
|
96
|
+
preset: 'ts-jest/presets/js-with-ts',
|
|
97
|
+
|
|
98
|
+
// Run tests from one or more projects
|
|
99
|
+
// projects: undefined,
|
|
100
|
+
|
|
101
|
+
// Use this configuration option to add custom reporters to Jest
|
|
102
|
+
// reporters: undefined,
|
|
103
|
+
|
|
104
|
+
// Automatically reset mock state between every test
|
|
105
|
+
// resetMocks: false,
|
|
106
|
+
|
|
107
|
+
// Reset the module registry before running each individual test
|
|
108
|
+
// resetModules: false,
|
|
109
|
+
|
|
110
|
+
// A path to a custom resolver
|
|
111
|
+
// resolver: undefined,
|
|
112
|
+
|
|
113
|
+
// Automatically restore mock state between every test
|
|
114
|
+
// restoreMocks: false,
|
|
115
|
+
|
|
116
|
+
// The root directory that Jest should scan for tests and modules within
|
|
117
|
+
// rootDir: undefined,
|
|
118
|
+
|
|
119
|
+
// A list of paths to directories that Jest should use to search for files in
|
|
120
|
+
// roots: [
|
|
121
|
+
// "<rootDir>"
|
|
122
|
+
// ],
|
|
123
|
+
|
|
124
|
+
// Allows you to use a custom runner instead of Jest's default test runner
|
|
125
|
+
// runner: "jest-runner",
|
|
126
|
+
|
|
127
|
+
// The paths to modules that run some code to configure or set up the testing environment before each test
|
|
128
|
+
// setupFiles: [],
|
|
129
|
+
|
|
130
|
+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
|
131
|
+
// setupFilesAfterEnv: [],
|
|
132
|
+
|
|
133
|
+
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
|
134
|
+
// slowTestThreshold: 5,
|
|
135
|
+
|
|
136
|
+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
|
137
|
+
// snapshotSerializers: [],
|
|
138
|
+
|
|
139
|
+
// The test environment that will be used for testing
|
|
140
|
+
testEnvironment: 'jsdom',
|
|
141
|
+
|
|
142
|
+
// Options that will be passed to the testEnvironment
|
|
143
|
+
// testEnvironmentOptions: {},
|
|
144
|
+
|
|
145
|
+
// Adds a location field to test results
|
|
146
|
+
// testLocationInResults: false,
|
|
147
|
+
|
|
148
|
+
// The glob patterns Jest uses to detect test files
|
|
149
|
+
// testMatch: [
|
|
150
|
+
// "**/__tests__/**/*.[jt]s?(x)",
|
|
151
|
+
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
|
152
|
+
// ],
|
|
153
|
+
|
|
154
|
+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
|
155
|
+
// testPathIgnorePatterns: [
|
|
156
|
+
// "/node_modules/"
|
|
157
|
+
// ],
|
|
158
|
+
|
|
159
|
+
// The regexp pattern or array of patterns that Jest uses to detect test files
|
|
160
|
+
// testRegex: [],
|
|
161
|
+
|
|
162
|
+
// This option allows the use of a custom results processor
|
|
163
|
+
// testResultsProcessor: undefined,
|
|
164
|
+
|
|
165
|
+
// This option allows use of a custom test runner
|
|
166
|
+
// testRunner: "jest-circus/runner",
|
|
167
|
+
|
|
168
|
+
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
|
|
169
|
+
// testURL: "http://localhost",
|
|
170
|
+
|
|
171
|
+
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
|
|
172
|
+
// timers: "real",
|
|
173
|
+
|
|
174
|
+
// A map from regular expressions to paths to transformers
|
|
175
|
+
// transform: undefined,
|
|
176
|
+
|
|
177
|
+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
|
178
|
+
// transformIgnorePatterns: [
|
|
179
|
+
// "/node_modules/",
|
|
180
|
+
// "\\.pnp\\.[^\\/]+$"
|
|
181
|
+
// ],
|
|
182
|
+
|
|
183
|
+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
|
184
|
+
// unmockedModulePathPatterns: undefined,
|
|
185
|
+
|
|
186
|
+
// Indicates whether each individual test should be reported during the run
|
|
187
|
+
verbose: true,
|
|
188
|
+
|
|
189
|
+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
|
190
|
+
// watchPathIgnorePatterns: [],
|
|
191
|
+
|
|
192
|
+
// Whether to use watchman for file crawling
|
|
193
|
+
// watchman: true,
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = config
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@promoboxx/use-filter",
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [],
|
|
10
|
+
"author": "",
|
|
11
|
+
"license": "ISC",
|
|
12
|
+
"devDependencies": {
|
|
13
|
+
"@promoboxx/eslint-config": "^2.3.0",
|
|
14
|
+
"@testing-library/react": "^12.0.0",
|
|
15
|
+
"@types/jest": "^26.0.24",
|
|
16
|
+
"@types/react": "^17.0.14",
|
|
17
|
+
"eslint": "^7.30.0",
|
|
18
|
+
"jest": "^27.0.6",
|
|
19
|
+
"prettier": "^2.3.2",
|
|
20
|
+
"react": "^17.0.2",
|
|
21
|
+
"react-dom": "^17.0.2",
|
|
22
|
+
"ts-jest": "^27.0.3",
|
|
23
|
+
"typescript": "^4.3.5"
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
module.exports = require('@promoboxx/eslint-config/prettier.config')
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { FilterInfo } from '../useFilter'
|
|
2
|
+
|
|
3
|
+
import getOffsetFromPage from './getOffsetFromPage'
|
|
4
|
+
import getPageFromOffset from './getPageFromOffset'
|
|
5
|
+
|
|
6
|
+
function buildDefaultFilterInfo<T>(
|
|
7
|
+
filterInfo: Partial<FilterInfo<T>> = {},
|
|
8
|
+
): FilterInfo<T> {
|
|
9
|
+
const merged: FilterInfo<T> = {
|
|
10
|
+
// Cast here to work around "'T' could be instantiated with an arbitrary
|
|
11
|
+
// type which could be unrelated to '{}'"
|
|
12
|
+
filter: {} as T,
|
|
13
|
+
|
|
14
|
+
sort: undefined,
|
|
15
|
+
pageSize: 20,
|
|
16
|
+
lastRefreshAt: new Date().getTime(),
|
|
17
|
+
totalResults: 1,
|
|
18
|
+
totalPages: 1,
|
|
19
|
+
offset: 0,
|
|
20
|
+
page: 1,
|
|
21
|
+
...filterInfo,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// If there's a page but no offset, set the offset.
|
|
25
|
+
if (filterInfo.page != null && filterInfo.offset == null) {
|
|
26
|
+
merged.offset = getOffsetFromPage(filterInfo.page, merged.pageSize)
|
|
27
|
+
// If there's an offset but no page, set the page.
|
|
28
|
+
} else if (filterInfo.page == null && filterInfo.offset != null) {
|
|
29
|
+
merged.page = getPageFromOffset(filterInfo.offset, merged.pageSize)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return merged
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default buildDefaultFilterInfo
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import shallowEqual from './shallowEqual'
|
|
2
|
+
|
|
3
|
+
describe('shallowEqual', () => {
|
|
4
|
+
it('should return true if arguments fields are equal', () => {
|
|
5
|
+
expect(
|
|
6
|
+
shallowEqual({ a: 1, b: 2, c: undefined }, { a: 1, b: 2, c: undefined }),
|
|
7
|
+
).toBe(true)
|
|
8
|
+
|
|
9
|
+
expect(shallowEqual({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 })).toBe(true)
|
|
10
|
+
|
|
11
|
+
const o = {}
|
|
12
|
+
expect(shallowEqual({ a: 1, b: 2, c: o }, { a: 1, b: 2, c: o })).toBe(true)
|
|
13
|
+
|
|
14
|
+
const d = function () {
|
|
15
|
+
return 1
|
|
16
|
+
}
|
|
17
|
+
expect(shallowEqual({ a: 1, b: 2, c: o, d }, { a: 1, b: 2, c: o, d })).toBe(
|
|
18
|
+
true,
|
|
19
|
+
)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('should return false if arguments fields are different function identities', () => {
|
|
23
|
+
expect(
|
|
24
|
+
shallowEqual(
|
|
25
|
+
{
|
|
26
|
+
a: 1,
|
|
27
|
+
b: 2,
|
|
28
|
+
d() {
|
|
29
|
+
return 1
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
a: 1,
|
|
34
|
+
b: 2,
|
|
35
|
+
d() {
|
|
36
|
+
return 1
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
),
|
|
40
|
+
).toBe(false)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('should return false if first argument has too many keys', () => {
|
|
44
|
+
expect(shallowEqual({ a: 1, b: 2, c: 3 }, { a: 1, b: 2 })).toBe(false)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('should return false if second argument has too many keys', () => {
|
|
48
|
+
expect(shallowEqual({ a: 1, b: 2 }, { a: 1, b: 2, c: 3 })).toBe(false)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('should return false if arguments have different keys', () => {
|
|
52
|
+
expect(
|
|
53
|
+
shallowEqual({ a: 1, b: 2, c: undefined }, { a: 1, bb: 2, c: undefined }),
|
|
54
|
+
).toBe(false)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('should compare two NaN values', () => {
|
|
58
|
+
expect(shallowEqual(NaN, NaN)).toBe(true)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('should compare empty objects, with false', () => {
|
|
62
|
+
expect(shallowEqual({}, false)).toBe(false)
|
|
63
|
+
expect(shallowEqual(false, {})).toBe(false)
|
|
64
|
+
expect(shallowEqual([], false)).toBe(false)
|
|
65
|
+
expect(shallowEqual(false, [])).toBe(false)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('should compare two zero values', () => {
|
|
69
|
+
expect(shallowEqual(0, 0)).toBe(true)
|
|
70
|
+
})
|
|
71
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const shallowEqual = (objA: any, objB: any) => {
|
|
2
|
+
if (Object.is(objA, objB)) {
|
|
3
|
+
return true
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
if (typeof objA !== 'object' || !objA || typeof objB !== 'object' || !objB) {
|
|
7
|
+
return false
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const keysA = Object.keys(objA)
|
|
11
|
+
const keysB = Object.keys(objB)
|
|
12
|
+
|
|
13
|
+
if (keysA.length !== keysB.length) {
|
|
14
|
+
return false
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
for (const key of keysA) {
|
|
18
|
+
if (!Object.is(objA[key], objB[key])) {
|
|
19
|
+
return false
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return true
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export default shallowEqual
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { FilterInfo } from '../useFilter'
|
|
2
|
+
|
|
3
|
+
export interface FilterStore {
|
|
4
|
+
getFilter(namespace: string): FilterInfo<any> | null | undefined
|
|
5
|
+
saveFilter(namespace: string, filter: FilterInfo<any>): void
|
|
6
|
+
clear(): void
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
let store: FilterStore | undefined
|
|
10
|
+
|
|
11
|
+
export function setFilterStore(newStore: FilterStore) {
|
|
12
|
+
store = newStore
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function getFilterStore() {
|
|
16
|
+
if (!store) {
|
|
17
|
+
throw new Error('A store must be set with setFilterStore')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return store
|
|
21
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { FilterInfo } from '../useFilter'
|
|
2
|
+
|
|
3
|
+
import { FilterStore } from '.'
|
|
4
|
+
|
|
5
|
+
let filters: Record<string, FilterInfo<any>> = {}
|
|
6
|
+
|
|
7
|
+
const memoryStore: FilterStore = {
|
|
8
|
+
getFilter(namespace) {
|
|
9
|
+
return filters[namespace]
|
|
10
|
+
},
|
|
11
|
+
saveFilter(namespace, filter) {
|
|
12
|
+
filters[namespace] = filter
|
|
13
|
+
},
|
|
14
|
+
clear() {
|
|
15
|
+
filters = {}
|
|
16
|
+
},
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export default memoryStore
|
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
|
2
|
+
import React, { useState } from 'react'
|
|
3
|
+
|
|
4
|
+
import buildDefaultFilterInfo from './lib/buildDefaultFilterInfo'
|
|
5
|
+
import { setFilterStore } from './store'
|
|
6
|
+
import memoryStore from './store/memoryStore'
|
|
7
|
+
import useFilter, { FilterInfo } from './useFilter'
|
|
8
|
+
|
|
9
|
+
describe('useFilter', () => {
|
|
10
|
+
const defaultFilterInfo = buildDefaultFilterInfo({
|
|
11
|
+
filter: {
|
|
12
|
+
foo: 'bar',
|
|
13
|
+
},
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('calls on mount', async () => {
|
|
17
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
18
|
+
|
|
19
|
+
expect(onChangeMock).toHaveBeenCalledTimes(1)
|
|
20
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
21
|
+
expect.objectContaining({ filter: { foo: 'bar' } }),
|
|
22
|
+
)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('calls when data changes', async () => {
|
|
26
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
27
|
+
|
|
28
|
+
await actAndWait(() => {
|
|
29
|
+
fireEvent.click(screen.getByTestId('updateFilterButton'))
|
|
30
|
+
})
|
|
31
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
32
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
33
|
+
expect.objectContaining({ filter: { foo: '42' } }),
|
|
34
|
+
)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('uses shallowEqual be default', async () => {
|
|
38
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
39
|
+
|
|
40
|
+
await actAndWait(() => {
|
|
41
|
+
fireEvent.click(screen.getByTestId('updateFilterButton'))
|
|
42
|
+
})
|
|
43
|
+
await actAndWait(() => {
|
|
44
|
+
fireEvent.click(screen.getByTestId('updateFilterButton'))
|
|
45
|
+
})
|
|
46
|
+
// 2 is still the correct number of times, as there is one from the initial
|
|
47
|
+
// mount and the other from updateFilter.
|
|
48
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('can reset and keeps defaults', async () => {
|
|
52
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
53
|
+
|
|
54
|
+
await actAndWait(() => {
|
|
55
|
+
fireEvent.click(screen.getByTestId('resetFilterButton'))
|
|
56
|
+
})
|
|
57
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
58
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
59
|
+
expect.objectContaining({ filter: { foo: 'bar' } }),
|
|
60
|
+
)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('can setSort', async () => {
|
|
64
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
65
|
+
|
|
66
|
+
await actAndWait(() => {
|
|
67
|
+
fireEvent.click(screen.getByTestId('setSortButton'))
|
|
68
|
+
})
|
|
69
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
70
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
71
|
+
expect.objectContaining({ filter: { foo: 'bar' }, sort: 'foo:bar' }),
|
|
72
|
+
)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('renders the current filter', async () => {
|
|
76
|
+
await setup({ defaultFilterInfo })
|
|
77
|
+
|
|
78
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
79
|
+
expect.objectContaining({ filter: { foo: 'bar' } }),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
await actAndWait(() => {
|
|
83
|
+
fireEvent.click(screen.getByTestId('updateFilterButton'))
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
87
|
+
expect.objectContaining({ filter: { foo: '42' } }),
|
|
88
|
+
)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('handles onChange.filterInfo', async () => {
|
|
92
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
93
|
+
|
|
94
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
95
|
+
expect.objectContaining({ totalResults: 1 }),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
// Say the server response with a new totalResults.
|
|
99
|
+
onChangeMock.mockImplementation(() => ({
|
|
100
|
+
filterInfo: {
|
|
101
|
+
totalResults: 100,
|
|
102
|
+
},
|
|
103
|
+
}))
|
|
104
|
+
await actAndWait(() => {
|
|
105
|
+
fireEvent.click(screen.getByTestId('forceRefreshButton'))
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
109
|
+
expect.objectContaining({ totalResults: 100 }),
|
|
110
|
+
)
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
it('handles onChange.filterInfo.totalResults', async () => {
|
|
114
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
115
|
+
|
|
116
|
+
// Say the server response with a new totalResults.
|
|
117
|
+
onChangeMock.mockImplementation(() => ({
|
|
118
|
+
filterInfo: {
|
|
119
|
+
totalResults: 99,
|
|
120
|
+
},
|
|
121
|
+
}))
|
|
122
|
+
await actAndWait(() => {
|
|
123
|
+
fireEvent.click(screen.getByTestId('forceRefreshButton'))
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
127
|
+
expect.objectContaining({ totalResults: 99 }),
|
|
128
|
+
)
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
// it("handles onChange.data", async () => {
|
|
132
|
+
// onChangeMock.mockImplementation((filterInfo) => ({
|
|
133
|
+
// data: [{ name: filterInfo.filter.foo }],
|
|
134
|
+
// }));
|
|
135
|
+
|
|
136
|
+
// getByTestId(wrapper, "updateFilterButton").simulate("click");
|
|
137
|
+
// await actWrapperUpdate(wrapper);
|
|
138
|
+
|
|
139
|
+
// expect(JSON.parse(getByTestId(wrapper, "responseDataJson").text())).toEqual(
|
|
140
|
+
// [{ name: "42" }]
|
|
141
|
+
// );
|
|
142
|
+
|
|
143
|
+
// getByTestId(wrapper, "resetFilterButton").simulate("click");
|
|
144
|
+
// await actWrapperUpdate(wrapper);
|
|
145
|
+
|
|
146
|
+
// expect(JSON.parse(getByTestId(wrapper, "responseDataJson").text())).toEqual(
|
|
147
|
+
// [{ name: "bar" }]
|
|
148
|
+
// );
|
|
149
|
+
// });
|
|
150
|
+
|
|
151
|
+
it('handles async onChange.filterInfo', async () => {
|
|
152
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
153
|
+
|
|
154
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
155
|
+
expect.objectContaining({ totalResults: 1 }),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
// Say the server response with a new totalResults.
|
|
159
|
+
onChangeMock.mockImplementation(() =>
|
|
160
|
+
Promise.resolve({
|
|
161
|
+
filterInfo: {
|
|
162
|
+
totalResults: 100,
|
|
163
|
+
},
|
|
164
|
+
}),
|
|
165
|
+
)
|
|
166
|
+
await actAndWait(() => {
|
|
167
|
+
fireEvent.click(screen.getByTestId('forceRefreshButton'))
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
171
|
+
expect.objectContaining({ totalResults: 100 }),
|
|
172
|
+
)
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
it('handles async onChange.filterInfo.totalResults', async () => {
|
|
176
|
+
const { onChangeMock } = await setup({ defaultFilterInfo })
|
|
177
|
+
|
|
178
|
+
// Say the server response with a new totalResults.
|
|
179
|
+
onChangeMock.mockImplementation(() =>
|
|
180
|
+
Promise.resolve({
|
|
181
|
+
filterInfo: {
|
|
182
|
+
totalResults: 99,
|
|
183
|
+
},
|
|
184
|
+
}),
|
|
185
|
+
)
|
|
186
|
+
await actAndWait(() => {
|
|
187
|
+
fireEvent.click(screen.getByTestId('forceRefreshButton'))
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
191
|
+
expect.objectContaining({ totalPages: 5 }),
|
|
192
|
+
)
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
// it("handles async onChange.data", async () => {
|
|
196
|
+
// onChangeMock.mockImplementation((filterInfo) =>
|
|
197
|
+
// Promise.resolve({
|
|
198
|
+
// data: [{ name: filterInfo.filter.foo }],
|
|
199
|
+
// })
|
|
200
|
+
// );
|
|
201
|
+
|
|
202
|
+
// getByTestId(wrapper, "updateFilterButton").simulate("click");
|
|
203
|
+
// await actWrapperUpdate(wrapper);
|
|
204
|
+
|
|
205
|
+
// expect(JSON.parse(getByTestId(wrapper, "responseDataJson").text())).toEqual(
|
|
206
|
+
// [{ name: "42" }]
|
|
207
|
+
// );
|
|
208
|
+
|
|
209
|
+
// getByTestId(wrapper, "resetFilterButton").simulate("click");
|
|
210
|
+
// await actWrapperUpdate(wrapper);
|
|
211
|
+
|
|
212
|
+
// expect(JSON.parse(getByTestId(wrapper, "responseDataJson").text())).toEqual(
|
|
213
|
+
// [{ name: "bar" }]
|
|
214
|
+
// );
|
|
215
|
+
// });
|
|
216
|
+
|
|
217
|
+
it('persists across mounts', async () => {
|
|
218
|
+
const { onChangeMock, ExampleComponent } = await setup({
|
|
219
|
+
defaultFilterInfo,
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
const ToggleComponent = () => {
|
|
223
|
+
const [shouldShow, setShouldShow] = useState(true)
|
|
224
|
+
|
|
225
|
+
return (
|
|
226
|
+
<div>
|
|
227
|
+
<button
|
|
228
|
+
data-testid="toggleShouldShow"
|
|
229
|
+
onClick={() => setShouldShow(!shouldShow)}
|
|
230
|
+
/>
|
|
231
|
+
{shouldShow ? <ExampleComponent /> : null}
|
|
232
|
+
</div>
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Simulate the filter being visible.
|
|
237
|
+
await actAndWait(() => {
|
|
238
|
+
// Cleanup the render done in `setup`.
|
|
239
|
+
cleanup()
|
|
240
|
+
render(<ToggleComponent />)
|
|
241
|
+
})
|
|
242
|
+
expect(screen.queryByTestId('updateFilterButton')).toBeTruthy()
|
|
243
|
+
|
|
244
|
+
// Simulate removing the filter.
|
|
245
|
+
await actAndWait(() => {
|
|
246
|
+
fireEvent.click(screen.getByTestId('toggleShouldShow'))
|
|
247
|
+
})
|
|
248
|
+
expect(screen.queryByTestId('updateFilterButton')).toBeFalsy()
|
|
249
|
+
|
|
250
|
+
// Simulate the filter being visible, again.
|
|
251
|
+
await actAndWait(() => {
|
|
252
|
+
fireEvent.click(screen.getByTestId('toggleShouldShow'))
|
|
253
|
+
})
|
|
254
|
+
expect(screen.queryByTestId('updateFilterButton')).toBeTruthy()
|
|
255
|
+
|
|
256
|
+
// onChange should still only be called once.
|
|
257
|
+
expect(onChangeMock).toHaveBeenCalledTimes(1)
|
|
258
|
+
})
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
describe('page based', () => {
|
|
262
|
+
const defaultFilterInfo = buildDefaultFilterInfo({
|
|
263
|
+
filter: {
|
|
264
|
+
foo: 'bar',
|
|
265
|
+
},
|
|
266
|
+
pageSize: 20,
|
|
267
|
+
page: 2,
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
const children: Wut = (wut) => (
|
|
271
|
+
<button data-testid="setPageButton" onClick={() => wut.setPage(3)} />
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
it('accepts initial page', async () => {
|
|
275
|
+
await setup({ defaultFilterInfo, children })
|
|
276
|
+
|
|
277
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
278
|
+
expect.objectContaining({ page: 2, offset: 20 }),
|
|
279
|
+
)
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
it('can set page', async () => {
|
|
283
|
+
const { onChangeMock } = await setup({ defaultFilterInfo, children })
|
|
284
|
+
|
|
285
|
+
await actAndWait(() => {
|
|
286
|
+
fireEvent.click(screen.getByTestId('setPageButton'))
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
290
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
291
|
+
expect.objectContaining({ page: 3, offset: 40 }),
|
|
292
|
+
)
|
|
293
|
+
})
|
|
294
|
+
|
|
295
|
+
it('can handle onChange.filterInfo.page', async () => {
|
|
296
|
+
const { onChangeMock } = await setup({ defaultFilterInfo, children })
|
|
297
|
+
|
|
298
|
+
// Intentionally respond with numbers that don't match what the button
|
|
299
|
+
// actually does.
|
|
300
|
+
// This is to test the actual response, the view updates immediately.
|
|
301
|
+
onChangeMock.mockImplementation(() => ({
|
|
302
|
+
filterInfo: {
|
|
303
|
+
page: 20,
|
|
304
|
+
},
|
|
305
|
+
}))
|
|
306
|
+
|
|
307
|
+
await actAndWait(() => {
|
|
308
|
+
fireEvent.click(screen.getByTestId('setPageButton'))
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
312
|
+
expect.objectContaining({ page: 20, offset: 380 }),
|
|
313
|
+
)
|
|
314
|
+
})
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
describe('offset based', () => {
|
|
318
|
+
const defaultFilterInfo = buildDefaultFilterInfo({
|
|
319
|
+
filter: {
|
|
320
|
+
foo: 'bar',
|
|
321
|
+
},
|
|
322
|
+
pageSize: 20,
|
|
323
|
+
offset: 80,
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
const children: Wut = (wut) => (
|
|
327
|
+
<button data-testid="setOffsetButton" onClick={() => wut.setOffset(100)} />
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
it('accepts initial offset', async () => {
|
|
331
|
+
await setup({ defaultFilterInfo, children })
|
|
332
|
+
|
|
333
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
334
|
+
expect.objectContaining({ offset: 80, page: 5 }),
|
|
335
|
+
)
|
|
336
|
+
})
|
|
337
|
+
|
|
338
|
+
it('can set offset', async () => {
|
|
339
|
+
const { onChangeMock } = await setup({ defaultFilterInfo, children })
|
|
340
|
+
|
|
341
|
+
await actAndWait(() => {
|
|
342
|
+
fireEvent.click(screen.getByTestId('setOffsetButton'))
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
expect(onChangeMock).toHaveBeenCalledTimes(2)
|
|
346
|
+
expect(onChangeMock).toHaveBeenLastCalledWith(
|
|
347
|
+
expect.objectContaining({ page: 6, offset: 100 }),
|
|
348
|
+
)
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
it('can handle onChange.filterInfo.offset', async () => {
|
|
352
|
+
const { onChangeMock } = await setup({ defaultFilterInfo, children })
|
|
353
|
+
|
|
354
|
+
// Intentionally respond with numbers that don't match what the button
|
|
355
|
+
// actually does.
|
|
356
|
+
// This is to test the actual response, the view updates immediately.
|
|
357
|
+
onChangeMock.mockImplementation(() => ({
|
|
358
|
+
filterInfo: {
|
|
359
|
+
offset: 380,
|
|
360
|
+
},
|
|
361
|
+
}))
|
|
362
|
+
await actAndWait(() => {
|
|
363
|
+
fireEvent.click(screen.getByTestId('setOffsetButton'))
|
|
364
|
+
})
|
|
365
|
+
|
|
366
|
+
expect(safeJsonParse(screen.getByTestId('filterJson').textContent)).toEqual(
|
|
367
|
+
expect.objectContaining({ page: 20, offset: 380 }),
|
|
368
|
+
)
|
|
369
|
+
})
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
function wait(n = 0) {
|
|
373
|
+
return new Promise((resolve) => setTimeout(resolve, n))
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function safeJsonParse(input: string | undefined | null = '') {
|
|
377
|
+
if (input) {
|
|
378
|
+
return JSON.parse(input)
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function actAndWait(fn: () => void, n = 0) {
|
|
383
|
+
act(fn)
|
|
384
|
+
await act(async () => {
|
|
385
|
+
await wait(n)
|
|
386
|
+
})
|
|
387
|
+
// You'd think you could just write this:
|
|
388
|
+
// await act(async () => {
|
|
389
|
+
// fn();
|
|
390
|
+
// await wait(n);
|
|
391
|
+
// });
|
|
392
|
+
// But for some reason, doing it that way needs a longer wait duration than
|
|
393
|
+
// just a single tick. /shrug.
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
type Wut = (wut: ReturnType<typeof useFilter>) => React.ReactNode
|
|
397
|
+
|
|
398
|
+
async function setup<TFilterInfo extends FilterInfo<any>>(options: {
|
|
399
|
+
defaultFilterInfo: TFilterInfo
|
|
400
|
+
children?: Wut
|
|
401
|
+
}) {
|
|
402
|
+
memoryStore.clear()
|
|
403
|
+
setFilterStore(memoryStore)
|
|
404
|
+
|
|
405
|
+
const onChangeMock = jest.fn()
|
|
406
|
+
|
|
407
|
+
const ExampleComponent = () => {
|
|
408
|
+
const wut = useFilter('namespace', {
|
|
409
|
+
defaultFilterInfo: options.defaultFilterInfo,
|
|
410
|
+
debounceDuration: 0,
|
|
411
|
+
onChange: onChangeMock,
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
return (
|
|
415
|
+
<div>
|
|
416
|
+
{options.children?.(wut)}
|
|
417
|
+
<button
|
|
418
|
+
data-testid="updateFilterButton"
|
|
419
|
+
onClick={() => wut.updateFilter({ foo: '42' })}
|
|
420
|
+
/>
|
|
421
|
+
<button
|
|
422
|
+
data-testid="resetFilterButton"
|
|
423
|
+
onClick={() => wut.resetFilter()}
|
|
424
|
+
/>
|
|
425
|
+
<button
|
|
426
|
+
data-testid="forceRefreshButton"
|
|
427
|
+
onClick={() => wut.forceRefresh()}
|
|
428
|
+
/>
|
|
429
|
+
<button
|
|
430
|
+
data-testid="setSortButton"
|
|
431
|
+
onClick={() => wut.setSort('foo:bar')}
|
|
432
|
+
/>
|
|
433
|
+
<div data-testid="filterJson">{JSON.stringify(wut.filterInfo)}</div>
|
|
434
|
+
{/* <div data-testid="responseDataJson">
|
|
435
|
+
{JSON.stringify(wut.responseData)}
|
|
436
|
+
</div> */}
|
|
437
|
+
</div>
|
|
438
|
+
)
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
await actAndWait(() => {
|
|
442
|
+
render(<ExampleComponent />)
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
return {
|
|
446
|
+
onChangeMock,
|
|
447
|
+
ExampleComponent,
|
|
448
|
+
}
|
|
449
|
+
}
|
package/src/useFilter.ts
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
}
|