Repository: jamiebuilds/unstated Branch: master Commit: 0c8b3102d2ed Files: 20 Total size: 48.6 KB Directory structure: gitextract_ttajw9oa/ ├── .babelrc ├── .babelrc.js ├── .flowconfig ├── .gitignore ├── .prettierrc ├── .travis.yml ├── LICENSE ├── README.md ├── __tests__/ │ ├── unstated.js │ └── unstated.tsx ├── example/ │ ├── complex.js │ ├── index.html │ ├── shared.js │ └── simple.js ├── flow-typed/ │ └── npm/ │ └── jest_v22.x.x.js ├── package.json ├── rollup.config.js ├── src/ │ ├── unstated.d.ts │ └── unstated.js └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": ["./.babelrc.js"] } ================================================ FILE: .babelrc.js ================================================ const { BABEL_ENV, NODE_ENV } = process.env; const cjs = BABEL_ENV === 'cjs' || NODE_ENV === 'test'; module.exports = { presets: [ [ 'env', { modules: false, loose: true, targets: { browsers: ['last 1 version'] } } ], 'flow', 'react' ], plugins: [ 'transform-class-properties', cjs && 'transform-es2015-modules-commonjs' ].filter(Boolean) }; ================================================ FILE: .flowconfig ================================================ [ignore] [include] [libs] [lints] [options] [strict] ================================================ FILE: .gitignore ================================================ node_modules *.log lib .cache dist coverage ================================================ FILE: .prettierrc ================================================ { "singleQuote": true } ================================================ FILE: .travis.yml ================================================ git: depth: 1 sudo: false language: node_js node_js: - '8' cache: yarn: true directories: - node_modules script: - yarn test --coverage && yarn flow - yarn typescript ================================================ FILE: LICENSE ================================================ Copyright (c) 2018-present James Kyle 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. ================================================ FILE: README.md ================================================





Unstated Logo







