atoms-state v0.8.1

#js#react#flux

git clone https://git.pyrossh.dev/atoms-state

Simple State management for react


6d09b46 — pyros2097 2021-04-03T00:40:17+05:30
initial commit

Generated files not shown: yarn.lock

.github/workflows/main.yml ADDED
@@ -0,0 +1,32 @@
1
+ name: CI
2
+ on: [push]
3
+ jobs:
4
+ build:
5
+ name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }}
6
+
7
+ runs-on: ${{ matrix.os }}
8
+ strategy:
9
+ matrix:
10
+ node: ['10.x', '12.x', '14.x']
11
+ os: [ubuntu-latest, windows-latest, macOS-latest]
12
+
13
+ steps:
14
+ - name: Checkout repo
15
+ uses: actions/checkout@v2
16
+
17
+ - name: Use Node ${{ matrix.node }}
18
+ uses: actions/setup-node@v1
19
+ with:
20
+ node-version: ${{ matrix.node }}
21
+
22
+ - name: Install deps and build (with cache)
23
+ uses: bahmutov/npm-install@v1
24
+
25
+ - name: Lint
26
+ run: yarn lint
27
+
28
+ - name: Test
29
+ run: yarn test --ci --coverage --maxWorkers=2
30
+
31
+ - name: Build
32
+ run: yarn build
.github/workflows/size.yml ADDED
@@ -0,0 +1,12 @@
1
+ name: size
2
+ on: [pull_request]
3
+ jobs:
4
+ size:
5
+ runs-on: ubuntu-latest
6
+ env:
7
+ CI_JOB_NUMBER: 1
8
+ steps:
9
+ - uses: actions/checkout@v1
10
+ - uses: andresz1/size-limit-action@v1
11
+ with:
12
+ github_token: ${{ secrets.GITHUB_TOKEN }}
.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ *.log
2
+ .DS_Store
3
+ node_modules
4
+ dist
LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 pyros2097
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.
README.md ADDED
@@ -0,0 +1,4 @@
1
+ # atoms
2
+
3
+ A simple statemanagement library for react.
4
+
package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "version": "0.1.0",
3
+ "license": "MIT",
4
+ "main": "dist/index.js",
5
+ "typings": "dist/index.d.ts",
6
+ "files": [
7
+ "dist",
8
+ "src"
9
+ ],
10
+ "engines": {
11
+ "node": ">=10"
12
+ },
13
+ "scripts": {
14
+ "start": "tsdx watch",
15
+ "build": "tsdx build",
16
+ "test": "tsdx test",
17
+ "lint": "tsdx lint",
18
+ "prepare": "tsdx build",
19
+ "size": "size-limit",
20
+ "analyze": "size-limit --why",
21
+ "deploy": "np"
22
+ },
23
+ "peerDependencies": {
24
+ "react": "*"
25
+ },
26
+ "husky": {
27
+ "hooks": {
28
+ "pre-commit": "tsdx lint"
29
+ }
30
+ },
31
+ "prettier": {
32
+ "printWidth": 80,
33
+ "semi": true,
34
+ "singleQuote": true,
35
+ "trailingComma": "es5"
36
+ },
37
+ "publishConfig": {
38
+ "registry": "https://npm.pkg.github.com"
39
+ },
40
+ "repository": {
41
+ "url": "[email protected]:pyros2097/atoms.git"
42
+ },
43
+ "name": "@pyros2097/atoms",
44
+ "author": "pyros2097",
45
+ "module": "dist/atoms.esm.js",
46
+ "size-limit": [
47
+ {
48
+ "path": "dist/atoms.cjs.production.min.js",
49
+ "limit": "10 KB"
50
+ },
51
+ {
52
+ "path": "dist/atoms.esm.js",
53
+ "limit": "10 KB"
54
+ }
55
+ ],
56
+ "devDependencies": {
57
+ "@size-limit/preset-small-lib": "^4.10.2",
58
+ "@types/react": "17.0.2",
59
+ "husky": "^6.0.0",
60
+ "np": "^7.4.0",
61
+ "react": "17.0.2",
62
+ "size-limit": "^4.10.2",
63
+ "tsdx": "^0.14.1",
64
+ "tslib": "^2.1.0",
65
+ "typescript": "^4.2.3"
66
+ }
67
+ }
src/index.ts ADDED
@@ -0,0 +1,143 @@
1
+ import { useState, useEffect } from 'react';
2
+
3
+ export type Atom<S> = {
4
+ getValue: () => S;
5
+ subscribe: (listener: (value: S) => void) => () => void;
6
+ update: (fn: (oldValue: S) => S) => void;
7
+ };
8
+ export type AtomGetter = <V>(atom: Atom<V>) => V;
9
+ export type DerivedAtomReader<S> = (read: AtomGetter) => S;
10
+
11
+ export const atom = <S>(initial: S | DerivedAtomReader<S>): Atom<S> => {
12
+ let value: S;
13
+ const isDerived = typeof initial === 'function';
14
+ const subs = new Set<(value: S) => void>();
15
+ const get = <A>(a: Atom<A>) => {
16
+ a.subscribe(compute);
17
+ return a.getValue();
18
+ };
19
+ const compute = () => {
20
+ value = (initial as DerivedAtomReader<S>)(get);
21
+ subs.forEach((sub) => {
22
+ sub(value);
23
+ });
24
+ };
25
+ if (isDerived) {
26
+ compute();
27
+ } else {
28
+ value = initial as S;
29
+ }
30
+ return {
31
+ getValue(): S {
32
+ return value;
33
+ },
34
+ subscribe(fn) {
35
+ subs.add(fn);
36
+ return () => subs.delete(fn);
37
+ },
38
+ update(fn: (oldValue: S) => S) {
39
+ value = fn(value);
40
+ subs.forEach((sub) => {
41
+ sub(value);
42
+ });
43
+ },
44
+ };
45
+ };
46
+
47
+ export const useAtom = <S>(atom: Atom<S>): S => {
48
+ const [data, setData] = useState<S>(atom.getValue());
49
+ useEffect(() => {
50
+ return atom.subscribe((value) => {
51
+ setData(value);
52
+ });
53
+ }, []);
54
+ return data;
55
+ };
56
+
57
+ export type AsyncAtom<P, S> = {
58
+ compute: (p: P) => S | Promise<S>;
59
+ fetch: (p: P) => Promise<S>;
60
+ subscribe: (listener: (value: S) => void) => () => void;
61
+ update: (fn: (oldValue: S) => S) => void;
62
+ };
63
+
64
+ export const asyncAtom = <P, S>(fn: (p: P) => Promise<S>): AsyncAtom<P, S> => {
65
+ let value: S | Promise<S>;
66
+ let params: any;
67
+ const subs = new Set<(value: S) => void>();
68
+ return {
69
+ compute(p: P): S | Promise<S> {
70
+ if (JSON.stringify(p) !== JSON.stringify(params)) {
71
+ params = p;
72
+ value = fn(p);
73
+ value
74
+ .then((res) => {
75
+ value = res;
76
+ })
77
+ .catch((err) => {
78
+ value = err;
79
+ });
80
+ }
81
+ return value;
82
+ },
83
+ fetch(p: P): Promise<S> {
84
+ return fn(p);
85
+ },
86
+ subscribe(fn) {
87
+ subs.add(fn);
88
+ return () => subs.delete(fn);
89
+ },
90
+ update(updater: (oldValue: S) => S) {
91
+ value = updater(value as S);
92
+ subs.forEach((sub) => {
93
+ sub(value as S);
94
+ });
95
+ },
96
+ };
97
+ };
98
+
99
+ export const useAsyncAtom = <P, S>(a: AsyncAtom<P, S>, params: P) => {
100
+ const [, toggle] = useState(false);
101
+ useEffect(() => {
102
+ return a.subscribe(() => toggle((v) => !v))
103
+ }, []);
104
+ const v = a.compute(params);
105
+ if (v instanceof Error) {
106
+ throw v;
107
+ } else if (v instanceof Promise) {
108
+ throw v;
109
+ } else {
110
+ return v;
111
+ }
112
+ }
113
+
114
+ type PromiseFunc<S, P> = (p: P) => Promise<S>
115
+
116
+ const usePromiseCache: Map<Function, Map<string, any>> = new Map();
117
+ export const usePromise = <S, P>(fn: PromiseFunc<S, P>, params: P): [S | null, (v: S) => void] => {
118
+ const [data, setData] = useState<boolean>(false);
119
+ const fnCache = usePromiseCache.get(fn) || new Map();
120
+ if (!usePromiseCache.get(fn)) {
121
+ usePromiseCache.set(fn, fnCache);
122
+ }
123
+ const key = typeof params === 'string' ? params : JSON.stringify(params);
124
+ const value = fnCache.get(key)
125
+ if (value) {
126
+ if (value instanceof Promise) {
127
+ throw value;
128
+ } else if (value instanceof Error || value?.errors) {
129
+ throw value;
130
+ }
131
+ return [value, (v) => {
132
+ fnCache.set(key, v)
133
+ setData(!data);
134
+ }];
135
+ }
136
+
137
+ fnCache.set(key, fn(params)
138
+ .then((res) => {
139
+ fnCache.set(key, res)
140
+ })
141
+ .catch((err) => fnCache.set(key, err)))
142
+ throw fnCache.get(key);
143
+ };
test/index.test.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { atom } from '../src';
2
+
3
+ describe('atom', () => {
4
+
5
+ it('getValue', () => {
6
+ const atomOne = atom(10);
7
+ const atomTwo = atom(20);
8
+ const sumAtom = atom((get) => get(atomOne) + get(atomTwo));
9
+ expect(atomOne.getValue()).toEqual(10);
10
+ expect(atomTwo.getValue()).toEqual(20);
11
+ expect(sumAtom.getValue()).toEqual(30);
12
+ });
13
+
14
+ it('update', () => {
15
+ const atomOne = atom(10);
16
+ const sumAtom = atom((get) => get(atomOne) + 5);
17
+ atomOne.update((v) => v + 2)
18
+ expect(atomOne.getValue()).toEqual(12);
19
+ expect(sumAtom.getValue()).toEqual(17);
20
+ })
21
+
22
+ it('subscribe', async () => {
23
+ const atomOne = atom(10);
24
+ const sumAtom = atom((get) => get(atomOne) + 5);
25
+ atomOne.subscribe((newValue) => expect(newValue).toEqual(15));
26
+ sumAtom.subscribe((newValue) => expect(newValue).toEqual(20));
27
+ atomOne.update((v) => v + 5)
28
+ })
29
+
30
+ // it('useAtom', async () => {
31
+ // })
32
+
33
+ });
34
+
35
+ describe('asyncAtom', () => {
36
+ })
37
+
38
+ describe('usePromise', () => {
39
+ })
tsconfig.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs
3
+ "include": ["src", "types"],
4
+ "compilerOptions": {
5
+ "module": "esnext",
6
+ "lib": ["dom", "esnext"],
7
+ "importHelpers": true,
8
+ // output .d.ts declaration files for consumers
9
+ "declaration": true,
10
+ // output .js.map sourcemap files for consumers
11
+ "sourceMap": true,
12
+ // match output dir to input dir. e.g. dist/index instead of dist/src/index
13
+ "rootDir": "./src",
14
+ // stricter type-checking for stronger correctness. Recommended by TS
15
+ "strict": true,
16
+ // linter checks for common issues
17
+ "noImplicitReturns": true,
18
+ "noFallthroughCasesInSwitch": true,
19
+ // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ // use Node's module resolution algorithm, instead of the legacy TS one
23
+ "moduleResolution": "node",
24
+ // transpile JSX to React.createElement
25
+ "jsx": "react",
26
+ // interop between ESM and CJS modules. Recommended by TS
27
+ "esModuleInterop": true,
28
+ // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS
29
+ "skipLibCheck": true,
30
+ // error out if import and file system have a casing mismatch. Recommended by TS
31
+ "forceConsistentCasingInFileNames": true,
32
+ // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc`
33
+ "noEmit": true,
34
+ }
35
+ }