mobx-react-use-autorun 1.0.1
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/.vscode/settings.json +13 -0
- package/LICENSE +21 -0
- package/README.md +139 -0
- package/babel.config.js +6 -0
- package/bin/mobx_react_build.ts +29 -0
- package/bin/mobx_react_test.ts +27 -0
- package/bin/pre_load_configuration.ts +30 -0
- package/jest.config.ts +195 -0
- package/package.json +52 -0
- package/src/index.tsx +13 -0
- package/src/lib/mobx_config.tsx +5 -0
- package/src/lib/timeout.tsx +5 -0
- package/src/lib/useAsLocalSource.tsx +22 -0
- package/src/lib/useAsyncExhaust.tsx +98 -0
- package/src/lib/useAutorun.tsx +35 -0
- package/test/timeout.test.tsx +12 -0
- package/test/use-as-local-source.test.tsx +9 -0
- package/test/use-async-exhaust.test.tsx +18 -0
- package/test/use-autorun.test.tsx +17 -0
- package/tsconfig.json +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Robert Taussig
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Getting Started with Create React App
|
|
2
|
+
|
|
3
|
+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). If you have any questions, please contact zdu.strong@gmail.com.<br/>
|
|
4
|
+
|
|
5
|
+
## Development environment setup
|
|
6
|
+
1. From https://code.visualstudio.com install Visual Studio Code.<br/>
|
|
7
|
+
2. From https://nodejs.org/en/ install nodejs v16.<br/>
|
|
8
|
+
|
|
9
|
+
## Available Scripts
|
|
10
|
+
|
|
11
|
+
In the project directory, you can run:<br/>
|
|
12
|
+
|
|
13
|
+
### `npm test`
|
|
14
|
+
|
|
15
|
+
Run all unit tests.<br/>
|
|
16
|
+
See the section about [running tests](https://www.cypress.io) for more information.<br/>
|
|
17
|
+
|
|
18
|
+
### `npm run build`
|
|
19
|
+
|
|
20
|
+
Builds the app for production to the `build` folder.<br/>
|
|
21
|
+
It correctly bundles React in production mode and optimizes the build for the best performance.<br/>
|
|
22
|
+
|
|
23
|
+
The build is minified and the filenames include the hashes.<br/>
|
|
24
|
+
Your app is ready to be deployed!<br/>
|
|
25
|
+
|
|
26
|
+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.<br/>
|
|
27
|
+
|
|
28
|
+
### `npm run push`
|
|
29
|
+
|
|
30
|
+
Publish to npm repository
|
|
31
|
+
|
|
32
|
+
## Notes - Define state with useLocalObservable
|
|
33
|
+
|
|
34
|
+
import { useLocalObservable, observer } from 'mobx-react-use-autorun';
|
|
35
|
+
|
|
36
|
+
export default observer(() => {
|
|
37
|
+
|
|
38
|
+
const state = useLocalObservable(() => ({ randomNumber: 1 }));
|
|
39
|
+
|
|
40
|
+
return <div onClick={() => state.randomNumber = Math.random()}>
|
|
41
|
+
{state.randomNumber}
|
|
42
|
+
</div>
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
more usage:<br/>
|
|
46
|
+
表单验证<br/>
|
|
47
|
+
|
|
48
|
+
import { Button, TextField } from '@mui/material';
|
|
49
|
+
import { observer, useLocalObservable } from 'mobx-react-use-autorun';
|
|
50
|
+
import { MessageService } from '../../common/MessageService';
|
|
51
|
+
|
|
52
|
+
export default observer(() => {
|
|
53
|
+
|
|
54
|
+
const state = useLocalObservable(() => ({
|
|
55
|
+
name: "",
|
|
56
|
+
submit: false,
|
|
57
|
+
errors: {
|
|
58
|
+
get name() {
|
|
59
|
+
return state.submit && !state.name && "请填写名称";
|
|
60
|
+
},
|
|
61
|
+
get hasError() {
|
|
62
|
+
return state.errors.name;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}));
|
|
66
|
+
|
|
67
|
+
const ok = async () => {
|
|
68
|
+
state.submit = true;
|
|
69
|
+
if (state.errors.hasError) {
|
|
70
|
+
MessageService.error("错误");
|
|
71
|
+
} else {
|
|
72
|
+
MessageService.success("提交成功");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return (<div className='flex flex-col' style={{ padding: "2em" }}>
|
|
77
|
+
<TextField value={state.name} label="用户名" onChange={(e) => state.name = e.target.value} error={!!state.errors.name} helperText={state.errors.name} />
|
|
78
|
+
<Button variant="contained" style={{ marginTop: "2em" }} onClick={ok} >提交</Button>
|
|
79
|
+
</div>)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
## Notes - Using props and other hooks with useAsLocalSource
|
|
83
|
+
|
|
84
|
+
import { observer, useAsLocalSource } from 'mobx-react-use-autorun';
|
|
85
|
+
import { useLocation } from 'react-router-dom';
|
|
86
|
+
|
|
87
|
+
export default observer((props: { name: string }) => {
|
|
88
|
+
|
|
89
|
+
const source = useAsLocalSource({ location: useLocation(), ...props });
|
|
90
|
+
|
|
91
|
+
return <div>
|
|
92
|
+
{source.name}
|
|
93
|
+
{source.location.pathname}
|
|
94
|
+
</div>
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
## Notes - Subscription property changes with useAutorun
|
|
98
|
+
|
|
99
|
+
import { useLocalObservable, observer, useAutorun, toJS } from 'mobx-react-use-autorun';
|
|
100
|
+
|
|
101
|
+
export default observer(() => {
|
|
102
|
+
|
|
103
|
+
const state = useLocalObservable(() => ({ randomNumber: 1 }));
|
|
104
|
+
|
|
105
|
+
useAutorun(() => {
|
|
106
|
+
console.log(toJS(state))
|
|
107
|
+
}, [state]);
|
|
108
|
+
|
|
109
|
+
return <div onClick={() => state.randomNumber = Math.random()}>
|
|
110
|
+
{state.randomNumber}
|
|
111
|
+
</div>
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
## Notes - Define global mutable data
|
|
115
|
+
|
|
116
|
+
import { observable } from 'mobx-react-use-autorun';
|
|
117
|
+
|
|
118
|
+
const state = observable({});
|
|
119
|
+
|
|
120
|
+
## Notes - Define a delayed promise with timeout
|
|
121
|
+
|
|
122
|
+
import { timeout } form 'mobx-react-use-autorun';
|
|
123
|
+
|
|
124
|
+
async function(){
|
|
125
|
+
await timeout(100);
|
|
126
|
+
await timeout(new Date());
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
## Notes - Get the real data of the proxy object with toJS
|
|
130
|
+
|
|
131
|
+
import { observable, toJS } from 'mobx-react-use-autorun';
|
|
132
|
+
|
|
133
|
+
const state = observable({});
|
|
134
|
+
console.log(toJS(state));
|
|
135
|
+
|
|
136
|
+
## Learn More
|
|
137
|
+
|
|
138
|
+
1. React UI framework (https://reactjs.org)<br/>
|
|
139
|
+
2. React hooks (https://www.npmjs.com/package/react-use)<br/>
|
package/babel.config.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { execSync } from "child_process";
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
const run = async () => {
|
|
5
|
+
execSync(
|
|
6
|
+
[
|
|
7
|
+
"cross-env",
|
|
8
|
+
"TS_NODE_SKIP_PROJECT=true",
|
|
9
|
+
"ts-node bin/pre_load_configuration.ts",
|
|
10
|
+
].join(" "),
|
|
11
|
+
|
|
12
|
+
{
|
|
13
|
+
stdio: "inherit",
|
|
14
|
+
cwd: path.join(__dirname, ".."),
|
|
15
|
+
}
|
|
16
|
+
);
|
|
17
|
+
execSync(
|
|
18
|
+
[
|
|
19
|
+
"cross-env",
|
|
20
|
+
"tsc -p .",
|
|
21
|
+
].join(" "),
|
|
22
|
+
{
|
|
23
|
+
stdio: "inherit",
|
|
24
|
+
cwd: path.join(__dirname, ".."),
|
|
25
|
+
}
|
|
26
|
+
);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export default run();
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { execSync } from "child_process";
|
|
2
|
+
import path from 'path';
|
|
3
|
+
|
|
4
|
+
const run = async () => {
|
|
5
|
+
execSync(
|
|
6
|
+
[
|
|
7
|
+
"cross-env",
|
|
8
|
+
"TS_NODE_SKIP_PROJECT=true",
|
|
9
|
+
"ts-node bin/pre_load_configuration.ts",
|
|
10
|
+
].join(" "),
|
|
11
|
+
{
|
|
12
|
+
stdio: "inherit",
|
|
13
|
+
cwd: path.join(__dirname, ".."),
|
|
14
|
+
}
|
|
15
|
+
);
|
|
16
|
+
execSync(
|
|
17
|
+
[
|
|
18
|
+
"jest --verbose --no-cache",
|
|
19
|
+
].join(" "),
|
|
20
|
+
{
|
|
21
|
+
stdio: "inherit",
|
|
22
|
+
cwd: path.join(__dirname, ".."),
|
|
23
|
+
}
|
|
24
|
+
);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export default run();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { execSync } from 'child_process';
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
|
|
5
|
+
const run = async () => {
|
|
6
|
+
await deletePackageLockFile();
|
|
7
|
+
await deleteBuildFolder();
|
|
8
|
+
execSync(
|
|
9
|
+
[
|
|
10
|
+
"cross-env",
|
|
11
|
+
"npm_config_package_lock=false",
|
|
12
|
+
"npm install",
|
|
13
|
+
].join(" "),
|
|
14
|
+
{
|
|
15
|
+
stdio: "inherit",
|
|
16
|
+
}
|
|
17
|
+
);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const deletePackageLockFile = async () => {
|
|
21
|
+
const filePathOfPackageLockFile = path.join(__dirname, "..", "package-lock.json");
|
|
22
|
+
await fs.promises.rm(filePathOfPackageLockFile, { recursive: true, force: true });
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const deleteBuildFolder = async () => {
|
|
26
|
+
const folderPath = path.join(__dirname, "..", "dist");
|
|
27
|
+
await fs.promises.rm(folderPath, { recursive: true, force: true });
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export default run();
|
package/jest.config.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* For a detailed explanation regarding each configuration property and type check, visit:
|
|
3
|
+
* https://jestjs.io/docs/configuration
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export default {
|
|
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: "C:\\Users\\zdu\\AppData\\Local\\Temp\\jest",
|
|
15
|
+
|
|
16
|
+
// Automatically clear mock calls, instances, contexts and results before every test
|
|
17
|
+
clearMocks: true,
|
|
18
|
+
|
|
19
|
+
// Indicates whether the coverage information should be collected while executing the test
|
|
20
|
+
collectCoverage: true,
|
|
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: "coverage",
|
|
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: "babel",
|
|
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
|
+
// The default configuration for fake timers
|
|
54
|
+
// fakeTimers: {
|
|
55
|
+
// "enableGlobally": false
|
|
56
|
+
// },
|
|
57
|
+
|
|
58
|
+
// Force coverage collection from ignored files using an array of glob patterns
|
|
59
|
+
// forceCoverageMatch: [],
|
|
60
|
+
|
|
61
|
+
// A path to a module which exports an async function that is triggered once before all test suites
|
|
62
|
+
// globalSetup: undefined,
|
|
63
|
+
|
|
64
|
+
// A path to a module which exports an async function that is triggered once after all test suites
|
|
65
|
+
// globalTeardown: undefined,
|
|
66
|
+
|
|
67
|
+
// A set of global variables that need to be available in all test environments
|
|
68
|
+
// globals: {},
|
|
69
|
+
|
|
70
|
+
// 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.
|
|
71
|
+
// maxWorkers: "50%",
|
|
72
|
+
|
|
73
|
+
// An array of directory names to be searched recursively up from the requiring module's location
|
|
74
|
+
// moduleDirectories: [
|
|
75
|
+
// "node_modules"
|
|
76
|
+
// ],
|
|
77
|
+
|
|
78
|
+
// An array of file extensions your modules use
|
|
79
|
+
// moduleFileExtensions: [
|
|
80
|
+
// "js",
|
|
81
|
+
// "mjs",
|
|
82
|
+
// "cjs",
|
|
83
|
+
// "jsx",
|
|
84
|
+
// "ts",
|
|
85
|
+
// "tsx",
|
|
86
|
+
// "json",
|
|
87
|
+
// "node"
|
|
88
|
+
// ],
|
|
89
|
+
|
|
90
|
+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
|
91
|
+
// moduleNameMapper: {},
|
|
92
|
+
|
|
93
|
+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
|
94
|
+
// modulePathIgnorePatterns: [],
|
|
95
|
+
|
|
96
|
+
// Activates notifications for test results
|
|
97
|
+
// notify: false,
|
|
98
|
+
|
|
99
|
+
// An enum that specifies notification mode. Requires { notify: true }
|
|
100
|
+
// notifyMode: "failure-change",
|
|
101
|
+
|
|
102
|
+
// A preset that is used as a base for Jest's configuration
|
|
103
|
+
// preset: undefined,
|
|
104
|
+
|
|
105
|
+
// Run tests from one or more projects
|
|
106
|
+
// projects: undefined,
|
|
107
|
+
|
|
108
|
+
// Use this configuration option to add custom reporters to Jest
|
|
109
|
+
// reporters: undefined,
|
|
110
|
+
|
|
111
|
+
// Automatically reset mock state before every test
|
|
112
|
+
// resetMocks: false,
|
|
113
|
+
|
|
114
|
+
// Reset the module registry before running each individual test
|
|
115
|
+
// resetModules: false,
|
|
116
|
+
|
|
117
|
+
// A path to a custom resolver
|
|
118
|
+
// resolver: undefined,
|
|
119
|
+
|
|
120
|
+
// Automatically restore mock state and implementation before every test
|
|
121
|
+
// restoreMocks: false,
|
|
122
|
+
|
|
123
|
+
// The root directory that Jest should scan for tests and modules within
|
|
124
|
+
// rootDir: undefined,
|
|
125
|
+
|
|
126
|
+
// A list of paths to directories that Jest should use to search for files in
|
|
127
|
+
// roots: [
|
|
128
|
+
// "<rootDir>"
|
|
129
|
+
// ],
|
|
130
|
+
|
|
131
|
+
// Allows you to use a custom runner instead of Jest's default test runner
|
|
132
|
+
// runner: "jest-runner",
|
|
133
|
+
|
|
134
|
+
// The paths to modules that run some code to configure or set up the testing environment before each test
|
|
135
|
+
// setupFiles: [],
|
|
136
|
+
|
|
137
|
+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
|
138
|
+
// setupFilesAfterEnv: [],
|
|
139
|
+
|
|
140
|
+
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
|
141
|
+
// slowTestThreshold: 5,
|
|
142
|
+
|
|
143
|
+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
|
144
|
+
// snapshotSerializers: [],
|
|
145
|
+
|
|
146
|
+
// The test environment that will be used for testing
|
|
147
|
+
testEnvironment: "jsdom",
|
|
148
|
+
|
|
149
|
+
// Options that will be passed to the testEnvironment
|
|
150
|
+
// testEnvironmentOptions: {},
|
|
151
|
+
|
|
152
|
+
// Adds a location field to test results
|
|
153
|
+
// testLocationInResults: false,
|
|
154
|
+
|
|
155
|
+
// The glob patterns Jest uses to detect test files
|
|
156
|
+
// testMatch: [
|
|
157
|
+
// "**/__tests__/**/*.[jt]s?(x)",
|
|
158
|
+
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
|
159
|
+
// ],
|
|
160
|
+
|
|
161
|
+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
|
162
|
+
// testPathIgnorePatterns: [
|
|
163
|
+
// "\\\\node_modules\\\\"
|
|
164
|
+
// ],
|
|
165
|
+
|
|
166
|
+
// The regexp pattern or array of patterns that Jest uses to detect test files
|
|
167
|
+
// testRegex: [],
|
|
168
|
+
|
|
169
|
+
// This option allows the use of a custom results processor
|
|
170
|
+
// testResultsProcessor: undefined,
|
|
171
|
+
|
|
172
|
+
// This option allows use of a custom test runner
|
|
173
|
+
// testRunner: "jest-circus/runner",
|
|
174
|
+
|
|
175
|
+
// A map from regular expressions to paths to transformers
|
|
176
|
+
// transform: undefined,
|
|
177
|
+
|
|
178
|
+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
|
179
|
+
// transformIgnorePatterns: [
|
|
180
|
+
// "\\\\node_modules\\\\",
|
|
181
|
+
// "\\.pnp\\.[^\\\\]+$"
|
|
182
|
+
// ],
|
|
183
|
+
|
|
184
|
+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
|
185
|
+
// unmockedModulePathPatterns: undefined,
|
|
186
|
+
|
|
187
|
+
// Indicates whether each individual test should be reported during the run
|
|
188
|
+
// verbose: undefined,
|
|
189
|
+
|
|
190
|
+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
|
191
|
+
// watchPathIgnorePatterns: [],
|
|
192
|
+
|
|
193
|
+
// Whether to use watchman for file crawling
|
|
194
|
+
// watchman: true,
|
|
195
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mobx-react-use-autorun",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "React Hook for mobx",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"build": "npm install -g typescript@4.6.3 @types/node@17.0.23 ts-node@10.7.0 cross-env@7.0.3 && cross-env TS_NODE_SKIP_PROJECT=true ts-node bin/mobx_react_build.ts",
|
|
7
|
+
"test": "npm install -g typescript@4.6.3 @types/node@17.0.23 ts-node@10.7.0 cross-env@7.0.3 && cross-env TS_NODE_SKIP_PROJECT=true ts-node bin/mobx_react_test.ts",
|
|
8
|
+
"push": "npm test npm run build && npm publish"
|
|
9
|
+
},
|
|
10
|
+
"main": "./dist/index.js",
|
|
11
|
+
"eslintConfig": {
|
|
12
|
+
"extends": [
|
|
13
|
+
"react-app"
|
|
14
|
+
]
|
|
15
|
+
},
|
|
16
|
+
"browserslist": {
|
|
17
|
+
"production": [
|
|
18
|
+
">0.2%",
|
|
19
|
+
"not dead",
|
|
20
|
+
"not op_mini all"
|
|
21
|
+
],
|
|
22
|
+
"development": [
|
|
23
|
+
"last 1 chrome version",
|
|
24
|
+
"last 1 firefox version",
|
|
25
|
+
"last 1 safari version"
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@babel/core": "7.17.10",
|
|
30
|
+
"@babel/preset-env": "7.17.10",
|
|
31
|
+
"@babel/preset-typescript": "7.16.7",
|
|
32
|
+
"@testing-library/react-hooks": "8.0.0",
|
|
33
|
+
"@types/jest": "27.5.0",
|
|
34
|
+
"@types/node": "17.0.23",
|
|
35
|
+
"@types/react": "17.0.44",
|
|
36
|
+
"babel-jest": "28.0.3",
|
|
37
|
+
"get-port": "5.1.1",
|
|
38
|
+
"jest": "28.0.3",
|
|
39
|
+
"jest-environment-jsdom": "28.0.2",
|
|
40
|
+
"mobx": "6.5.0",
|
|
41
|
+
"mobx-react-lite": "3.3.0",
|
|
42
|
+
"react": "17.0.2",
|
|
43
|
+
"react-dom": "17.0.2",
|
|
44
|
+
"react-use": "17.3.2",
|
|
45
|
+
"rxjs": "7.5.5",
|
|
46
|
+
"rxjs-exhaustmap-with-trailing": "2.0.0",
|
|
47
|
+
"tree-kill": "1.2.2",
|
|
48
|
+
"ts-node": "10.7.0",
|
|
49
|
+
"typescript": "4.6.3",
|
|
50
|
+
"wait-on": "6.0.1"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/index.tsx
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import './lib/mobx_config'
|
|
2
|
+
import { toJS, observable } from 'mobx';
|
|
3
|
+
import { useLocalObservable, observer } from 'mobx-react-lite';
|
|
4
|
+
import { timeout } from './lib/timeout'
|
|
5
|
+
import { useAsLocalSource } from './lib/useAsLocalSource';
|
|
6
|
+
import { useAutorun } from './lib/useAutorun';
|
|
7
|
+
import { useAsyncExhaust } from './lib/useAsyncExhaust';
|
|
8
|
+
|
|
9
|
+
export { toJS, observable, observer, useLocalObservable }
|
|
10
|
+
export { timeout }
|
|
11
|
+
export { useAsLocalSource }
|
|
12
|
+
export { useAutorun }
|
|
13
|
+
export { useAsyncExhaust }
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import './mobx_config'
|
|
2
|
+
import { toJS } from 'mobx';
|
|
3
|
+
import { useRef } from 'react';
|
|
4
|
+
|
|
5
|
+
export function useAsLocalSource<T extends object>(data: T): T {
|
|
6
|
+
|
|
7
|
+
const initStateCallback = () => {
|
|
8
|
+
if (Array.isArray(data)) {
|
|
9
|
+
throw new Error('Arrays is unsupported!');
|
|
10
|
+
}
|
|
11
|
+
const initState = {} as T;
|
|
12
|
+
return initState;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const state = useRef(initStateCallback());
|
|
16
|
+
|
|
17
|
+
for (const key in data) {
|
|
18
|
+
state.current[key] = toJS(data[key]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return state.current;
|
|
22
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import './mobx_config'
|
|
2
|
+
import { toJS } from 'mobx';
|
|
3
|
+
import { useLocalObservable } from 'mobx-react-lite';
|
|
4
|
+
import { useMount, useUnmount } from 'react-use';
|
|
5
|
+
import { catchError, concatMap, debounceTime, EMPTY, from, lastValueFrom, ReplaySubject, Subscription } from 'rxjs';
|
|
6
|
+
import { exhaustMapWithTrailing } from 'rxjs-exhaustmap-with-trailing';
|
|
7
|
+
import { useAsLocalSource } from './useAsLocalSource';
|
|
8
|
+
|
|
9
|
+
export function useAsyncExhaust<T>(callback: T) {
|
|
10
|
+
|
|
11
|
+
const runCallback: any = function () {
|
|
12
|
+
if (state.isUnmount) {
|
|
13
|
+
const resultSubjectPromise = Promise.reject(new Error("Cancelled!"));
|
|
14
|
+
resultSubjectPromise.catch(() => null);
|
|
15
|
+
return resultSubjectPromise;
|
|
16
|
+
} else {
|
|
17
|
+
const resultSubject = new ReplaySubject(0);
|
|
18
|
+
const resultSubjectPromise = lastValueFrom(resultSubject);
|
|
19
|
+
state.resultSubjectList.push({
|
|
20
|
+
subject: resultSubject,
|
|
21
|
+
promise: resultSubjectPromise
|
|
22
|
+
});
|
|
23
|
+
state.subject.next({
|
|
24
|
+
params: arguments
|
|
25
|
+
});
|
|
26
|
+
return resultSubjectPromise;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const state = useLocalObservable(() => {
|
|
31
|
+
return {
|
|
32
|
+
subscription: new Subscription(),
|
|
33
|
+
subject: new ReplaySubject(0),
|
|
34
|
+
resultSubjectList: [] as {
|
|
35
|
+
subject: ReplaySubject<any>,
|
|
36
|
+
promise: Promise<any>,
|
|
37
|
+
}[],
|
|
38
|
+
isUnmount: false,
|
|
39
|
+
};
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
const source: { callback: any } = useAsLocalSource({
|
|
43
|
+
callback
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
useMount(() => {
|
|
47
|
+
state.subscription.add(state.subject.pipe(
|
|
48
|
+
debounceTime(0),
|
|
49
|
+
exhaustMapWithTrailing(({ params }: any) => {
|
|
50
|
+
const resultSubjectList = toJS(state.resultSubjectList);
|
|
51
|
+
return from((async () => { return await source.callback(...params) })()).pipe(
|
|
52
|
+
concatMap((result) => {
|
|
53
|
+
for (const resultSubject of resultSubjectList) {
|
|
54
|
+
resultSubject.subject.next(result);
|
|
55
|
+
resultSubject.subject.complete();
|
|
56
|
+
if (resultSubject.subject.closed) {
|
|
57
|
+
const index = state.resultSubjectList.findIndex(s => s === resultSubject);
|
|
58
|
+
if (index >= 0) {
|
|
59
|
+
state.resultSubjectList.splice(index, 1);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return EMPTY;
|
|
64
|
+
}),
|
|
65
|
+
catchError((error) => {
|
|
66
|
+
for (const resultSubject of resultSubjectList) {
|
|
67
|
+
resultSubject.subject.error(error);
|
|
68
|
+
if (resultSubject.subject.closed) {
|
|
69
|
+
const index = state.resultSubjectList.findIndex(s => s === resultSubject);
|
|
70
|
+
if (index >= 0) {
|
|
71
|
+
state.resultSubjectList.splice(index, 1);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return EMPTY;
|
|
76
|
+
})
|
|
77
|
+
);
|
|
78
|
+
}),
|
|
79
|
+
).subscribe());
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
useUnmount(() => {
|
|
83
|
+
state.subscription.unsubscribe();
|
|
84
|
+
state.isUnmount = true;
|
|
85
|
+
for (const resultSubject of toJS(state.resultSubjectList)) {
|
|
86
|
+
resultSubject.promise.catch(() => null);
|
|
87
|
+
resultSubject.subject.error(new Error("Cancelled!"));
|
|
88
|
+
if (resultSubject.subject.closed) {
|
|
89
|
+
const index = state.resultSubjectList.findIndex(s => s === resultSubject);
|
|
90
|
+
if (index >= 0) {
|
|
91
|
+
state.resultSubjectList.splice(index, 1);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
return runCallback as T;
|
|
98
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import './mobx_config'
|
|
2
|
+
import { useLocalObservable } from 'mobx-react-lite';
|
|
3
|
+
import { useMount, useUnmount } from 'react-use';
|
|
4
|
+
import { catchError, distinctUntilChanged, ReplaySubject, Subscription, tap } from 'rxjs';
|
|
5
|
+
import { useEffect } from 'react';
|
|
6
|
+
import { useAsLocalSource } from './useAsLocalSource';
|
|
7
|
+
|
|
8
|
+
export const useAutorun = (callback: () => void, dependencyList: any[]): void => {
|
|
9
|
+
const state = useLocalObservable(() => ({
|
|
10
|
+
subscription: new Subscription(),
|
|
11
|
+
subject: new ReplaySubject(1),
|
|
12
|
+
}))
|
|
13
|
+
|
|
14
|
+
const source = useAsLocalSource({
|
|
15
|
+
callback
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
state.subject.next(JSON.stringify(dependencyList));
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
useMount(() => {
|
|
23
|
+
state.subscription.add(state.subject.pipe(
|
|
24
|
+
distinctUntilChanged(),
|
|
25
|
+
tap(() => {
|
|
26
|
+
source.callback();
|
|
27
|
+
}),
|
|
28
|
+
catchError((_, caught) => caught),
|
|
29
|
+
).subscribe());
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
useUnmount(() => {
|
|
33
|
+
state.subscription.unsubscribe();
|
|
34
|
+
})
|
|
35
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { timeout } from '../src/index'
|
|
2
|
+
|
|
3
|
+
let startDate = null as Date | null;
|
|
4
|
+
|
|
5
|
+
test('Expect timeout as a promise to return after one second', async () => {
|
|
6
|
+
await timeout(1000)
|
|
7
|
+
expect(new Date().getTime()).toBeGreaterThanOrEqual(startDate.getTime())
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
beforeAll(() => {
|
|
11
|
+
startDate = new Date();
|
|
12
|
+
})
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { useAsLocalSource } from '../src/index'
|
|
2
|
+
import { renderHook } from '@testing-library/react-hooks'
|
|
3
|
+
|
|
4
|
+
test('Expect useAsLocalSource to return the passed in value', () => {
|
|
5
|
+
const { result } = renderHook((props) => useAsLocalSource(props), {
|
|
6
|
+
initialProps: { people: { name: 'tom' } }
|
|
7
|
+
});
|
|
8
|
+
expect(result.current.people.name).toEqual('tom')
|
|
9
|
+
})
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { useAsyncExhaust, timeout } from '../src/index'
|
|
2
|
+
import { renderHook } from '@testing-library/react-hooks'
|
|
3
|
+
|
|
4
|
+
test('Expect useAsyncExhaust to run only once when it is called consecutively', async () => {
|
|
5
|
+
let runTimes = 0;
|
|
6
|
+
const { result } = renderHook(() => useAsyncExhaust(async () => {
|
|
7
|
+
await timeout(1000);
|
|
8
|
+
runTimes++;
|
|
9
|
+
}));
|
|
10
|
+
await Promise.all([
|
|
11
|
+
result.current(),
|
|
12
|
+
result.current(),
|
|
13
|
+
result.current(),
|
|
14
|
+
result.current(),
|
|
15
|
+
result.current(),
|
|
16
|
+
])
|
|
17
|
+
expect(runTimes).toEqual(1)
|
|
18
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { useAutorun } from '../src/index'
|
|
2
|
+
import { renderHook } from '@testing-library/react-hooks'
|
|
3
|
+
|
|
4
|
+
test('Expect useAutorun to take effect', () => {
|
|
5
|
+
let runTimes = 0;
|
|
6
|
+
const { rerender } = renderHook((props) => useAutorun(() => {
|
|
7
|
+
runTimes++;
|
|
8
|
+
}, [props.people]), {
|
|
9
|
+
initialProps: { people: { name: 'tom', age: 16 } }
|
|
10
|
+
});
|
|
11
|
+
expect(runTimes).toEqual(1)
|
|
12
|
+
rerender({ people: { name: 'tom', age: 16 } })
|
|
13
|
+
expect(runTimes).toEqual(1)
|
|
14
|
+
rerender({ people: { name: 'tom', age: 17 } })
|
|
15
|
+
rerender({ people: { name: 'tom', age: 18 } })
|
|
16
|
+
expect(runTimes).toEqual(3)
|
|
17
|
+
})
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"outDir": "./dist/",
|
|
4
|
+
"target": "es5",
|
|
5
|
+
"lib": [
|
|
6
|
+
"dom",
|
|
7
|
+
"dom.iterable",
|
|
8
|
+
"esnext"
|
|
9
|
+
],
|
|
10
|
+
"allowJs": true,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"esModuleInterop": true,
|
|
13
|
+
"allowSyntheticDefaultImports": true,
|
|
14
|
+
"strict": true,
|
|
15
|
+
"forceConsistentCasingInFileNames": true,
|
|
16
|
+
"noFallthroughCasesInSwitch": true,
|
|
17
|
+
"module": "esnext",
|
|
18
|
+
"moduleResolution": "node",
|
|
19
|
+
"resolveJsonModule": true,
|
|
20
|
+
"isolatedModules": true,
|
|
21
|
+
"noEmit": false,
|
|
22
|
+
"jsx": "react-jsx",
|
|
23
|
+
"sourceMap": true,
|
|
24
|
+
"declaration": true,
|
|
25
|
+
},
|
|
26
|
+
"include": [
|
|
27
|
+
"src",
|
|
28
|
+
]
|
|
29
|
+
}
|