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 <me@thejameskyle.com>
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
================================================
<div align="center">
<br><br><br><br><br>
<img src="https://raw.githubusercontent.com/thejameskyle/unstated/master/logo.png" alt="Unstated Logo" width="400">
<br><br><br><br><br><br><br><br>
</div>
# 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<CounterState> {
state = {
count: 0
};
increment() {
this.setState({ count: this.state.count + 1 });
}
decrement() {
this.setState({ count: this.state.count - 1 });
}
}
function Counter() {
return (
<Subscribe to={[CounterContainer]}>
{counter => (
<div>
<button onClick={() => counter.decrement()}>-</button>
<span>{counter.state.count}</span>
<button onClick={() => counter.increment()}>+</button>
</div>
)}
</Subscribe>
);
}
render(
<Provider>
<Counter />
</Provider>,
document.getElementById('root')
);
```
For more examples, see the `example/` directory.
## Happy Customers
<h4 align="center">
"Unstated is a breath of fresh air for state management. I rewrote my whole app to use it yesterday."
<br><br>
<a href="https://twitter.com/sindresorhus">Sindre Sorhus</a>
</h4>
<h4 align="center">
"When people say you don't need Redux most of the time, they actually mean you do need Unstated.<br>It's like setState on fucking horse steroids"
<br><br>
<a href="https://twitter.com/ken_wheeler">Ken Wheeler</a> (obviously)
</h4>
## 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 (
<div>
<span>{this.state.count}</span>
<button onClick={this.decrement}>-</button>
<button onClick={this.increment}>+</button>
</div>
);
}
}
```
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.Consumer>
{amount => (
<div>
<span>{this.state.count}</span>
<button onClick={() => this.decrement(amount)}>-</button>
<button onClick={() => this.increment(amount)}>+</button>
</div>
)}
</Amount.Consumer>
);
}
}
class AmountAdjuster extends React.Component {
state = { amount: 0 };
handleChange = event => {
this.setState({
amount: parseInt(event.currentTarget.value, 10)
});
};
render() {
return (
<Amount.Provider value={this.state.amount}>
<div>
{this.props.children}
<input type="number" value={this.state.amount} onChange={this.handleChange}/>
</div>
</Amount.Provider>
);
}
}
render(
<AmountAdjuster>
<Counter/>
</AmountAdjuster>
);
```
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.
##### `<Subscribe>`
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 `<Subscribe>` component which allows us to pass our
container classes/instances and receive instances of them in the tree.
```jsx
function Counter() {
return (
<Subscribe to={[CounterContainer]}>
{counter => (
<div>
<span>{counter.state.count}</span>
<button onClick={counter.decrement}>-</button>
<button onClick={counter.increment}>+</button>
</div>
)}
</Subscribe>
);
}
```
`<Subscribe>` will automatically construct our container and listen for changes.
##### `<Provider>`
The final piece that we'll need is something to store all of our instances
internally. For this we have `<Provider>`.
```jsx
render(
<Provider>
<Counter />
</Provider>
);
```
We can do some interesting things with `<Provider>` as well like dependency
injection:
```jsx
let counter = new CounterContainer();
render(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
```
### 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(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
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(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
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
<Tabs>
<Tab>One</Tab>
<Tab>Two</Tab>
<Tab>Three</Tab>
</Tabs>
```
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 `<Subscribe to>`
If you want to use your own instance of a container directly to `<Subscribe>`
and you don't care about dependency injection, you can do so:
<!-- prettier-ignore -->
```jsx
let counter = new CounterContainer();
function Counter() {
return (
<Subscribe to={[counter]}>
{counter => <div>...</div>}
</Subscribe>
);
}
```
You just need to keep a couple things in mind:
1. You are opting out of dependency injection, you won't be able to
`<Provider inject>` another instance in your tests.
2. Your instance will be local to whatever `<Subscribe>`'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 `<Provider inject>` 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 `<Provider inject>`.
```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(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
```
## 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 (
<Subscribe to={[CounterContainer]}>
{counter => (
<div>
<span>{counter.state.count}</span>
<button id="decrement" onClick={() => counter.decrement()}>
-
</button>
<button id="increment" onClick={() => counter.increment()}>
+
</button>
</div>
)}
</Subscribe>
);
}
test('should incresase/decrease state counter in container', async () => {
let counter = new CounterContainer();
let tree = render(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
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(
<Provider inject={[counter]}>
<Counter />
</Provider>
);
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 <Subscribe> component is not wrapper with <Provider>', () => {
spyOn(console, 'error');
expect(() => render(<Counter />)).toThrowError(
'You must wrap your <Subscribe> components with a <Provider>'
);
});
================================================
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 (
<Subscribe to={[CounterContainer]}>
{(counter: CounterContainer) => (
<div>
<span>{counter.state.count}</span>
<button onClick={() => counter.decrement()}>-</button>
<button onClick={() => counter.increment()}>+</button>
</div>
)}
</Subscribe>
);
}
function CounterWithAmount() {
return (
<Subscribe to={[CounterContainer, AmounterContainer]}>
{(counter: CounterContainer, amounter: AmounterContainer) => (
<div>
<span>{counter.state.count}</span>
<button onClick={() => counter.decrement(amounter.state.amount)}>
-
</button>
<button onClick={() => counter.increment(amounter.state.amount)}>
+
</button>
</div>
)}
</Subscribe>
);
}
function CounterWithAmountApp() {
return (
<Subscribe to={[AmounterContainer]}>
{(amounter: AmounterContainer) => (
<div>
<Counter />
<input
type="number"
value={amounter.state.amount}
onChange={event => {
amounter.setAmount(parseInt(event.currentTarget.value, 10));
}}
/>
</div>
)}
</Subscribe>
);
}
const sharedAmountContainer = new AmounterContainer();
function CounterWithSharedAmountApp() {
return (
<Subscribe to={[sharedAmountContainer]}>
{(amounter: AmounterContainer) => (
<div>
<Counter />
<input
type="number"
value={amounter.state.amount}
onChange={event => {
amounter.setAmount(parseInt(event.currentTarget.value, 10));
}}
/>
</div>
)}
</Subscribe>
);
}
let counter = new CounterContainer();
let render = () => (
<Provider inject={[counter]}>
<Counter />
</Provider>
);
================================================
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<AppState> {
state = {
amount: 1
};
setAmount(amount: number) {
this.setState({ amount });
}
}
type CounterState = {
count: number
};
class CounterContainer extends Container<CounterState> {
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 (
<Subscribe to={[AppContainer, CounterContainer]}>
{(app, counter) => (
<div>
<span>Count: {counter.state.count}</span>
<button onClick={() => counter.decrement(app.state.amount)}>-</button>
<button onClick={() => counter.increment(app.state.amount)}>+</button>
</div>
)}
</Subscribe>
);
}
function App() {
return (
<Subscribe to={[AppContainer]}>
{app => (
<div>
<Counter />
<label>Amount: </label>
<input
type="number"
value={app.state.amount}
onChange={event => {
app.setAmount(parseInt(event.currentTarget.value, 10));
}}
/>
</div>
)}
</Subscribe>
);
}
render(
<Provider>
<App />
</Provider>,
window.complex
);
================================================
FILE: example/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Unstated - Examples</title>
</head>
<body>
<h3>Simple</h3>
<div id="simple"></div>
<script type="text/javascript" src="./simple.js"></script>
<h3>Complex</h3>
<div id="complex"></div>
<script type="text/javascript" src="./complex.js"></script>
<h3>Shared</h3>
<div id="shared"></div>
<script type="text/javascript" src="./shared.js"></script>
</body>
</html>
================================================
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<CounterState> {
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 (
<Subscribe to={[sharedCounterContainer]}>
{counter => (
<div>
<button onClick={() => counter.decrement()}>-</button>
<span>{counter.state.count}</span>
<button onClick={() => sharedCounterContainer.increment()}>+</button>
</div>
)}
</Subscribe>
);
}
render(
<Provider>
<Counter />
</Provider>,
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<CounterState> {
state = { count: 0 };
increment() {
this.setState({ count: this.state.count + 1 });
}
decrement() {
this.setState({ count: this.state.count - 1 });
}
}
function Counter() {
return (
<Subscribe to={[CounterContainer]}>
{counter => (
<div>
<button onClick={() => counter.decrement()}>-</button>
<span>{counter.state.count}</span>
<button onClick={() => counter.increment()}>+</button>
</div>
)}
</Subscribe>
);
}
render(
<Provider>
<Counter />
</Provider>,
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<TArguments: $ReadOnlyArray<*>, 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<TArguments>,
/**
* An array that contains all the object instances that have been
* instantiated from this mock function.
*/
instances: Array<TReturn>
},
/**
* 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<TArguments, TReturn>,
/**
* 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<TArguments, TReturn>,
/**
* Just a simple sugar function for returning `this`
*/
mockReturnThis(): void,
/**
* Deprecated: use jest.fn(() => value) instead
*/
mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,
/**
* Sugar for only returning a value once inside your mock
*/
mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>
};
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<any>): 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<any>): 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<any>): 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<any>): 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<any>): void,
/**
* Use .toHaveBeenLastCalledWith to ensure that a mock function was last called
* with specific arguments.
*/
toHaveBeenLastCalledWith(...args: Array<any>): 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<Object>): 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<Error> | RegExp): void,
toThrowError(message?: string | Error | Class<Error> | 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<TArguments: $ReadOnlyArray<*>, TReturn>(
implementation?: (...args: TArguments) => TReturn
): JestMockFn<TArguments, TReturn>,
/**
* 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<any, any>,
/**
* 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<mixed>,
timeout?: number
): void;
/** Runs this function before every test inside this context */
declare function beforeEach(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** Runs this function after all tests have finished inside this context */
declare function afterAll(
fn: (done: () => void) => ?Promise<mixed>,
timeout?: number
): void;
/** Runs this function before any tests have started inside this context */
declare function beforeAll(
fn: (done: () => void) => ?Promise<mixed>,
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<mixed>,
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<mixed>,
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<mixed>,
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<mixed>,
timeout?: number
): void
};
declare function fit(
name: string,
fn: (done: () => void) => ?Promise<mixed>,
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<mixed>): 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<mixed>): void,
clock(): JestClockType,
createSpy(name: string): JestSpyType,
createSpyObj(
baseName: string,
methodNames: Array<string>
): { [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 <me@thejameskyle.com>",
"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 extends object> {
state: State;
setState<K extends keyof State>(
state:
| ((prevState: Readonly<State>) => Pick<State, K> | State | null)
| (Pick<State, K> | State | null),
callback?: () => void
): Promise<void>;
subscribe(fn: () => any): void;
unsubscribe(fn: () => any): void;
}
export interface ContainerType<State extends object> {
new (...args: any[]): Container<State>;
}
interface SubscribeProps {
to: (ContainerType<any> | Container<any>)[];
children(...instances: Container<any>[]): React.ReactNode;
}
export class Subscribe extends React.Component<SubscribeProps> {}
export interface ProviderProps {
inject?: Container<any>[];
children: React.ReactNode;
}
export const Provider: React.SFC<ProviderProps>;
================================================
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: State;
_listeners: Array<Listener> = [];
constructor() {
CONTAINER_DEBUG_CALLBACKS.forEach(cb => cb(this));
}
setState(
updater: $Shape<State> | ((prevState: $Shape<State>) => $Shape<State>),
callback?: () => void
): Promise<void> {
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<Object>;
export type ContainersType = Array<Class<ContainerType> | ContainerType>;
export type ContainerMapType = Map<Class<ContainerType>, ContainerType>;
export type SubscribeProps<Containers: ContainersType> = {
to: Containers,
children: (
...instances: $TupleMap<Containers, <C>(Class<C> | C) => C>
) => Node
};
type SubscribeState = {};
const DUMMY_STATE = {};
export class Subscribe<Containers: ContainersType> extends React.Component<
SubscribeProps<Containers>,
SubscribeState
> {
state = {};
instances: Array<ContainerType> = [];
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<ContainerType> {
this._unsubscribe();
if (map === null) {
throw new Error(
'You must wrap your <Subscribe> components with a <Provider>'
);
}
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 (
<StateContext.Consumer>
{map =>
this.props.children.apply(
null,
this._createInstances(map, this.props.to)
)
}
</StateContext.Consumer>
);
}
}
export type ProviderProps = {
inject?: Array<ContainerType>,
children: Node
};
export function Provider(props: ProviderProps) {
return (
<StateContext.Consumer>
{parentMap => {
let childMap = new Map(parentMap);
if (props.inject) {
props.inject.forEach(instance => {
childMap.set(instance.constructor, instance);
});
}
return (
<StateContext.Provider value={childMap}>
{props.children}
</StateContext.Provider>
);
}}
</StateContext.Consumer>
);
}
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<any>) => 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"]
}
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
SYMBOL INDEX (25 symbols across 6 files)
FILE: __tests__/unstated.js
function render (line 6) | function render(element) {
function click (line 10) | async function click({ children = [] }, id) {
class CounterContainer (line 15) | class CounterContainer extends Container<{ count: number }> {
function Counter (line 25) | function Counter() {
FILE: __tests__/unstated.tsx
class CounterContainer (line 4) | class CounterContainer extends Container<{ count: number }> {
method increment (line 6) | increment(amount = 1) {
method decrement (line 9) | decrement(amount = 1) {
class AmounterContainer (line 14) | class AmounterContainer extends Container<{ amount: number }> {
method setAmount (line 16) | setAmount(amount: number) {
function Counter (line 21) | function Counter() {
function CounterWithAmount (line 35) | function CounterWithAmount() {
function CounterWithAmountApp (line 53) | function CounterWithAmountApp() {
function CounterWithSharedAmountApp (line 74) | function CounterWithSharedAmountApp() {
FILE: example/shared.js
class CounterContainer (line 10) | class CounterContainer extends Container<CounterState> {
function Counter (line 24) | function Counter() {
FILE: example/simple.js
class CounterContainer (line 10) | class CounterContainer extends Container<CounterState> {
function Counter (line 22) | function Counter() {
FILE: src/unstated.d.ts
class Container (line 3) | class Container<State extends object> {
type ContainerType (line 15) | interface ContainerType<State extends object> {
type SubscribeProps (line 19) | interface SubscribeProps {
class Subscribe (line 24) | class Subscribe extends React.Component<SubscribeProps> {}
type ProviderProps (line 26) | interface ProviderProps {
FILE: src/unstated.js
constant DUMMY_STATE (line 69) | const DUMMY_STATE = {};
function Provider (line 159) | function Provider(props: ProviderProps) {
constant CONTAINER_DEBUG_CALLBACKS (line 181) | let CONTAINER_DEBUG_CALLBACKS = [];
Condensed preview — 20 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (53K chars).
[
{
"path": ".babelrc",
"chars": 33,
"preview": "{ \"presets\": [\"./.babelrc.js\"] }\n"
},
{
"path": ".babelrc.js",
"chars": 435,
"preview": "const { BABEL_ENV, NODE_ENV } = process.env;\nconst cjs = BABEL_ENV === 'cjs' || NODE_ENV === 'test';\n\nmodule.exports = {"
},
{
"path": ".flowconfig",
"chars": 58,
"preview": "[ignore]\n\n[include]\n\n[libs]\n\n[lints]\n\n[options]\n\n[strict]\n"
},
{
"path": ".gitignore",
"chars": 43,
"preview": "node_modules\n*.log\nlib\n.cache\ndist\ncoverage"
},
{
"path": ".prettierrc",
"chars": 26,
"preview": "{\n \"singleQuote\": true\n}\n"
},
{
"path": ".travis.yml",
"chars": 183,
"preview": "git:\n depth: 1\nsudo: false\nlanguage: node_js\nnode_js:\n - '8'\ncache:\n yarn: true\n directories:\n - node_modules\nscr"
},
{
"path": "LICENSE",
"chars": 1084,
"preview": "Copyright (c) 2018-present James Kyle <me@thejameskyle.com>\n\nPermission is hereby granted, free of charge, to any person"
},
{
"path": "README.md",
"chars": 13676,
"preview": "<div align=\"center\">\n <br><br><br><br><br>\n <img src=\"https://raw.githubusercontent.com/thejameskyle/unstated/master/l"
},
{
"path": "__tests__/unstated.js",
"chars": 2181,
"preview": "// @flow\nimport React from 'react';\nimport renderer from 'react-test-renderer';\nimport { Provider, Subscribe, Container "
},
{
"path": "__tests__/unstated.tsx",
"chars": 2425,
"preview": "import * as React from 'react';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\nclass CounterContaine"
},
{
"path": "example/complex.js",
"chars": 1511,
"preview": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '"
},
{
"path": "example/index.html",
"chars": 473,
"preview": "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>Unstated - Examples</title>\n </head>\n <body>\n "
},
{
"path": "example/shared.js",
"chars": 889,
"preview": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '"
},
{
"path": "example/simple.js",
"chars": 812,
"preview": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '"
},
{
"path": "flow-typed/npm/jest_v22.x.x.js",
"chars": 18438,
"preview": "// flow-typed signature: 6e1fc0a644aa956f79029fec0709e597\n// flow-typed version: 07ebad4796/jest_v22.x.x/flow_>=v0.39.x\n"
},
{
"path": "package.json",
"chars": 1677,
"preview": "{\n \"name\": \"unstated\",\n \"version\": \"2.1.1\",\n \"description\": \"State so simple, it goes without saying\",\n \"main\": \"lib"
},
{
"path": "rollup.config.js",
"chars": 382,
"preview": "import babel from 'rollup-plugin-babel';\nimport pkg from './package.json';\n\nexport default {\n input: 'src/unstated.js',"
},
{
"path": "src/unstated.d.ts",
"chars": 822,
"preview": "import * as React from 'react';\n\nexport class Container<State extends object> {\n state: State;\n setState<K extends key"
},
{
"path": "src/unstated.js",
"chars": 4260,
"preview": "// @flow\nimport React, { type Node } from 'react';\nimport createReactContext from 'create-react-context';\n\ntype Listener"
},
{
"path": "tsconfig.json",
"chars": 310,
"preview": "{\n \"compilerOptions\": {\n \"module\": \"commonjs\",\n \"target\": \"es5\",\n \"lib\": [\"es6\", \"dom\"],\n \"sourceMap\": true"
}
]
About this extraction
This page contains the full source code of the jamiebuilds/unstated GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 20 files (48.6 KB), approximately 12.8k tokens, and a symbol index with 25 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.