redux-astroglide 0.1.16 → 0.1.18

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.
Files changed (56) hide show
  1. package/package.json +33 -6
  2. package/.babelrc +0 -4
  3. package/.editorconfig +0 -13
  4. package/.github/workflows/release.yml +0 -38
  5. package/.husky/commit-msg +0 -4
  6. package/.husky/pre-commit +0 -4
  7. package/.prettierrc +0 -1
  8. package/.releaserc.json +0 -17
  9. package/commitlint.config.js +0 -6
  10. package/internals/utils/rollup.js +0 -89
  11. package/rollup.config.js +0 -9
  12. package/src/actions.ts +0 -25
  13. package/src/astroglide.ts +0 -234
  14. package/src/index.ts +0 -7
  15. package/src/middleware.ts +0 -1
  16. package/src/plugins/index.ts +0 -5
  17. package/src/plugins/persist/index.ts +0 -97
  18. package/src/plugins/persist/types.d.ts +0 -8
  19. package/src/plugins/plugins.d.ts +0 -54
  20. package/src/plugins/service.ts +0 -69
  21. package/src/plugins/set/index.ts +0 -9
  22. package/src/plugins/type/index.ts +0 -35
  23. package/src/plugins/type/types.ts +0 -37
  24. package/src/reducers.ts +0 -59
  25. package/src/selectors/index.ts +0 -134
  26. package/tsconfig.json +0 -20
  27. /package/{index.es.js → dist/index.es.js} +0 -0
  28. /package/{index.js → dist/index.js} +0 -0
  29. /package/{index.umd.js → dist/index.umd.js} +0 -0
  30. /package/{plugins → dist/plugins}/index.es.js +0 -0
  31. /package/{plugins → dist/plugins}/index.js +0 -0
  32. /package/{plugins → dist/plugins}/index.umd.js +0 -0
  33. /package/{plugins → dist/plugins}/persist/index.es.js +0 -0
  34. /package/{plugins → dist/plugins}/persist/index.js +0 -0
  35. /package/{plugins → dist/plugins}/persist/index.umd.js +0 -0
  36. /package/{plugins → dist/plugins}/set/index.es.js +0 -0
  37. /package/{plugins → dist/plugins}/set/index.js +0 -0
  38. /package/{plugins → dist/plugins}/set/index.umd.js +0 -0
  39. /package/{plugins → dist/plugins}/type/index.es.js +0 -0
  40. /package/{plugins → dist/plugins}/type/index.js +0 -0
  41. /package/{plugins → dist/plugins}/type/index.umd.js +0 -0
  42. /package/{selectors → dist/selectors}/index.es.js +0 -0
  43. /package/{selectors → dist/selectors}/index.js +0 -0
  44. /package/{selectors → dist/selectors}/index.umd.js +0 -0
  45. /package/{types → dist/types}/actions.d.ts +0 -0
  46. /package/{types → dist/types}/astroglide.d.ts +0 -0
  47. /package/{types → dist/types}/index.d.ts +0 -0
  48. /package/{types → dist/types}/middleware.d.ts +0 -0
  49. /package/{types → dist/types}/plugins/index.d.ts +0 -0
  50. /package/{types → dist/types}/plugins/persist/index.d.ts +0 -0
  51. /package/{types → dist/types}/plugins/service.d.ts +0 -0
  52. /package/{types → dist/types}/plugins/set/index.d.ts +0 -0
  53. /package/{types → dist/types}/plugins/type/index.d.ts +0 -0
  54. /package/{types → dist/types}/plugins/type/types.d.ts +0 -0
  55. /package/{types → dist/types}/reducers.d.ts +0 -0
  56. /package/{types → dist/types}/selectors/index.d.ts +0 -0
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "redux-astroglide",
3
- "version": "0.1.16",
3
+ "version": "0.1.18",
4
4
  "description": "Taking the pain out of redux state management",
5
- "type": "module",
6
5
  "keywords": [
7
6
  "redux",
8
7
  "flux",
@@ -20,17 +19,45 @@
20
19
  },
21
20
  "license": "MIT",
22
21
  "author": "Dustin Schultz <dmanke@gmail.com>",
23
- "main": "./index.js",
22
+ "exports": {
23
+ ".": {
24
+ "import": "./dist/index.es.js",
25
+ "require": "./dist/index.js"
26
+ },
27
+ "./selectors": {
28
+ "import": "./dist/selectors/index.es.js",
29
+ "require": "./dist/selectors/index.js"
30
+ },
31
+ "./plugins": {
32
+ "import": "./dist/plugins/index.es.js",
33
+ "require": "./dist/plugins/index.js"
34
+ },
35
+ "./plugins/set": {
36
+ "import": "./dist/plugins/set/index.es.js",
37
+ "require": "./dist/plugins/set/index.js"
38
+ },
39
+ "./plugins/type": {
40
+ "import": "./dist/plugins/type/index.es.js",
41
+ "require": "./dist/plugins/type/index.js"
42
+ },
43
+ "./plugins/persist": {
44
+ "import": "./dist/plugins/persist/index.es.js",
45
+ "require": "./dist/plugins/persist/index.js"
46
+ }
47
+ },
48
+ "main": "./dist/index.js",
24
49
  "module": "./dist/index.es.js",