# Unstated > State so simple, it goes without saying ### :wave: [Check out the *-next version of Unstated with an all new React Hooks API →](https://github.com/jamiebuilds/unstated-next) ## Installation ```sh yarn add unstated ``` ## Example ```jsx // @flow import React from 'react'; import { render } from 'react-dom'; import { Provider, Subscribe, Container } from 'unstated'; type CounterState = { count: number }; class CounterContainer extends Container { state = { count: 0 }; increment() { this.setState({ count: this.state.count + 1 }); } decrement() { this.setState({ count: this.state.count - 1 }); } } function Counter() { return ( {counter => (
{counter.state.count}
)}
); } render( , document.getElementById('root') ); ``` For more examples, see the `example/` directory. ## Happy Customers

"Unstated is a breath of fresh air for state management. I rewrote my whole app to use it yesterday."

Sindre Sorhus

"When people say you don't need Redux most of the time, they actually mean you do need Unstated.
It's like setState on fucking horse steroids"

Ken Wheeler (obviously)

## Guide If you're like me, you're sick of all the ceremony around state management in React, you want something that fits in well with the React way of thinking, but doesn't command some crazy architecture and methodology. So first off: Component state is nice! It makes sense and people can pick it up quickly: ```jsx class Counter extends React.Component { state = { count: 0 }; increment = () => { this.setState({ count: this.state.count + 1 }); }; decrement = () => { this.setState({ count: this.state.count - 1 }); }; render() { return (
{this.state.count}
); } } ``` As a new React developer you might not know exactly how everything works, but you can get a general sense pretty quickly. The only problem here is that we can't easily share this state with other components in our tree. Which is intentional! React components are designed to be very self-contained. What would be great is if we could replicate the nice parts of React's component state API while sharing it across multiple components. But how do we share values between components in React? Through "context". > **Note:** The following is part of the new `React.createContext` API > [described in this RFC](https://github.com/reactjs/rfcs/blob/master/text/0002-new-version-of-context.md). ```jsx const Amount = React.createContext(1); class Counter extends React.Component { state = { count: 0 }; increment = amount => { this.setState({ count: this.state.count + amount }); }; decrement = amount => { this.setState({ count: this.state.count - amount }); }; render() { return ( {amount => (
{this.state.count}
)}
); } } class AmountAdjuster extends React.Component { state = { amount: 0 }; handleChange = event => { this.setState({ amount: parseInt(event.currentTarget.value, 10) }); }; render() { return (
{this.props.children}
); } } render( ); ``` This is already pretty great. Once you get a little bit used to React's way of thinking, it makes total sense and it's very predictable. But can we build on this pattern to make something even nicer? ### Introducing Unstated Well this is where Unstated comes in. Unstated is designed to build on top of the patterns already set out by React components and context. It has three pieces: ##### `Container` We're going to want another place to store our state and some of the logic for updating it. `Container` is a very simple class which is meant to look just like `React.Component` but with only the state-related bits: `this.state` and `this.setState`. ```js class CounterContainer extends Container { state = { count: 0 }; increment = () => { this.setState({ count: this.state.count + 1 }); }; decrement = () => { this.setState({ count: this.state.count - 1 }); }; } ``` Behind the scenes our `Container`s are also event emitters that our app can subscribe to for updates. When you call `setState` it triggers components to re-render, be careful not to mutate `this.state` directly or your components won't re-render. ###### `setState()` `setState()` in `Container` mimics React's `setState()` method as closely as possible. ```js class CounterContainer extends Container { state = { count: 0 }; increment = () => { this.setState( state => { return { count: state.count + 1 }; }, () => { console.log('Updated!'); } ); }; } ``` It's also run asynchronously, so you need to follow the same rules as React. **Don't read state immediately after setting it** ```js class CounterContainer extends Container { state = { count: 0 }; increment = () => { this.setState({ count: 1 }); console.log(this.state.count); // 0 }; } ``` **If you are using previous state to calculate the next state, use the function form** ```js class CounterContainer extends Container { state = { count: 0 }; increment = () => { this.setState(state => { return { count: state.count + 1 }; }); }; } ``` However, unlike React's `setState()` Unstated's `setState()` returns a promise, so you can `await` it like this: ```js class CounterContainer extends Container { state = { count: 0 }; increment = async () => { await this.setState({ count: 1 }); console.log(this.state.count); // 1 }; } ``` Async functions are now available in [all the major browsers](https://caniuse.com/#feat=async-functions), but you can also use [Babel](http://babeljs.io) to compile them down to something that works in every browser. ##### `` Next we'll need a piece to introduce our state back into the tree so that: * When state changes, our components re-render. * We can depend on our container's state. * We can call methods on our container. For this we have the `` component which allows us to pass our container classes/instances and receive instances of them in the tree. ```jsx function Counter() { return ( {counter => (
{counter.state.count}
)}
); } ``` `` will automatically construct our container and listen for changes. ##### `` The final piece that we'll need is something to store all of our instances internally. For this we have ``. ```jsx render( ); ``` We can do some interesting things with `` as well like dependency injection: ```jsx let counter = new CounterContainer(); render( ); ``` ### Testing Whenever we consider the way that we write the state in our apps we should be thinking about testing. We want to make sure that our state containers have a clean way Well because our containers are very simple classes, we can construct them in tests and assert different things about them very easily. ```js test('counter', async () => { let counter = new CounterContainer(); assert(counter.state.count === 0); await counter.increment(); assert(counter.state.count === 1); await counter.decrement(); assert(counter.state.count === 0); }); ``` If we want to test the relationship between our container and the component we can again construct our own instance and inject it into the tree. ```js test('counter', async () => { let counter = new CounterContainer(); let tree = render( ); await click(tree, '#increment'); assert(counter.state.count === 1); await click(tree, '#decrement'); assert(counter.state.count === 0); }); ``` Dependency injection is useful in many ways. Like if we wanted to stub out a method in our state container we can do that painlessly. ```js test('counter', async () => { let counter = new CounterContainer(); let inc = stub(counter, 'increment'); let dec = stub(counter, 'decrement'); let tree = render( ); await click(tree, '#increment'); assert(inc.calls.length === 1); assert(dec.calls.length === 0); }); ``` We don't even have to do anything to clean up after ourselves because we just throw everything out afterwards. ## FAQ #### What state should I put into Unstated? The React community has focused a lot on trying to put all their state in one place. You could keep doing that with Unstated, but I wouldn't recommend it. I would recommend a multi-part solution. First, use local component state as much as you possibly can. That counter example from above never should have been refactored away from component state, it was fine before Unstated. Second, use libraries to abstract away the bits of state that you'll repeat over and over. Like if form state has you down, you might want to use a library like [Final Form](https://github.com/final-form/react-final-form). If fetching data is getting to be too much, maybe try out [Apollo](https://www.apollographql.com). Or even something uncool but familiar and reliable like [Backbone models and collections](http://backbonejs.org). What? Are you too cool to use an old framework? Third, a lot of shared state between components is localized to a few components in the tree. ```jsx One Two Three ``` For this, I recommend using React's built-in `React.createContext()` API and being careful in designing the API for the base components you create. > **Note:** If you're on an old version of React and want to use the new > context API, [I've got you](https://github.com/thejameskyle/create-react-context/) Finally, (and only after other things are exhausted), if you really need some global state to be shared throughout your app, you can use Unstated. I know all of this might sound somehow more complicated, but it's a matter of using the right tool for the job and not forcing a single paradigm on the entire universe. Unstated isn't ambitious, use it as you need it, it's nice and small for that reason. Don't think of it as a "Redux killer". Don't go trying to build complex tools on top of it. Don't reinvent the wheel. Just try it out and see how you like it. #### Passing your own instances directly to `` If you want to use your own instance of a container directly to `` and you don't care about dependency injection, you can do so: ```jsx let counter = new CounterContainer(); function Counter() { return ( {counter =>
...
}
); } ``` You just need to keep a couple things in mind: 1. You are opting out of dependency injection, you won't be able to `` another instance in your tests. 2. Your instance will be local to whatever ``'s you pass it to, you will end up with multiple instances of your container if you don't pass the same reference in everywhere. Also remember that it is _okay_ to use `` in your application code, you can pass your instance in there. It's probably better to do that in most scenarios anyways (cause then you get dependency injection and all that good stuff). #### How can I pass in options to my container? A good pattern for doing this might be to add a constructor to your container which accepts `props` sorta like React components. Then create your own instance of your container and pass it into ``. ```jsx class CounterContainer extends Container { constructor(props = {}) { super(); this.state = { amount: props.initialAmount || 1, count: 0 }; } increment = () => { this.setState({ count: this.state.count + this.state.amount }); }; } let counter = new CounterContainer({ initialAmount: 5 }); render( ); ``` ## Related - [unstated-debug](https://github.com/sindresorhus/unstated-debug) - Debug your Unstated containers with ease ================================================ FILE: __tests__/unstated.js ================================================ // @flow import React from 'react'; import renderer from 'react-test-renderer'; import { Provider, Subscribe, Container } from '../src/unstated'; function render(element) { return renderer.create(element).toJSON(); } async function click({ children = [] }, id) { const el: any = children.find(({ props = {} }) => props.id === id); el.props.onClick(); } class CounterContainer extends Container<{ count: number }> { state = { count: 0 }; increment(amount = 1) { this.setState({ count: this.state.count + amount }); } decrement(amount = 1) { this.setState({ count: this.state.count - amount }); } } function Counter() { return ( {counter => (
{counter.state.count}
)}
); } test('should incresase/decrease state counter in container', async () => { let counter = new CounterContainer(); let tree = render( ); expect(counter.state.count).toBe(0); await click(tree, 'increment'); expect(counter.state.count).toBe(1); await click(tree, 'decrement'); expect(counter.state.count).toBe(0); }); test('should remove subscriber listeners if component is unmounted', () => { let counter = new CounterContainer(); let tree = renderer.create( ); const testInstance = tree.root.findByType(Subscribe)._fiber.stateNode; expect(counter._listeners.length).toBe(1); expect(testInstance.unmounted).toBe(false); tree.unmount(); expect(counter._listeners.length).toBe(0); expect(testInstance.unmounted).toBe(true); }); test('should throw an error if component is not wrapper with ', () => { spyOn(console, 'error'); expect(() => render()).toThrowError( 'You must wrap your components with a ' ); }); ================================================ FILE: __tests__/unstated.tsx ================================================ import * as React from 'react'; import { Provider, Subscribe, Container } from '../src/unstated'; class CounterContainer extends Container<{ count: number }> { state = { count: 0 }; increment(amount = 1) { this.setState({ count: this.state.count + amount }); } decrement(amount = 1) { this.setState({ count: this.state.count - amount }); } } class AmounterContainer extends Container<{ amount: number }> { state = { amount: 1 }; setAmount(amount: number) { this.setState({ amount }); } } function Counter() { return ( {(counter: CounterContainer) => (
{counter.state.count}
)}
); } function CounterWithAmount() { return ( {(counter: CounterContainer, amounter: AmounterContainer) => (
{counter.state.count}
)}
); } function CounterWithAmountApp() { return ( {(amounter: AmounterContainer) => (
{ amounter.setAmount(parseInt(event.currentTarget.value, 10)); }} />
)}
); } const sharedAmountContainer = new AmounterContainer(); function CounterWithSharedAmountApp() { return ( {(amounter: AmounterContainer) => (
{ amounter.setAmount(parseInt(event.currentTarget.value, 10)); }} />
)}
); } let counter = new CounterContainer(); let render = () => ( ); ================================================ FILE: example/complex.js ================================================ // @flow import React from 'react'; import { render } from 'react-dom'; import { Provider, Subscribe, Container } from '../src/unstated'; type AppState = { amount: number }; class AppContainer extends Container { state = { amount: 1 }; setAmount(amount: number) { this.setState({ amount }); } } type CounterState = { count: number }; class CounterContainer extends Container { state = { count: 0 }; increment(amount: number) { this.setState({ count: this.state.count + amount }); } decrement(amount: number) { this.setState({ count: this.state.count - amount }); } } function Counter() { return ( {(app, counter) => (
Count: {counter.state.count}
)}
); } function App() { return ( {app => (
{ app.setAmount(parseInt(event.currentTarget.value, 10)); }} />
)}
); } render( , window.complex ); ================================================ FILE: example/index.html ================================================ Unstated - Examples

Simple

Complex

Shared

================================================ FILE: example/shared.js ================================================ // @flow import React from 'react'; import { render } from 'react-dom'; import { Provider, Subscribe, Container } from '../src/unstated'; type CounterState = { count: number }; class CounterContainer extends Container { state = { count: 0 }; increment() { this.setState({ count: this.state.count + 1 }); } decrement() { this.setState({ count: this.state.count - 1 }); } } const sharedCounterContainer = new CounterContainer(); function Counter() { return ( {counter => (
{counter.state.count}
)}
); } render( , window.shared ); ================================================ FILE: example/simple.js ================================================ // @flow import React from 'react'; import { render } from 'react-dom'; import { Provider, Subscribe, Container } from '../src/unstated'; type CounterState = { count: number }; class CounterContainer extends Container { state = { count: 0 }; increment() { this.setState({ count: this.state.count + 1 }); } decrement() { this.setState({ count: this.state.count - 1 }); } } function Counter() { return ( {counter => (
{counter.state.count}
)}
); } render( , window.simple ); ================================================ FILE: flow-typed/npm/jest_v22.x.x.js ================================================ // flow-typed signature: 6e1fc0a644aa956f79029fec0709e597 // flow-typed version: 07ebad4796/jest_v22.x.x/flow_>=v0.39.x type JestMockFn, TReturn> = { (...args: TArguments): TReturn, /** * An object for introspecting mock calls */ mock: { /** * An array that represents all calls that have been made into this mock * function. Each call is represented by an array of arguments that were * passed during the call. */ calls: Array, /** * An array that contains all the object instances that have been * instantiated from this mock function. */ instances: Array }, /** * Resets all information stored in the mockFn.mock.calls and * mockFn.mock.instances arrays. Often this is useful when you want to clean * up a mock's usage data between two assertions. */ mockClear(): void, /** * Resets all information stored in the mock. This is useful when you want to * completely restore a mock back to its initial state. */ mockReset(): void, /** * Removes the mock and restores the initial implementation. This is useful * when you want to mock functions in certain test cases and restore the * original implementation in others. Beware that mockFn.mockRestore only * works when mock was created with jest.spyOn. Thus you have to take care of * restoration yourself when manually assigning jest.fn(). */ mockRestore(): void, /** * Accepts a function that should be used as the implementation of the mock. * The mock itself will still record all calls that go into and instances * that come from itself -- the only difference is that the implementation * will also be executed when the mock is called. */ mockImplementation( fn: (...args: TArguments) => TReturn ): JestMockFn, /** * Accepts a function that will be used as an implementation of the mock for * one call to the mocked function. Can be chained so that multiple function * calls produce different results. */ mockImplementationOnce( fn: (...args: TArguments) => TReturn ): JestMockFn, /** * Just a simple sugar function for returning `this` */ mockReturnThis(): void, /** * Deprecated: use jest.fn(() => value) instead */ mockReturnValue(value: TReturn): JestMockFn, /** * Sugar for only returning a value once inside your mock */ mockReturnValueOnce(value: TReturn): JestMockFn }; type JestAsymmetricEqualityType = { /** * A custom Jasmine equality tester */ asymmetricMatch(value: mixed): boolean }; type JestCallsType = { allArgs(): mixed, all(): mixed, any(): boolean, count(): number, first(): mixed, mostRecent(): mixed, reset(): void }; type JestClockType = { install(): void, mockDate(date: Date): void, tick(milliseconds?: number): void, uninstall(): void }; type JestMatcherResult = { message?: string | (() => string), pass: boolean }; type JestMatcher = (actual: any, expected: any) => JestMatcherResult; type JestPromiseType = { /** * Use rejects to unwrap the reason of a rejected promise so any other * matcher can be chained. If the promise is fulfilled the assertion fails. */ rejects: JestExpectType, /** * Use resolves to unwrap the value of a fulfilled promise so any other * matcher can be chained. If the promise is rejected the assertion fails. */ resolves: JestExpectType }; /** * Plugin: jest-enzyme */ type EnzymeMatchersType = { toBeChecked(): void, toBeDisabled(): void, toBeEmpty(): void, toBePresent(): void, toContainReact(element: React$Element): void, toHaveClassName(className: string): void, toHaveHTML(html: string): void, toHaveProp(propKey: string, propValue?: any): void, toHaveRef(refName: string): void, toHaveState(stateKey: string, stateValue?: any): void, toHaveStyle(styleKey: string, styleValue?: any): void, toHaveTagName(tagName: string): void, toHaveText(text: string): void, toIncludeText(text: string): void, toHaveValue(value: any): void, toMatchElement(element: React$Element): void, toMatchSelector(selector: string): void }; type JestExpectType = { not: JestExpectType & EnzymeMatchersType, /** * If you have a mock function, you can use .lastCalledWith to test what * arguments it was last called with. */ lastCalledWith(...args: Array): void, /** * toBe just checks that a value is what you expect. It uses === to check * strict equality. */ toBe(value: any): void, /** * Use .toHaveBeenCalled to ensure that a mock function got called. */ toBeCalled(): void, /** * Use .toBeCalledWith to ensure that a mock function was called with * specific arguments. */ toBeCalledWith(...args: Array): void, /** * Using exact equality with floating point numbers is a bad idea. Rounding * means that intuitive things fail. */ toBeCloseTo(num: number, delta: any): void, /** * Use .toBeDefined to check that a variable is not undefined. */ toBeDefined(): void, /** * Use .toBeFalsy when you don't care what a value is, you just want to * ensure a value is false in a boolean context. */ toBeFalsy(): void, /** * To compare floating point numbers, you can use toBeGreaterThan. */ toBeGreaterThan(number: number): void, /** * To compare floating point numbers, you can use toBeGreaterThanOrEqual. */ toBeGreaterThanOrEqual(number: number): void, /** * To compare floating point numbers, you can use toBeLessThan. */ toBeLessThan(number: number): void, /** * To compare floating point numbers, you can use toBeLessThanOrEqual. */ toBeLessThanOrEqual(number: number): void, /** * Use .toBeInstanceOf(Class) to check that an object is an instance of a * class. */ toBeInstanceOf(cls: Class<*>): void, /** * .toBeNull() is the same as .toBe(null) but the error messages are a bit * nicer. */ toBeNull(): void, /** * Use .toBeTruthy when you don't care what a value is, you just want to * ensure a value is true in a boolean context. */ toBeTruthy(): void, /** * Use .toBeUndefined to check that a variable is undefined. */ toBeUndefined(): void, /** * Use .toContain when you want to check that an item is in a list. For * testing the items in the list, this uses ===, a strict equality check. */ toContain(item: any): void, /** * Use .toContainEqual when you want to check that an item is in a list. For * * * * ing the items in the list, this matcher recursively checks the * equality of all fields, rather than checking for object identity. */ toContainEqual(item: any): void, /** * Use .toEqual when you want to check that two objects have the same value. * This matcher recursively checks the equality of all fields, rather than * checking for object identity. */ toEqual(value: any): void, /** * Use .toHaveBeenCalled to ensure that a mock function got called. */ toHaveBeenCalled(): void, /** * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact * number of times. */ toHaveBeenCalledTimes(number: number): void, /** * Use .toHaveBeenCalledWith to ensure that a mock function was called with * specific arguments. */ toHaveBeenCalledWith(...args: Array): void, /** * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called * with specific arguments. */ toHaveBeenLastCalledWith(...args: Array): void, /** * Check that an object has a .length property and it is set to a certain * numeric value. */ toHaveLength(number: number): void, /** * */ toHaveProperty(propPath: string, value?: any): void, /** * Use .toMatch to check that a string matches a regular expression or string. */ toMatch(regexpOrString: RegExp | string): void, /** * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object. */ toMatchObject(object: Object | Array): void, /** * This ensures that a React component matches the most recent snapshot. */ toMatchSnapshot(name?: string): void, /** * Use .toThrow to test that a function throws when it is called. * If you want to test that a specific error gets thrown, you can provide an * argument to toThrow. The argument can be a string for the error message, * a class for the error, or a regex that should match the error. * * Alias: .toThrowError */ toThrow(message?: string | Error | Class | RegExp): void, toThrowError(message?: string | Error | Class | RegExp): void, /** * Use .toThrowErrorMatchingSnapshot to test that a function throws a error * matching the most recent snapshot when it is called. */ toThrowErrorMatchingSnapshot(): void }; type JestObjectType = { /** * Disables automatic mocking in the module loader. * * After this method is called, all `require()`s will return the real * versions of each module (rather than a mocked version). */ disableAutomock(): JestObjectType, /** * An un-hoisted version of disableAutomock */ autoMockOff(): JestObjectType, /** * Enables automatic mocking in the module loader. */ enableAutomock(): JestObjectType, /** * An un-hoisted version of enableAutomock */ autoMockOn(): JestObjectType, /** * Clears the mock.calls and mock.instances properties of all mocks. * Equivalent to calling .mockClear() on every mocked function. */ clearAllMocks(): JestObjectType, /** * Resets the state of all mocks. Equivalent to calling .mockReset() on every * mocked function. */ resetAllMocks(): JestObjectType, /** * Restores all mocks back to their original value. */ restoreAllMocks(): JestObjectType, /** * Removes any pending timers from the timer system. */ clearAllTimers(): void, /** * The same as `mock` but not moved to the top of the expectation by * babel-jest. */ doMock(moduleName: string, moduleFactory?: any): JestObjectType, /** * The same as `unmock` but not moved to the top of the expectation by * babel-jest. */ dontMock(moduleName: string): JestObjectType, /** * Returns a new, unused mock function. Optionally takes a mock * implementation. */ fn, TReturn>( implementation?: (...args: TArguments) => TReturn ): JestMockFn, /** * Determines if the given function is a mocked function. */ isMockFunction(fn: Function): boolean, /** * Given the name of a module, use the automatic mocking system to generate a * mocked version of the module for you. */ genMockFromModule(moduleName: string): any, /** * Mocks a module with an auto-mocked version when it is being required. * * The second argument can be used to specify an explicit module factory that * is being run instead of using Jest's automocking feature. * * The third argument can be used to create virtual mocks -- mocks of modules * that don't exist anywhere in the system. */ mock( moduleName: string, moduleFactory?: any, options?: Object ): JestObjectType, /** * Returns the actual module instead of a mock, bypassing all checks on * whether the module should receive a mock implementation or not. */ requireActual(moduleName: string): any, /** * Returns a mock module instead of the actual module, bypassing all checks * on whether the module should be required normally or not. */ requireMock(moduleName: string): any, /** * Resets the module registry - the cache of all required modules. This is * useful to isolate modules where local state might conflict between tests. */ resetModules(): JestObjectType, /** * Exhausts the micro-task queue (usually interfaced in node via * process.nextTick). */ runAllTicks(): void, /** * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(), * setInterval(), and setImmediate()). */ runAllTimers(): void, /** * Exhausts all tasks queued by setImmediate(). */ runAllImmediates(): void, /** * Executes only the macro task queue (i.e. all tasks queued by setTimeout() * or setInterval() and setImmediate()). */ runTimersToTime(msToRun: number): void, /** * Executes only the macro-tasks that are currently pending (i.e., only the * tasks that have been queued by setTimeout() or setInterval() up to this * point) */ runOnlyPendingTimers(): void, /** * Explicitly supplies the mock object that the module system should return * for the specified module. Note: It is recommended to use jest.mock() * instead. */ setMock(moduleName: string, moduleExports: any): JestObjectType, /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the * real module). */ unmock(moduleName: string): JestObjectType, /** * Instructs Jest to use fake versions of the standard timer functions * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, * setImmediate and clearImmediate). */ useFakeTimers(): JestObjectType, /** * Instructs Jest to use the real versions of the standard timer functions. */ useRealTimers(): JestObjectType, /** * Creates a mock function similar to jest.fn but also tracks calls to * object[methodName]. */ spyOn(object: Object, methodName: string): JestMockFn, /** * Set the default timeout interval for tests and before/after hooks in milliseconds. * Note: The default timeout interval is 5 seconds if this method is not called. */ setTimeout(timeout: number): JestObjectType }; type JestSpyType = { calls: JestCallsType }; /** Runs this function after every test inside this context */ declare function afterEach( fn: (done: () => void) => ?Promise, timeout?: number ): void; /** Runs this function before every test inside this context */ declare function beforeEach( fn: (done: () => void) => ?Promise, timeout?: number ): void; /** Runs this function after all tests have finished inside this context */ declare function afterAll( fn: (done: () => void) => ?Promise, timeout?: number ): void; /** Runs this function before any tests have started inside this context */ declare function beforeAll( fn: (done: () => void) => ?Promise, timeout?: number ): void; /** A context for grouping tests together */ declare var describe: { /** * Creates a block that groups together several related tests in one "test suite" */ (name: string, fn: () => void): void, /** * Only run this describe block */ only(name: string, fn: () => void): void, /** * Skip running this describe block */ skip(name: string, fn: () => void): void }; /** An individual test unit */ declare var it: { /** * An individual test unit * * @param {string} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ ( name: string, fn?: (done: () => void) => ?Promise, timeout?: number ): void, /** * Only run this test * * @param {string} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ only( name: string, fn?: (done: () => void) => ?Promise, timeout?: number ): void, /** * Skip running this test * * @param {string} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ skip( name: string, fn?: (done: () => void) => ?Promise, timeout?: number ): void, /** * Run the test concurrently * * @param {string} Name of Test * @param {Function} Test * @param {number} Timeout for the test, in milliseconds. */ concurrent( name: string, fn?: (done: () => void) => ?Promise, timeout?: number ): void }; declare function fit( name: string, fn: (done: () => void) => ?Promise, timeout?: number ): void; /** An individual test unit */ declare var test: typeof it; /** A disabled group of tests */ declare var xdescribe: typeof describe; /** A focused group of tests */ declare var fdescribe: typeof describe; /** A disabled individual test */ declare var xit: typeof it; /** A disabled individual test */ declare var xtest: typeof it; /** The expect function is used every time you want to test a value */ declare var expect: { /** The object that you want to make assertions against */ (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType, /** Add additional Jasmine matchers to Jest's roster */ extend(matchers: { [name: string]: JestMatcher }): void, /** Add a module that formats application-specific data structures. */ addSnapshotSerializer(serializer: (input: Object) => string): void, assertions(expectedAssertions: number): void, hasAssertions(): void, any(value: mixed): JestAsymmetricEqualityType, anything(): void, arrayContaining(value: Array): void, objectContaining(value: Object): void, /** Matches any received string that contains the exact expected string. */ stringContaining(value: string): void, stringMatching(value: string | RegExp): void }; // TODO handle return type // http://jasmine.github.io/2.4/introduction.html#section-Spies declare function spyOn(value: mixed, method: string): Object; /** Holds all functions related to manipulating test runner */ declare var jest: JestObjectType; /** * The global Jasmine object, this is generally not exposed as the public API, * using features inside here could break in later versions of Jest. */ declare var jasmine: { DEFAULT_TIMEOUT_INTERVAL: number, any(value: mixed): JestAsymmetricEqualityType, anything(): void, arrayContaining(value: Array): void, clock(): JestClockType, createSpy(name: string): JestSpyType, createSpyObj( baseName: string, methodNames: Array ): { [methodName: string]: JestSpyType }, objectContaining(value: Object): void, stringMatching(value: string): void }; ================================================ FILE: package.json ================================================ { "name": "unstated", "version": "2.1.1", "description": "State so simple, it goes without saying", "main": "lib/unstated.js", "module": "lib/unstated.es.js", "types": "lib/unstated.d.ts", "repository": "https://github.com/thejameskyle/unstated", "author": "James Kyle ", "license": "MIT", "files": ["lib"], "scripts": { "clean": "rm -rf lib", "build": "rollup -c && flow-copy-source src lib && cp src/unstated.d.ts lib/unstated.d.ts", "typecheck": "flow", "test": "jest", "format": "prettier --write **/*.{js,json,md}", "prepublish": "yarn clean && yarn build", "precommit": "lint-staged", "example": "parcel example/index.html", "typescript": "tsc -p tsconfig.json" }, "dependencies": { "create-react-context": "^0.2.2" }, "peerDependencies": { "react": "^15.0.0 || ^16.0.0" }, "devDependencies": { "@types/react": "^16.0.36", "babel-core": "^6.26.0", "babel-plugin-transform-class-properties": "^6.24.1", "babel-preset-env": "^1.6.1", "babel-preset-flow": "^6.23.0", "babel-preset-react": "^6.24.1", "babel-register": "^6.26.0", "flow-bin": "^0.64.0", "flow-copy-source": "^1.2.2", "husky": "^0.14.3", "jest": "^22.1.4", "jsdom": "^11.6.2", "lint-staged": "^6.1.0", "parcel-bundler": "^1.5.1", "prettier": "^1.10.2", "prop-types": "^15.6.0", "react": "^16.2.0", "react-dom": "^16.2.0", "react-test-renderer": "^16.2.0", "rollup": "^0.55.3", "rollup-plugin-babel": "^3.0.3", "typescript": "^2.7.1" }, "lint-staged": { "*.{js,json,md}": ["prettier --write", "git add"] } } ================================================ FILE: rollup.config.js ================================================ import babel from 'rollup-plugin-babel'; import pkg from './package.json'; export default { input: 'src/unstated.js', output: [ { file: pkg.main, format: 'cjs' }, { file: pkg.module, format: 'es' } ], external: [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {}) ], plugins: [babel()] }; ================================================ FILE: src/unstated.d.ts ================================================ import * as React from 'react'; export class Container { state: State; setState( state: | ((prevState: Readonly) => Pick | State | null) | (Pick | State | null), callback?: () => void ): Promise; subscribe(fn: () => any): void; unsubscribe(fn: () => any): void; } export interface ContainerType { new (...args: any[]): Container; } interface SubscribeProps { to: (ContainerType | Container)[]; children(...instances: Container[]): React.ReactNode; } export class Subscribe extends React.Component {} export interface ProviderProps { inject?: Container[]; children: React.ReactNode; } export const Provider: React.SFC; ================================================ FILE: src/unstated.js ================================================ // @flow import React, { type Node } from 'react'; import createReactContext from 'create-react-context'; type Listener = () => mixed; const StateContext = createReactContext(null); export class Container { state: State; _listeners: Array = []; constructor() { CONTAINER_DEBUG_CALLBACKS.forEach(cb => cb(this)); } setState( updater: $Shape | ((prevState: $Shape) => $Shape), callback?: () => void ): Promise { return Promise.resolve().then(() => { let nextState; if (typeof updater === 'function') { nextState = updater(this.state); } else { nextState = updater; } if (nextState == null) { if (callback) callback(); return; } this.state = Object.assign({}, this.state, nextState); let promises = this._listeners.map(listener => listener()); return Promise.all(promises).then(() => { if (callback) { return callback(); } }); }); } subscribe(fn: Listener) { this._listeners.push(fn); } unsubscribe(fn: Listener) { this._listeners = this._listeners.filter(f => f !== fn); } } export type ContainerType = Container; export type ContainersType = Array | ContainerType>; export type ContainerMapType = Map, ContainerType>; export type SubscribeProps = { to: Containers, children: ( ...instances: $TupleMap(Class | C) => C> ) => Node }; type SubscribeState = {}; const DUMMY_STATE = {}; export class Subscribe extends React.Component< SubscribeProps, SubscribeState > { state = {}; instances: Array = []; unmounted = false; componentWillUnmount() { this.unmounted = true; this._unsubscribe(); } _unsubscribe() { this.instances.forEach(container => { container.unsubscribe(this.onUpdate); }); } onUpdate: Listener = () => { return new Promise(resolve => { if (!this.unmounted) { this.setState(DUMMY_STATE, resolve); } else { resolve(); } }); }; _createInstances( map: ContainerMapType | null, containers: ContainersType ): Array { this._unsubscribe(); if (map === null) { throw new Error( 'You must wrap your components with a ' ); } let safeMap = map; let instances = containers.map(ContainerItem => { let instance; if ( typeof ContainerItem === 'object' && ContainerItem instanceof Container ) { instance = ContainerItem; } else { instance = safeMap.get(ContainerItem); if (!instance) { instance = new ContainerItem(); safeMap.set(ContainerItem, instance); } } instance.unsubscribe(this.onUpdate); instance.subscribe(this.onUpdate); return instance; }); this.instances = instances; return instances; } render() { return ( {map => this.props.children.apply( null, this._createInstances(map, this.props.to) ) } ); } } export type ProviderProps = { inject?: Array, children: Node }; export function Provider(props: ProviderProps) { return ( {parentMap => { let childMap = new Map(parentMap); if (props.inject) { props.inject.forEach(instance => { childMap.set(instance.constructor, instance); }); } return ( {props.children} ); }} ); } let CONTAINER_DEBUG_CALLBACKS = []; // If your name isn't Sindre, this is not for you. // I might ruin your day suddenly if you depend on this without talking to me. export function __SUPER_SECRET_CONTAINER_DEBUG_HOOK__( callback: (container: Container) => mixed ) { CONTAINER_DEBUG_CALLBACKS.push(callback); } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "target": "es5", "lib": ["es6", "dom"], "sourceMap": true, "jsx": "react", "moduleResolution": "node", "forceConsistentCasingInFileNames": true, "strict": true, "noEmit": true }, "include": ["src/**/*", "__test__/*.tsx"] }