Skip to content

Commit

Permalink
use global immer
Browse files Browse the repository at this point in the history
  • Loading branch information
marianban committed May 12, 2020
1 parent 9368020 commit 540b144
Show file tree
Hide file tree
Showing 15 changed files with 11,543 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
coverage
dist
.DS_Store
.yarn
.pnp.js
3 changes: 3 additions & 0 deletions GlobalImmerContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as React from 'react';

export const GlobalImmerContext = React.createContext();
13 changes: 13 additions & 0 deletions GlobalImmerProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from 'react';
import { useImmer } from 'use-immer';
import { GlobalImmerContext } from './GlobalImmerContext';
import { deepFreeze } from './deepFreeze';

export const GlobalImmerProvider = ({ children, store }) => {
const [state, setState] = useImmer(store.initialState);
return (
<GlobalImmerContext.Provider value={[deepFreeze(state), setState]}>
{children}
</GlobalImmerContext.Provider>
);
};
55 changes: 54 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,54 @@
# use-global-immer
# Use Global Immer

## Installation

```bash
npm i use-global-immer use-immer immer
```

## Get Started

```js
// store.js

import { createImmerStore } from 'useGlobalImmer';

const store = createImmerStore({
counter: 0,
});
```

```jsx
// Counter.js

import * as React from 'react';
import { useGlobalImmer } from 'use-global-immer';
import { store } from './store';

export const Counter = () => {
const [counter, setCounter] = useGlobalImmer(store.counter);
return (
<div>
<div>{counter}</div>
<button onClick={() => setCounter(value => void value +)}>Increment</button>
</div>
);
};
```

```jsx
// App.js

import * as React from 'react';
import { GlobalImmerProvider } from 'use-global-immer';
import { store } from './store';
import { Counter } from './Counter';

export const App = () => {
return (
<GlobalImmerProvider store={store}>
<Counter />
</GlobalImmerProvider>
);
};
```
53 changes: 53 additions & 0 deletions __tests__/useGlobalImmer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import * as React from 'react';
import { createImmerStore } from '../createImmerStore';
import { GlobalImmerProvider } from '../GlobalImmerProvider';
import { useGlobalImmer } from '../useGlobalImmer';
import { renderHook, act } from '@testing-library/react-hooks';

const firstUserName = 'Claudia Keebler';
const store = createImmerStore({
counter: 0,
users: [
{
name: firstUserName,
},
],
});

const makeWrapper = (store) => ({ children }) => (
<GlobalImmerProvider store={store}>{children}</GlobalImmerProvider>
);

describe('useGlobalImmer', () => {
it('can modify primitive value', () => {
const { result } = renderHook(() => useGlobalImmer(store.counter), {
wrapper: makeWrapper(store),
});
let counter, setCounter;
[counter, setCounter] = result.current;
expect(counter).toBe(0);
act(() => {
setCounter((value) => value + 1);
setCounter((value) => value + 1);
});
[counter] = result.current;
expect(counter).toBe(2);
});
it('can modify object value', () => {
const { result } = renderHook(() => useGlobalImmer(store.users), {
wrapper: makeWrapper(store),
});
let users, setUsers;
[users, setUsers] = result.current;
expect(users).toHaveLength(1);
expect(users[0]).toHaveProperty('name', firstUserName);
const secondUserName = 'Berenice Graham';
act(() => {
setUsers((users) => void users.push({ name: secondUserName }));
});
[users] = result.current;
expect(users).toHaveLength(2);
expect(users[0]).toHaveProperty('name', firstUserName);
expect(users[1]).toHaveProperty('name', secondUserName);
});
});
4 changes: 4 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};
10 changes: 10 additions & 0 deletions createImmerStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export const createImmerStore = (initialState) => {
const keys = Object.keys(initialState);
return keys.reduce(
(acc, key) => {
acc[key] = { key };
return acc;
},
{ initialState }
);
};
17 changes: 17 additions & 0 deletions deepFreeze.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
export const deepFreeze = (object) => {
// Retrieve the property names defined on object
var propNames = Object.getOwnPropertyNames(object);

// Freeze properties before freezing self

for (let name of propNames) {
let value = object[name];

if (value && typeof value === 'object') {
deepFreeze(value);
}
}

return Object.freeze(object);
};
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createImmerStore } from './createImmerStore';
import { GlobalImmerProvider } from './GlobalImmerProvider';
import { useGlobalImmer } from './useGlobalImmer';

export { createImmerStore, GlobalImmerProvider, useGlobalImmer };
190 changes: 190 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html

module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,

// Stop running tests after `n` failures
// bail: 0,

// Respect "browser" field in package.json when resolving modules
// browser: false,

// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/b0/g0qdcs8n5slg1mss0h6ft4j40000gn/T/jest_dx",

// Automatically clear mock calls and instances between every test
clearMocks: true,

// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,

// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,

// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',

// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],

// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],

// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,

// A path to a custom dependency extractor
// dependencyExtractor: undefined,

// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,

// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],

// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,

// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,

// A set of global variables that need to be available in all test environments
// globals: {},

// 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.
// maxWorkers: "50%",

// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],

// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],

// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},

// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],

// Activates notifications for test results
// notify: false,

// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",

// A preset that is used as a base for Jest's configuration
// preset: undefined,

// Run tests from one or more projects
// projects: undefined,

// Use this configuration option to add custom reporters to Jest
// reporters: undefined,

// Automatically reset mock state between every test
// resetMocks: false,

// Reset the module registry before running each individual test
// resetModules: false,

// A path to a custom resolver
// resolver: undefined,

// Automatically restore mock state between every test
// restoreMocks: false,

// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,

// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],

// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",

// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],

// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],

// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],

// The test environment that will be used for testing
// testEnvironment: "jest-environment-jsdom",

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},

// Adds a location field to test results
// testLocationInResults: false,

// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],

// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],

// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],

// This option allows the use of a custom results processor
// testResultsProcessor: undefined,

// This option allows use of a custom test runner
// testRunner: "jasmine2",

// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",

// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",

// A map from regular expressions to paths to transformers
transform: {
'^.+\\.js$': 'babel-jest',
},

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/"
// ],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,

// Indicates whether each individual test should be reported during the run
// verbose: undefined,

// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],

// Whether to use watchman for file crawling
// watchman: true,
};
7 changes: 7 additions & 0 deletions jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"module": "es6",
"target": "es6"
},
"exclude": ["node_modules"]
}
Loading

0 comments on commit 540b144

Please sign in to comment.