Skip to content

Commit

Permalink
Initialize the library
Browse files Browse the repository at this point in the history
  • Loading branch information
mintsweet committed Jul 1, 2021
0 parents commit d7c4944
Show file tree
Hide file tree
Showing 11 changed files with 2,959 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.DS_Store
node_modules
dist
5 changes: 5 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
tabWidth: 2,
semi: true,
singleQuote: true,
};
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Reate

## 1.0.0

`2021-07-01`

- 🌟 Initialize the library.
- 🌟 Support three APIs, `useState` `setState` `dispatch`.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 青湛<[email protected]> (github/mintsweet)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Reate

> A lightweight react global state management library.
## ✨ Feature

- Simple and easy to use, only three APIs.
- Only 4kb size after build.
- Support TypeScript static check.
- No dependencies.

## 🌈 Install

```bash
$ npm i reate --save
```

## 😊 Usage

**create a store**

```javascript
// store.js
import Reate from 'reate';

export default new Reate(
{
visible: false,
},
{
changeVisible: (store, { visible }) => store.setState({ visible });
}
);
```

**use this store in react**

```javascript
// Test.js
import React from 'react';
import store from './store.js';

function Test() {
const visible = store.useState('visible');
return (
<div>
<div
onClick={() => store.dispatch('changeVisible', { visible: !visible })}
>
ChangeVisible
</div>
{visible ? <div>Hide</div> : <div>Show</div>}
</div>
);
}
```

## 🔨 License

[MIT](LICENSE)
4 changes: 4 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
};
39 changes: 39 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "reate",
"version": "1.0.0",
"main": "dist/index.js",
"description": "A lightweight react global state management library",
"keywords": [
"react",
"redux",
"hooks",
"state",
"store",
"reate"
],
"files": [
"dist",
"CHANGELOG.md",
"LICENSE",
"README.md"
],
"repository": "[email protected]:mintsweet/reate.git",
"author": "mintsweet <[email protected]>",
"license": "MIT",
"scripts": {
"build": "rm -rf dist && tsc",
"test": "jest",
"prepublishOnly": "npm run test"
},
"peerDependencies": {
"react": ">16.8.0"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"jest": "^27.0.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"ts-jest": "^27.0.3",
"typescript": "^4.3.4"
}
}
88 changes: 88 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useState, useEffect } from 'react';

interface State {
[key: string]: any;
}

type EventCallback<T> = (k: T) => void;

function isPlainObject(value: any): boolean {
if (typeof value !== 'object' || value === null) {
return false;
}

if (Object.getPrototypeOf(value) === null) {
return true;
}

let proto = value;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}

return Object.getPrototypeOf(value) === proto;
}

class Reate<
S extends State,
E extends {
[key: string]: (store: Reate<S, E>, payload?: any) => void;
}
> {
private state: any = {};
private event: any = {};
private effect: any = {};

constructor(state: S, effect?: E) {
if (!isPlainObject(state)) {
throw new Error('state is must be a plain object');
}
this.state = state;
this.effect = effect;
}

private on<K extends keyof S>(key: K, callback: EventCallback<S[K]>): void {
if (!this.event[key]) {
this.event[key] = callback;
}
}

private off<K extends keyof S>(key: K): void {
if (this.event[key]) {
this.event[key] = undefined;
}
}

useState<K extends keyof S>(key: K): S[K] {
const [value, setValue] = useState(this.state[key]);

useEffect(() => {
this.on(key, setValue);
return () => this.off(key);
}, [key]);

return value;
}

setState(state: S): void {
if (!isPlainObject(state)) {
throw new Error('state is must be a plain object');
}

Object.keys(state).forEach((key) => {
this.state[key] = state[key];
if (this.event[key]) {
this.event[key](state[key]);
}
});
}

dispatch<K extends keyof E>(key: K, payload?: any): void {
if (typeof this.effect[key] === 'function') {
return this.effect[key](this, payload);
}
throw new Error(`effect not found: ${key}`);
}
}

export default Reate;
88 changes: 88 additions & 0 deletions test/index.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import Reate from '../src';

let container;

beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});

afterEach(() => {
document.body.removeChild(container);
container = null;
});

test('new Reate()', () => {
expect(() => new Reate(undefined)).toThrow('state is must be a plain object');
expect(() => new Reate(null)).toThrow('state is must be a plain object');
});

test('.useState', () => {
const global = new Reate({ text: 'Test' });

function Test() {
const ctx = global.useState('text');
return <div>{ctx}</div>;
}

act(() => {
ReactDOM.render(<Test />, container);
});

const dom = container.querySelector('div');
expect(dom.textContent).toEqual('Test');
});

test('.setState', () => {
const global = new Reate({ visible: false });

function Test() {
const visible = global.useState('visible');
return visible ? <div>Hide</div> : <div>Show</div>;
}

act(() => {
ReactDOM.render(<Test />, container);
});

const dom = container.querySelector('div');
expect(dom.textContent).toEqual('Show');

act(() => {
global.setState({ visible: true });
});

expect(dom.textContent).toEqual('Hide');
});

test('.dispatch', () => {
const global = new Reate(
{ visible: false },
{
changeVisible: (store, { visible }) => {
store.setState({ visible });
},
}
);

function Test() {
const visible = global.useState('visible');
return visible ? <div>Hide</div> : <div>Show</div>;
}

act(() => {
ReactDOM.render(<Test />, container);
});

const dom = container.querySelector('div');
expect(dom.textContent).toEqual('Show');

act(() => {
global.dispatch('changeVisible', { visible: true });
});

expect(dom.textContent).toEqual('Hide');
});
11 changes: 11 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"include": ["src/**/*"],
"compilerOptions": {
"outDir": "dist",
"jsx": "react",
"esModuleInterop": true,
"target": "ES5",
"module": "CommonJS",
"declaration": true
}
}
Loading

0 comments on commit d7c4944

Please sign in to comment.