Skip to content

Commit

Permalink
State containers (#52384) (#52421)
Browse files Browse the repository at this point in the history
* feat: 🎸 add state containers

* docs: ✏️ add state container demos

* docs: ✏️ refrech state container docs

* chore: πŸ€– install default comparator

* chore: πŸ€– remove old state container implementation

* feat: 🎸 add selectors

* chore: πŸ€– move Ensure tyep to type utils

* fix: πŸ› fix useSelector() types and demo CLI command

* test: πŸ’ add tests for state container demos

* feat: 🎸 add ReacursiveReadonly to kbn-utility-types

* feat: 🎸 shallow freeze state when not in production

* test: πŸ’ fix Jest tests

* refactor: πŸ’‘ remove .state and use BehaviourSubject
  • Loading branch information
streamich authored Dec 6, 2019
1 parent 7671ce3 commit db342e9
Show file tree
Hide file tree
Showing 36 changed files with 1,275 additions and 750 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@
"encode-uri-query": "1.0.1",
"execa": "^3.2.0",
"expiry-js": "0.1.7",
"fast-deep-equal": "^3.1.1",
"file-loader": "4.2.0",
"font-awesome": "4.7.0",
"getos": "^3.1.0",
Expand Down Expand Up @@ -226,6 +227,7 @@
"react-resize-detector": "^4.2.0",
"react-router-dom": "^4.3.1",
"react-sizeme": "^2.3.6",
"react-use": "^13.10.2",
"reactcss": "1.2.3",
"redux": "4.0.0",
"redux-actions": "2.2.1",
Expand Down
8 changes: 5 additions & 3 deletions packages/kbn-utility-types/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ type B = UnwrapPromise<A>; // string

## Reference

- `UnwrapPromise<T>` &mdash; Returns wrapped type of a promise.
- `UnwrapObservable<T>` &mdash; Returns wrapped type of an observable.
- `ShallowPromise<T>` &mdash; Same as `Promise` type, but it flat maps the wrapped type.
- `Ensure<T, X>` &mdash; Makes sure `T` is of type `X`.
- `ObservableLike<T>` &mdash; Minimal interface for an object resembling an `Observable`.
- `RecursiveReadonly<T>` &mdash; Like `Readonly<T>`, but freezes object recursively.
- `ShallowPromise<T>` &mdash; Same as `Promise` type, but it flat maps the wrapped type.
- `UnwrapObservable<T>` &mdash; Returns wrapped type of an observable.
- `UnwrapPromise<T>` &mdash; Returns wrapped type of a promise.
16 changes: 16 additions & 0 deletions packages/kbn-utility-types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,19 @@ export type UnwrapObservable<T extends ObservableLike<any>> = T extends Observab
* Converts a type to a `Promise`, unless it is already a `Promise`. Useful when proxying the return value of a possibly async function.
*/
export type ShallowPromise<T> = T extends Promise<infer U> ? Promise<U> : Promise<T>;

/**
* Ensures T is of type X.
*/
export type Ensure<T, X> = T extends X ? T : never;

// If we define this inside RecursiveReadonly TypeScript complains.
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface RecursiveReadonlyArray<T> extends Array<RecursiveReadonly<T>> {}
export type RecursiveReadonly<T> = T extends (...args: any) => any
? T
: T extends any[]
? RecursiveReadonlyArray<T[number]>
: T extends object
? Readonly<{ [K in keyof T]: RecursiveReadonly<T[K]> }>
: T;
2 changes: 1 addition & 1 deletion src/plugins/kibana_utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

Utilities for building Kibana plugins.

- [Store reactive serializable app state in state containers, `createStore`](./docs/store/README.md).
- [State containers](./docs/state_containers/README.md).
36 changes: 36 additions & 0 deletions src/plugins/kibana_utils/demos/demos.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { result as counterResult } from './state_containers/counter';
import { result as todomvcResult } from './state_containers/todomvc';

describe('demos', () => {
describe('state containers', () => {
test('counter demo works', () => {
expect(counterResult).toBe(10);
});

test('TodoMVC demo works', () => {
expect(todomvcResult).toEqual([
{ id: 0, text: 'Learning state containers', completed: true },
{ id: 1, text: 'Learning transitions...', completed: true },
]);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,16 @@
* under the License.
*/

import { Observable } from 'rxjs';
import { Store as ReduxStore } from 'redux';
import { createStateContainer } from '../../public/state_containers';

export interface AppStore<
State extends {},
StateMutators extends Mutators<PureMutators<State>> = {}
> {
redux: ReduxStore;
get: () => State;
set: (state: State) => void;
state$: Observable<State>;
createMutators: <M extends PureMutators<State>>(pureMutators: M) => Mutators<M>;
mutators: StateMutators;
}
const container = createStateContainer(0, {
increment: (cnt: number) => (by: number) => cnt + by,
double: (cnt: number) => () => cnt * 2,
});

export type PureMutator<State extends {}> = (state: State) => (...args: any[]) => State;
export type Mutator<M extends PureMutator<any>> = (...args: Parameters<ReturnType<M>>) => void;
container.transitions.increment(5);
container.transitions.double();

export interface PureMutators<State extends {}> {
[name: string]: PureMutator<State>;
}
console.log(container.get()); // eslint-disable-line

export type Mutators<M extends PureMutators<any>> = { [K in keyof M]: Mutator<M[K]> };
export const result = container.get();
69 changes: 69 additions & 0 deletions src/plugins/kibana_utils/demos/state_containers/todomvc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { createStateContainer, PureTransition } from '../../public/state_containers';

export interface TodoItem {
text: string;
completed: boolean;
id: number;
}

export type TodoState = TodoItem[];

export const defaultState: TodoState = [
{
id: 0,
text: 'Learning state containers',
completed: false,
},
];

export interface TodoActions {
add: PureTransition<TodoState, [TodoItem]>;
edit: PureTransition<TodoState, [TodoItem]>;
delete: PureTransition<TodoState, [number]>;
complete: PureTransition<TodoState, [number]>;
completeAll: PureTransition<TodoState, []>;
clearCompleted: PureTransition<TodoState, []>;
}

export const pureTransitions: TodoActions = {
add: state => todo => [...state, todo],
edit: state => todo => state.map(item => (item.id === todo.id ? { ...item, ...todo } : item)),
delete: state => id => state.filter(item => item.id !== id),
complete: state => id =>
state.map(item => (item.id === id ? { ...item, completed: true } : item)),
completeAll: state => () => state.map(item => ({ ...item, completed: true })),
clearCompleted: state => () => state.filter(({ completed }) => !completed),
};

const container = createStateContainer<TodoState, TodoActions>(defaultState, pureTransitions);

container.transitions.add({
id: 1,
text: 'Learning transitions...',
completed: false,
});
container.transitions.complete(0);
container.transitions.complete(1);

console.log(container.get()); // eslint-disable-line

export const result = container.get();
50 changes: 50 additions & 0 deletions src/plugins/kibana_utils/docs/state_containers/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# State containers

State containers are Redux-store-like objects meant to help you manage state in
your services or apps.

- State containers are strongly typed, you will get TypeScript autocompletion suggestions from
your editor when accessing state, executing transitions and using React helpers.
- State containers can be easily hooked up with your React components.
- State containers can be used without React, too.
- State containers provide you central place where to store state, instead of spreading
state around multiple RxJs observables, which you need to coordinate. With state
container you can always access the latest state snapshot synchronously.
- Unlike Redux, state containers are less verbose, see example below.


## Example

```ts
import { createStateContainer } from 'src/plugins/kibana_utils';

const container = createStateContainer(0, {
increment: (cnt: number) => (by: number) => cnt + by,
double: (cnt: number) => () => cnt * 2,
});

container.transitions.increment(5);
container.transitions.double();
console.log(container.get()); // 10
```


## Demos

See demos [here](../../demos/state_containers/).

You can run them with

```
npx -q ts-node src/plugins/kibana_utils/demos/state_containers/counter.ts
npx -q ts-node src/plugins/kibana_utils/demos/state_containers/todomvc.ts
```


## Reference

- [Creating a state container](./creation.md).
- [State transitions](./transitions.md).
- [Using with React](./react.md).
- [Using without React`](./no_react.md).
- [Parallels with Redux](./redux.md).
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface MyState {
}
```

Create default state of your *store*.
Create default state of your container.

```ts
const defaultState: MyState = {
Expand All @@ -27,17 +27,12 @@ const defaultState: MyState = {
};
```

Create your state container, i.e *store*.
Create your a state container.

```ts
import { createStore } from 'kibana-utils';
import { createStateContainer } from 'src/plugins/kibana_utils';

const store = createStore<MyState>(defaultState);
console.log(store.get());
```
const container = createStateContainer<MyState>(defaultState, {});

> ##### N.B.
>
> State must always be an object `{}`.
>
> You cannot create a store out of an array, e.g ~~`createStore([])`~~.
console.log(container.get());
```
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Reading state
# Consuming state in non-React setting

To read the current `state` of the store use `.get()` method.

Expand Down
41 changes: 41 additions & 0 deletions src/plugins/kibana_utils/docs/state_containers/react.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# React

`createStateContainerReactHelpers` factory allows you to easily use state containers with React.


## Example


```ts
import { createStateContainer, createStateContainerReactHelpers } from 'src/plugins/kibana_utils';

const container = createStateContainer({}, {});
export const {
Provider,
Consumer,
context,
useContainer,
useState,
useTransitions,
useSelector,
connect,
} = createStateContainerReactHelpers<typeof container>();
```

Wrap your app with `<Provider>`.

```tsx
<Provider value={container}>
<MyApplication />
</Provider>
```


## Reference

- [`useContainer()`](./react/use_container.md)
- [`useState()`](./react/use_state.md)
- [`useSelector()`](./react/use_selector.md)
- [`useTransitions()`](./react/use_transitions.md)
- [`connect()()`](./react/connect.md)
- [Context](./react/context.md)
22 changes: 22 additions & 0 deletions src/plugins/kibana_utils/docs/state_containers/react/connect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# `connect()()` higher order component

Use `connect()()` higher-order-component to inject props from state into your component.

```tsx
interface Props {
name: string;
punctuation: '.' | ',' | '!',
}
const Demo: React.FC<Props> = ({ name, punctuation }) =>
<div>Hello, {name}{punctuation}</div>;

const store = createStateContainer({ userName: 'John' });
const { Provider, connect } = createStateContainerReactHelpers(store);

const mapStateToProps = ({ userName }) => ({ name: userName });
const DemoConnected = connect<Props, 'name'>(mapStateToProps)(Demo);

<Provider>
<DemoConnected punctuation="!" />
</Provider>
```
24 changes: 24 additions & 0 deletions src/plugins/kibana_utils/docs/state_containers/react/context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# React context

`createStateContainerReactHelpers` returns `<Provider>` and `<Consumer>` components
as well as `context` React context object.

```ts
export const {
Provider,
Consumer,
context,
} = createStateContainerReactHelpers<typeof container>();
```

`<Provider>` and `<Consumer>` are just regular React context components.

```tsx
<Provider value={container}>
<div>
<Consumer>{container =>
<pre>{JSON.stringify(container.get())}</pre>
}</Consumer>
</div>
</Provider>
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# `useContainer` hook

`useContainer` React hook will simply return you `container` object from React context.

```tsx
const Demo = () => {
const store = useContainer();
return <div>{store.get().isDarkMode ? 'πŸŒ‘' : 'β˜€οΈ'}</div>;
};
```
Loading

0 comments on commit db342e9

Please sign in to comment.