This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
80 lines (65 loc) · 1.86 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import createBindings from "@grafoo/bindings";
import {
Context,
GrafooConsumerProps,
GrafooBoundState,
GrafooBoundMutations
} from "@grafoo/types";
import { Component, createContext, createElement, ReactElement, ReactNode, SFC } from "react";
/**
* T = Query
* U = Mutations
*/
type GrafooRenderFn<T, U> = (
renderProps: GrafooBoundState & T & GrafooBoundMutations<U>
) => ReactNode;
/**
* T = Query
* U = Mutations
*/
type GrafooReactConsumerProps<T = {}, U = {}> = GrafooConsumerProps<T, U> & {
children: GrafooRenderFn<T, U>;
};
/**
* T = Query
* U = Mutations
*/
interface ConsumerType extends SFC {
<T, U>(props: GrafooReactConsumerProps<T, U>): ReactElement<any> | null;
}
let ctx = createContext({});
export let Provider: SFC<Context> = props =>
createElement(ctx.Provider, { value: props.client }, props.children);
class GrafooConsumer<T, U> extends Component<GrafooReactConsumerProps<T, U>> {
state: GrafooBoundState & T & GrafooBoundMutations<U>;
constructor(props) {
super(props);
let bindings = createBindings<T, U>(props.client, props, () => {
this.setState(bindings.getState());
});
this.state = bindings.getState();
this.componentDidMount = () => {
if (props.skip || !props.query || this.state.loaded) return;
bindings.load();
};
this.componentWillReceiveProps = next => {
if ((!this.state.loaded && !next.skip) || props.variables !== next.variables) {
bindings.load(next.variables);
}
};
this.componentWillUnmount = () => {
bindings.unbind();
};
}
render() {
return this.props.children(this.state);
}
}
/**
* T = Query
* U = Mutations
*/
export let Consumer: ConsumerType = <T, U>(props: GrafooReactConsumerProps<T, U>) =>
createElement(ctx.Consumer, null, client =>
createElement(GrafooConsumer, Object.assign({ client }, props))
);