25
50
  "browser": "./dist/index.umd.js",
26
51
  "types": "./dist/types",
52
+ "files": [
53
+ "dist"
54
+ ],
27
55
  "scripts": {
28
56
  "start": "BUILD_ENV=dev npm run build:js -- --watch",
29
- "build": "rimraf dist && npm run build:js && npm run build:types",
57
+ "build": "rimraf dist && npm run build:js && npm run build:types",
30
58
  "build:js": "rollup -c",
31
59
  "build:types": "tsc --emitDeclarationOnly",
32
- "prepare": "husky install",
33
- "prepublish": "cp -r ./dist/* ."
60
+ "prepare": "husky install"
34
61
  },
35
62
  "lint-staged": {
36
63
  "*.{js,jsx,ts,tsx}": [
package/.babelrc DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "presets": ["@babel/preset-env", "@babel/preset-typescript"],
3
- "plugins": []
4
- }
package/.editorconfig DELETED
@@ -1,13 +0,0 @@
1
- # editorconfig.org
2
- root = true
3
-
4
- [*]
5
- charset = utf-8
6
- end_of_line = lf
7
- indent_size = 2
8
- indent_style = space
9
- insert_final_newline = true
10
- trim_trailing_whitespace = true
11
-
12
- [*.md]
13
- trim_trailing_whitespace = false
@@ -1,38 +0,0 @@
1
- name: Release
2
-
3
- on:
4
- push:
5
- branches:
6
- - master
7
-
8
- jobs:
9
- release:
10
- name: Release
11
- runs-on: ubuntu-latest
12
- steps:
13
- - name: Checkout
14
- uses: actions/checkout@v3
15
- with:
16
- fetch-depth: 0
17
-
18
- - uses: pnpm/action-setup@v2
19
- name: Install pnpm
20
- with:
21
- version: 7
22
-
23
- - name: Setup Node.js
24
- uses: actions/setup-node@v3
25
- with:
26
- node-version: 16
27
- cache: 'pnpm'
28
-
29
- - name: Install dependencies
30
- run: pnpm install
31
-
32
- - run: pnpm build
33
-
34
- - name: Release
35
- env:
36
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
37
- NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
38
- run: npx semantic-release
package/.husky/commit-msg DELETED
@@ -1,4 +0,0 @@
1
- #!/bin/sh
2
- . "$(dirname "$0")/_/husky.sh"
3
-
4
- npx --no -- commitlint --edit $1
package/.husky/pre-commit DELETED
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env sh
2
- . "$(dirname -- "$0")/_/husky.sh"
3
-
4
- npx lint-staged
package/.prettierrc DELETED
@@ -1 +0,0 @@
1
- { }
package/.releaserc.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "branches": ["master"],
3
- "plugins": [
4
- "@semantic-release/commit-analyzer",
5
- "@semantic-release/release-notes-generator",
6
- ["@semantic-release/changelog", { "changelogFile": "CHANGELOG.md" }],
7
- "@semantic-release/npm",
8
- [
9
- "@semantic-release/git",
10
- {
11
- "assets": ["package.json", "pnpm-lock.yaml", "CHANGELOG.md"],
12
- "message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
13
- }
14
- ],
15
- "@semantic-release/github"
16
- ]
17
- }
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- extends: ['@commitlint/config-conventional'],
3
- rules: {
4
- 'body-max-line-length': [0, 'always', 100],
5
- },
6
- }
@@ -1,89 +0,0 @@
1
- import { babel } from "@rollup/plugin-babel";
2
- import commonjs from "@rollup/plugin-commonjs";
3
- import json from "@rollup/plugin-json";
4
- import { nodeResolve } from "@rollup/plugin-node-resolve";
5
- import { terser } from "rollup-plugin-terser";
6
-
7
- import pkg from "../../package.json";
8
-
9
- const extensions = [".js", ".jsx", ".ts", ".tsx"];
10
-
11
- const plugins = [
12
- json(),
13
- nodeResolve({ extensions }),
14
- commonjs(),
15
- babel({ extensions }),
16
- process.env.BUILD_ENV !== "dev" && terser(),
17
- ];
18
-
19
- export const modifyPath = (path, subpath, name) =>
20
- name
21
- ? path.replace(
22
- new RegExp(`^(\\.?\\/?)${subpath}\\/`),
23
- `$1${subpath}/${name ? `${name}/` : ""}`
24
- )
25
- : path;
26
-
27
- export const modifyOutputPath = (path, name) => modifyPath(path, "dist", name);
28
- export const modifyInputPath = (path, name) => modifyPath(path, "src", name);
29
-
30
- export const makeExportedPackage = (name, pkgConfig = pkg) => {
31
- pkgConfig = { ...pkg, pkgConfig };
32
-
33
- const path = modifyInputPath("src/index.ts", name);
34
-
35
- return [
36
- {
37
- input: path,
38
- external: [
39
- Object.keys(pkgConfig.dependencies || {}),
40
- Object.keys(pkgConfig.peerDependencies || {}),
41
- ].flat(),
42
- output: [
43
- {
44
- file: modifyOutputPath(pkgConfig.module, name),
45
- format: "esm",
46
- },
47
- {
48
- file: modifyOutputPath(pkgConfig.main, name),
49
- format: "cjs",
50
- },
51
- ],
52
- plugins,
53
- },
54
- {
55
- input: path,
56
- output: [
57
- {
58
- name: name ? `${pkgConfig.name}/${name}` : pkgConfig.name,
59
- file: modifyOutputPath(pkgConfig.browser, name),
60
- format: "umd",
61
- },
62
- ],
63
- plugins,
64
- },
65
- ];
66
- };
67
-
68
- const makePackageJsonExports = (packages) => {
69
- return `package.json "exports" section should read:
70
-
71
- "exports": {${packages
72
- .map(
73
- (pkg) => `
74
- ".${pkg ? `/${pkg}` : ""}": {
75
- "import": "${modifyOutputPath("./dist/index.es.js", pkg)}",
76
- "require": "${modifyOutputPath("./dist/index.js", pkg)}"
77
- }`
78
- )
79
- .join(",")}
80
- }`;
81
- };
82
-
83
- export const makeExportedPackages = (...packages) => {
84
- packages = [undefined, ...packages];
85
-
86
- console.log(makePackageJsonExports(packages));
87
-
88
- return packages.map((pkg) => makeExportedPackage(pkg)).flat();
89
- };
package/rollup.config.js DELETED
@@ -1,9 +0,0 @@
1
- import { makeExportedPackages } from "./internals/utils/rollup.js";
2
-
3
- export default makeExportedPackages(
4
- "plugins",
5
- "plugins/set",
6
- "plugins/type",
7
- "plugins/persist",
8
- "selectors"
9
- );
package/src/actions.ts DELETED
@@ -1,25 +0,0 @@
1
- // source: https://react-redux.js.org/api/hooks#recipe-useactions
2
-
3
- import { bindActionCreators } from "@reduxjs/toolkit";
4
- import { useDispatch } from "react-redux";
5
- import { useMemo } from "react";
6
-
7
- export const useAction = (action, deps) => {
8
- return useActions([action], deps)[0];
9
- };
10
-
11
- export const useActions = (actions, deps) => {
12
- const dispatch = useDispatch();
13
- return useMemo(
14
- () => {
15
- if (Array.isArray(actions)) {
16
- return actions.map((a) => bindActionCreators(a, dispatch));
17
- }
18
- return bindActionCreators(actions, dispatch);
19
- },
20
- /* eslint-disable-next-line react-hooks/exhaustive-deps */
21
- deps ? [dispatch, ...deps] : [dispatch]
22
- );
23
- };
24
-
25
- export const makeUseActions = (actions) => (deps) => useActions(actions, deps);
package/src/astroglide.ts DELETED
@@ -1,234 +0,0 @@
1
- import {
2
- ReducersMapObject,
3
- combineReducers,
4
- configureStore,
5
- createSlice,
6
- } from "@reduxjs/toolkit";
7
- import map from "lodash/map";
8
- import reduce from "lodash/reduce";
9
- import upperFirst from "lodash/upperFirst";
10
- import { useSelector } from "react-redux";
11
- import {
12
- injectableMiddleware,
13
- injectMiddleware,
14
- } from "redux-injectable-middleware";
15
- import { useAction } from "./actions";
16
-
17
- import {
18
- injectReducer as _injectReducer,
19
- injectSlice as _injectSlice,
20
- makeSetterReducersFromInitialState,
21
- } from "./reducers";
22
-
23
- import { plugins } from "./plugins/service";
24
- import { configure as configureSelectors } from "./selectors";
25
-
26
- import type { ConfigureStoreOptions, Slice } from "@reduxjs/toolkit";
27
-
28
- type ExtendedSlice = Slice & {
29
- hooks: object;
30
- selectors: object;
31
- };
32
-
33
- export const configure = ({
34
- middleware,
35
- devTools,
36
- preloadedState,
37
- enhancers,
38
- ...staticReducers
39
- }: ConfigureStoreOptions) => {
40
- const store = configureStore({
41
- // @ts-ignore-next-line
42
- reducer: combineReducers(staticReducers),
43
- middleware: (getDefaultMiddleware) => [
44
- ...(typeof middleware === "function"
45
- ? middleware(getDefaultMiddleware)
46
- : middleware || []),
47
- injectableMiddleware,
48
- ],
49
- devTools,
50
- preloadedState,
51
- enhancers,
52
- });
53
-
54
- const { makePropertySelectorsFromSlice } = configureSelectors(store);
55
-
56
- const injectSlice = (slice) => _injectSlice(store, staticReducers, slice);
57
-
58
- const injectReducer = (key, asyncReducer) => {
59
- return _injectReducer(store, staticReducers, key, asyncReducer);
60
- };
61
-
62
- type PluginData = {
63
- data: any;
64
- plugin: any;
65
- };
66
-
67
- const createAutomatedSlice = (sliceConfig, rtkConfig) => {
68
- const pluginData: object = {};
69
-
70
- map(sliceConfig.initialState, (_item, key) => {
71
- let item = _item; // cache it here to pull item -> value -> value -> value if multiple plugins are used...
72
-
73
- let foundIndex;
74
-
75
- const findPlugin = () => {
76
- foundIndex = plugins.findIndex((type: any) => item instanceof type);
77
- };
78
-
79
- findPlugin();
80
-
81
- const activePlugins: PluginData[] = [];
82
-
83
- while (foundIndex != -1) {
84
- activePlugins.push({
85
- data: {
86
- sliceConfig,
87
- key,
88
- plugin: item,
89
- ...item.setup(item, { key, sliceConfig, config: item.config }),
90
- },
91
- plugin: item,
92
- });
93
-
94
- item = item.value; // pull the next value or plugin off the stack
95
-
96
- findPlugin();
97
- }
98
-
99
- let value = item;
100
-
101
- for (const { data, plugin } of activePlugins) {
102
- value = plugin.getInitialValue(value, {
103
- config: plugin.config,
104
- plugin,
105
- key,
106
- ...data,
107
- });
108
- }
109
-
110
- sliceConfig.initialState[key] = value;
111
- pluginData[key] = activePlugins;
112
- });
113
-
114
- const setterReducers = makeSetterReducersFromInitialState(
115
- sliceConfig.initialState,
116
- rtkConfig,
117
- pluginData
118
- );
119
-
120
- let sliceSetterKey = "setSlice";
121
- while (setterReducers[sliceSetterKey]) {
122
- // avoid naming conflicts if initialState has a "slice" property
123
- sliceSetterKey = `_${sliceSetterKey}`;
124
- }
125
-
126
- const slice = createSlice({
127
- ...sliceConfig,
128
- reducers: {
129
- ...setterReducers,
130
- __override__slice__caution: (state, action) => action.payload,
131
- [sliceSetterKey]: (state, action) => {
132
- for (const key in action.payload) {
133
- const actionType = `set${upperFirst(key)}`;
134
- const setter =
135
- setterReducers[actionType] ||
136
- ((_state, _action) => {
137
- _state[key] = _action.payload;
138
- });
139
-
140
- setter(state, { type: actionType, payload: action.payload[key] });
141
- }
142
- },
143
- ...(sliceConfig.reducers || {}),
144
- },
145
- }) as ExtendedSlice;
146
-
147
- const { selectDomain, ...hooks } = makePropertySelectorsFromSlice(slice);
148
-
149
- let domainHookKey = "useSlice";
150
- while (!!hooks[domainHookKey]) {
151
- // avoid naming conflicts in case initialState contains a "domain" property
152
- domainHookKey = domainHookKey.replace(/(^use)(.*)(Slice$)/, "$1$2_$3");
153
- }
154
-
155
- const getParams = (...args) => {
156
- let params = args;
157
-
158
- if (args.length === 1 && typeof args[0] === "function") {
159
- // if the first and only arg is a function, call it with the current state
160
- params = [args[0](selectDomain(store.getState()))];
161
- }
162
-
163
- return params;
164
- };
165
-
166
- const updateFn = (...args: any[]) =>
167
- slice.actions[sliceSetterKey](
168
- // call the modifier fn here
169
- // @ts-ignore
170
- ...getParams(...args)
171
- );
172
-
173
- updateFn.toString = () => slice.actions[sliceSetterKey].toString();
174
-
175
- /* eslint-disable react-hooks/rules-of-hooks */
176
- hooks[domainHookKey] = () => {
177
- return [
178
- useSelector(selectDomain),
179
- useAction(slice.actions[sliceSetterKey], undefined)(...getParams()), // prop updater
180
- useAction(slice.actions.__override__slice__caution, undefined), // state overwriter
181
- ];
182
- };
183
-
184
- hooks[domainHookKey].select = selectDomain;
185
- hooks[domainHookKey].update = updateFn;
186
- /* eslint-enable react-hooks/rules-of-hooks */
187
-
188
- slice.hooks = hooks;
189
-
190
- slice.selectors = {
191
- selectDomain,
192
- ...reduce(
193
- map(slice.hooks, (hook: any, key) => ({
194
- [key.replace(/^use/, "select")]: hook.select,
195
- })),
196
- (a, b) => ({ ...a, ...b })
197
- ),
198
- ...(slice.selectors || {}), // RTK implemented selectors after astroglide was created, some people may not have them
199
- };
200
-
201
- injectSlice(slice);
202
-
203
- return slice;
204
- };
205
-
206
- const astroglide = (
207
- name: string | { name: string; initialState: object },
208
- initialState: object,
209
- rtkConfig: {} = {},
210
- astroglideConfigOverrides = {}
211
- ) => {
212
- const shorthandParams = typeof name === "object";
213
-
214
- const params = [
215
- // @ts-ignore
216
- ...(shorthandParams
217
- ? [name, initialState, rtkConfig]
218
- : [{ ...rtkConfig, name, initialState }]),
219
-
220
- shorthandParams ? astroglideConfigOverrides : initialState,
221
- ];
222
-
223
- return createAutomatedSlice(...params);
224
- };
225
-
226
- return {
227
- createSlice: astroglide,
228
- astroglide,
229
- injectReducer,
230
- injectSlice,
231
- injectMiddleware,
232
- store,
233
- };
234
- };
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- import { configure } from "./astroglide";
2
-
3
- export { createSelectorHook, createSelectorUpdateHook } from "./selectors";
4
- export { configure };
5
- export { plugins, addPlugin, addPlugins } from "./plugins/service";
6
-
7
- export default configure;
package/src/middleware.ts DELETED
@@ -1 +0,0 @@
1
- export { injectableMiddleware as middleware } from "redux-injectable-middleware";
@@ -1,5 +0,0 @@
1
- export { default as set } from "./set";
2
- export { default as type } from "./type";
3
- export { default as persist } from "./persist";
4
-
5
- export { plugins, addPlugin, addPlugins } from "./service";
@@ -1,97 +0,0 @@
1
- import type { PluginClass, sliceConfig } from "../plugins.d";
2
- import type { Storage } from "./types.d";
3
-
4
- const localStorage = (window || {}).localStorage;
5
- const isLocalStorageAvaialble = !!localStorage;
6
-
7
- const PERSISTENCE_KEY = `astroglide-persist`;
8
-
9
- let defaultStorageType: Storage = localStorage;
10
-
11
- export const getPersistedStore = (storage: Storage = defaultStorageType) =>
12
- JSON.parse(storage.getItem(PERSISTENCE_KEY) || "{}");
13
-
14
- export const storePersistedValue = (
15
- key: string,
16
- namespace?: string,
17
- value?: any,
18
- storage: Storage = localStorage
19
- ) => {
20
- const store = getPersistedStore(storage);
21
-
22
- if (namespace) {
23
- store[namespace] = store[namespace] || {};
24
- store[namespace][key] = value;
25
- } else {
26
- store[key] = value;
27
- }
28
-
29
- try {
30
- storage.setItem(PERSISTENCE_KEY, JSON.stringify(store));
31
- } catch (e) {
32
- console.error(e);
33
- }
34
- };
35
-
36
- export const getPersistedValue = (
37
- key: string,
38
- namespace?: string,
39
- _storage?: Storage
40
- ) => {
41
- const storage = _storage || defaultStorageType;
42
- let scope = getPersistedStore(storage);
43
-
44
- if (namespace) {
45
- scope = scope?.[namespace];
46
- }
47
-
48
- return scope?.[key];
49
- };
50
-
51
- export default ({
52
- storageType = defaultStorageType,
53
- }: { storageType?: Storage } = {}) => {
54
- if (!isLocalStorageAvaialble && !storageType) {
55
- console.warn(
56
- "localStorage is not available! You must provide your own storage to persist"
57
- ); // eslint-disable-line no-console
58
- }
59
-
60
- defaultStorageType = storageType;
61
-
62
- return {
63
- setup(plugin: PluginClass, { sliceConfig }: { sliceConfig: sliceConfig }) {
64
- return {
65
- namespace: sliceConfig.name,
66
- storageType: storageType,
67
- };
68
- },
69
-
70
- getInitialValue(value, { sliceConfig, key }) {
71
- const existingPersistedValue = getPersistedValue(
72
- key,
73
- sliceConfig.name,
74
- storageType
75
- );
76
-
77
- if (existingPersistedValue !== undefined) {
78
- return existingPersistedValue;
79
- }
80
-
81
- return value;
82
- },
83
-
84
- update(value, { key, sliceConfig }) {
85
- storePersistedValue(
86
- key,
87
- sliceConfig.name,
88
- value,
89
- storageType !== undefined
90
- ? storageType
91
- : this.config.storageType || defaultStorageType
92
- );
93
-
94
- return value;
95
- },
96
- };
97
- };
@@ -1,8 +0,0 @@
1
- export type Storage =
2
- | typeof localStorage
3
- | typeof sessionStorage
4
- | {
5
- getItem: (key: string) => string | null;
6
- setItem: (key: string, value: string) => void;
7
- removeItem: (key: string) => void;
8
- };
@@ -1,54 +0,0 @@
1
- import type { Draft } from "@reduxjs/toolkit";
2
-
3
- export type sliceConfig = {
4
- name: string;
5
- initialState: object;
6
- };
7
-
8
- export type setupConfig = {
9
- key: string;
10
- sliceConfig: sliceConfig;
11
- };
12
-
13
- export type setup = (item: any, { key, sliceConfig }: setupConfig) => any;
14
-
15
- export type getInitialValueConfig = {
16
- sliceConfig: sliceConfig;
17
- key: string;
18
- plugin?: any;
19
- config: object;
20
- };
21
-
22
- export type getInitialValue = (
23
- value: any,
24
- { sliceConfig, key, plugin }: getInitialValueConfig
25
- ) => any;
26
-
27
- export type updateConfig = {
28
- key: string;
29
- sliceConfig: sliceConfig;
30
- plugin: any;
31
- draft: Draft<(...args: any[]) => any>;
32
- };
33
-
34
- export type update = (value: any, { key, sliceConfig }: updateConfig) => any;
35
-
36
- export type PluginConfig = {
37
- setup?: setup;
38
- getInitialValue?: getInitialValue;
39
- update?: update;
40
- constructor?: Function | ((value: any) => void) | any;
41
- config?: object;
42
- };
43
-
44
- export type PluginClass = {
45
- value: any; // either the initial state value or the next plugin
46
- config: object;
47
-
48
- setValue(value: any): void;
49
- setConfig: (config: object) => void;
50
-
51
- setup(item: PluginClass, {}): any;
52
- getInitialValue(value: any, {}): any;
53
- update(value: any, {}): any;
54
- };
@@ -1,69 +0,0 @@
1
- import type {
2
- PluginClass,
3
- PluginConfig,
4
- setupConfig,
5
- getInitialValueConfig,
6
- updateConfig,
7
- } from "./plugins.d";
8
-
9
- export const plugin = ({
10
- constructor: constructorFn,
11
- setup,
12
- getInitialValue,
13
- update,
14
- config = {},
15
- }: PluginConfig): any => {
16
- return class implements PluginClass {
17
- constructor(value: any, ...args: any[]) {
18
- this.value = value;
19
-
20
- this.setup = setup || this.setup;
21
- this.getInitialValue = getInitialValue || this.getInitialValue;
22
- this.update = update || this.update;
23
- this.config = config;
24
-
25
- constructorFn?.call(this, value, ...args);
26
- }
27
-
28
- value: any; // either the initial state value or the next plugin
29
- config: object;
30
-
31
- getValue(): any {
32
- return this.value;
33
- }
34
-
35
- setValue(value: any): void {
36
- this.value = value;
37
- }
38
-
39
- setConfig(config: object): void {
40
- this.config = { ...this.config, ...config };
41
- }
42
-
43
- setup(item: any, {}: setupConfig): any {
44
- return { plugin: item };
45
- }
46
-
47
- getInitialValue(value: any, {}: getInitialValueConfig): any {
48
- return value;
49
- }
50
-
51
- update(value: any, {}: updateConfig): any {
52
- return value;
53
- }
54
- };
55
- };
56
-
57
- export const addPlugin = (config: PluginConfig) => {
58
- const Class = plugin(config);
59
- plugins.push(Class);
60
-
61
- return (...args: any[]) => new Class(...args);
62
- };
63
-
64
- export const addPlugins = (...configs: PluginConfig[]) =>
65
- configs.map(addPlugin);
66
-
67
- export const plugins: PluginClass[] = [];
68
-
69
- export const getPlugins = () => plugins;
@@ -1,9 +0,0 @@
1
- export default (callback: (value: any, { draft }) => any) => ({
2
- constructor(innerCallback, value) {
3
- this.value = value;
4
- this.callback = innerCallback || callback;
5
- },
6
- update(value, { draft, plugin }) {
7
- return plugin.callback(value, { draft });
8
- },
9
- });
@@ -1,35 +0,0 @@
1
- import { checkProp } from "./types";
2
-
3
- export default (
4
- { preventUpdate }: { preventUpdate: boolean } = { preventUpdate: false }
5
- ) => ({
6
- constructor(propType, value, config = {}) {
7
- this.value = value; // value set here because constructor signature is different
8
- this.propType = propType;
9
- this.config = { ...this.config, ...config };
10
- },
11
-
12
- getInitialValue(value, { key, plugin }) {
13
- const { propType } = plugin;
14
-
15
- checkProp(propType, value, key);
16
-
17
- return value;
18
- },
19
-
20
- update(value, { key, plugin }) {
21
- const { propType } = plugin;
22
-
23
- checkProp(
24
- propType,
25
- value,
26
- key,
27
- plugin.config.preventUpdate !== undefined
28
- ? plugin.config.preventUpdate
29
- : preventUpdate
30
- );
31
-
32
- return value;
33
- },
34
- config: { preventUpdate: false },
35
- });
@@ -1,37 +0,0 @@
1
- import checkPropTypes from "check-prop-types";
2
-
3
- export const checkPropType = (
4
- propType: any,
5
- value: any,
6
- name: string,
7
- extraProps: object = {}
8
- ) => {
9
- return checkPropTypes(
10
- { [name]: propType },
11
- { ...extraProps, [name]: value },
12
- name,
13
- undefined
14
- );
15
- };
16
-
17
- export const checkProp = (
18
- propType: any,
19
- value: any,
20
- name: string,
21
- shouldTypeErrorPreventUpdate: boolean = false
22
- ) => {
23
- const result = checkPropType(propType, value, name);
24
- if (result) {
25
- const errorText = `Astroglide: prop ${name} with value ${value} is not of the specified type`;
26
-
27
- if (shouldTypeErrorPreventUpdate) {
28
- throw Error(errorText);
29
- } else {
30
- console.warn(errorText);
31
- }
32
-
33
- return result;
34
- }
35
-
36
- return false;
37
- };
package/src/reducers.ts DELETED
@@ -1,59 +0,0 @@
1
- /* eslint-disable react/forbid-foreign-prop-types */
2
- import upperFirst from "lodash/upperFirst";
3
-
4
- import { combineReducers } from "@reduxjs/toolkit";
5
-
6
- const asyncReducers = {}; // placeholder for injected reducers
7
-
8
- export const injectReducer = (
9
- store,
10
- staticReducers = {},
11
- key,
12
- asyncReducer
13
- ) => {
14
- if (!asyncReducers[key]) {
15
- asyncReducers[key] = asyncReducer;
16
-
17
- store.replaceReducer(
18
- combineReducers({
19
- ...staticReducers,
20
- ...asyncReducers,
21
- })
22
- );
23
- }
24
- };
25
-
26
- export const injectSlice = (store, staticReducers, slice) =>
27
- injectReducer(store, staticReducers, slice.name, slice.reducer);
28
-
29
- export const getSetterActionName = (name) => `set${upperFirst(name)}`;
30
-
31
- export const makeSetterReducersFromInitialState = (
32
- initialState,
33
- config,
34
- pluginsData
35
- ) => {
36
- const reducer = {};
37
-
38
- Object.keys(initialState).forEach((name) => {
39
- const key = getSetterActionName(name);
40
- reducer[key] = (state, action) => {
41
- let value = action.payload;
42
-
43
- pluginsData[name].forEach(({ data, plugin }) => {
44
- value = plugin.update(value, {
45
- state,
46
- config: plugin.config,
47
- draft: state,
48
- ...data,
49
- }); // provide both state. and draft. apis so fewer users complain
50
- });
51
-
52
- state[name] = value;
53
- };
54
- });
55
-
56
- return reducer;
57
- };
58
-
59
- /* eslint-enable react/forbid-foreign-prop-types */
@@ -1,134 +0,0 @@
1
- import { useSelector, shallowEqual } from "react-redux";
2
- import { createDraftSafeSelector as createSelector } from "@reduxjs/toolkit";
3
- import { useAction } from "../actions";
4
- import { getSetterActionName } from "../reducers";
5
- import get from "lodash/get";
6
- import upperFirst from "lodash/upperFirst";
7
- import type { Action, Selector } from "@reduxjs/toolkit";
8
-
9
- export const makeSelectorHook = (selector) => () =>
10
- useSelector(selector, shallowEqual);
11
-
12
- export const makeSelectorFactoryHook = (selectorFactory) => (args) =>
13
- // a selector factory is used when the selector requires args
14
- // this factory produces a function that accepts those arguments
15
- useSelector(selectorFactory(args), shallowEqual);
16
-
17
- export const createSelectorUpdateHook =
18
- (selector: Selector, action: Action) => () =>
19
- [useSelector(selector), useAction(action, undefined)];
20
-
21
- export const createSelectorHook = (...args: [any]) => {
22
- // creates a redux selector and a react hook that produce identical results
23
- const selector: any = createSelector(...args);
24
- const hook: any = makeSelectorHook(selector);
25
-
26
- hook.select = selector;
27
-
28
- return hook;
29
- };
30
-
31
- export const makeQuerySelectors = (endpoint, defaultValue) => {
32
- // a data selector is used when loading state is irrelevant
33
- const selector = endpoint.select();
34
- const dataSelector = createSelector(
35
- selector,
36
- ({ data, ...rest }) => data || defaultValue
37
- );
38
-
39
- return [selector, dataSelector];
40
- };
41
-
42
- export const dataSelector = ({ data }) => data;
43
-
44
- export const configure = (store) => {
45
- const makeDomainSelector = (name, initialState) => (state) =>
46
- state?.[name] || initialState;
47
-
48
- const makeDomainSelectorFromSlice = (slice) =>
49
- makeDomainSelector(slice.name, slice.getInitialState());
50
-
51
- const selectProp = (name: string, defaultValue?: any) => (substate) =>
52
- get(substate, name, defaultValue);
53
-
54
- const makePropertySelectorHookFactory = (baseSelector, slice) => (names) => {
55
- // to be used in conjunction with singlePropReducer to mimic the useState api,
56
- // but for individual pieces of redux state rather than component state
57
- // usage:
58
- // selector.js:
59
- // const selectDomain = state => state?.[domain] || initialState;
60
- // const createUseState = makePropertySelectorHookFactory(baseSelector, slice);
61
- // const [selectMyData, useMyData] = createUseState("myData");
62
- // index.js:
63
- // const [data, setData] = useMyData();
64
- if (Array.isArray(names)) {
65
- return names.map((name) => makeReduxStateHook(name, baseSelector, slice));
66
- }
67
- names = [names];
68
- return makeReduxStateHook(names, baseSelector, slice);
69
- };
70
-
71
- const makeReduxStateHook = (name, baseSelector, slice) => {
72
- const selector = createSelector(baseSelector, selectProp(name));
73
- const actionName = getSetterActionName(name);
74
- const updateAction = (...args) => {
75
- let params = args;
76
-
77
- if (args.length === 1 && typeof args[0] === "function") {
78
- params = [args[0](selector(store.getState()))];
79
- }
80
-
81
- return slice.actions[actionName](...params);
82
- };
83
-
84
- updateAction.toString = () => slice.actions[actionName].toString();
85
-
86
- if (!updateAction) {
87
- throw Error(`Action ${slice.name}/${actionName} not defined`);
88
- }
89
-
90
- const useState = (setterCb = (value) => value) => [
91
- useSelector(selector),
92
- useAction((value) => updateAction(setterCb(value)), undefined),
93
- ];
94
-
95
- useState.select = selector;
96
- useState.update = updateAction;
97
-
98
- return useState;
99
- };
100
-
101
- const getHookName = (key) => `use${upperFirst(key)}`;
102
-
103
- const makePropertySelectorHooksFromInitialState = (
104
- baseSelector,
105
- slice,
106
- initialState
107
- ) => {
108
- const selectorHooksFactory = makePropertySelectorHookFactory(
109
- baseSelector,
110
- slice
111
- );
112
- const selectorHooksObject = {};
113
-
114
- Object.keys(initialState).forEach((key, i) => {
115
- selectorHooksObject[getHookName(key)] = selectorHooksFactory(key);
116
- });
117
-
118
- return selectorHooksObject;
119
- };
120
-
121
- const makePropertySelectorsFromSlice = (slice) => {
122
- const selectDomain = makeDomainSelectorFromSlice(slice);
123
- return {
124
- selectDomain,
125
- ...makePropertySelectorHooksFromInitialState(
126
- selectDomain,
127
- slice,
128
- slice.getInitialState()
129
- ),
130
- };
131
- };
132
-
133
- return { makePropertySelectorsFromSlice };
134
- };
package/tsconfig.json DELETED
@@ -1,20 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "esnext",
4
- "esModuleInterop": true,
5
- "allowSyntheticDefaultImports": true,
6
- "strict": false,
7
- "forceConsistentCasingInFileNames": true,
8
- "module": "esnext",
9
- "moduleResolution": "node",
10
- "resolveJsonModule": true,
11
- "declaration": true,
12
- "declarationDir": "dist/types",
13
- "noFallthroughCasesInSwitch": true,
14
- "noImplicitReturns": true,
15
- "noUnusedLocals": true,
16
- "noUnusedParameters": false
17
- },
18
- "exclude": ["node_modules", "dist"],
19
- "include": ["src"]
20
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes