|
1 | | -import {Component} from 'react'; |
2 | | -import renderProp from '../util/renderProp'; |
3 | | -import {IUniversalInterfaceProps} from '../typing'; |
| 1 | +import {h} from '../util'; |
| 2 | +import {Component, createContext} from 'react'; |
| 3 | +import {getGapiAuthInstance} from './gapi'; |
4 | 4 |
|
5 | | -export interface IGoogleAuthButtonProps extends IUniversalInterfaceProps<IGoogleAuthButtonState> { |
6 | | - clientId: string; |
| 5 | +export interface IGoogleAuthProviderProps { |
| 6 | + children; |
7 | 7 | } |
8 | 8 |
|
9 | | -export interface IGoogleAuthButtonState { |
10 | | - loading?: boolean; |
| 9 | +export interface IGoogleAuthProviderState { |
| 10 | + loading?: boolean; |
| 11 | + signIn: () => Promise<void>; |
| 12 | + signOut: () => Promise<void>; |
| 13 | + user: any | null; |
11 | 14 | } |
12 | 15 |
|
13 | | -export class GoogleAuthButton extends Component<IGoogleAuthButtonProps, IGoogleAuthButtonState> { |
| 16 | +export interface IGoogleAuthConsumerProps { |
| 17 | + children: (state: IGoogleAuthProviderState) => React.ReactNode; |
| 18 | +} |
| 19 | + |
| 20 | +export const createGoogleAuthContext = (clientId: string) => { |
| 21 | + const context = createContext({}); |
| 22 | + |
| 23 | + let googleAuth; |
| 24 | + const getAuthInstance = async () => { |
| 25 | + if (!googleAuth) { |
| 26 | + googleAuth = await getGapiAuthInstance(clientId); |
| 27 | + } |
| 28 | + |
| 29 | + return googleAuth; |
| 30 | + }; |
| 31 | + |
| 32 | + class Provider extends Component<IGoogleAuthProviderProps, IGoogleAuthProviderState> { |
| 33 | + state: IGoogleAuthProviderState = { |
| 34 | + signIn: async () => { |
| 35 | + const googleAuth = await getAuthInstance(); |
| 36 | + await googleAuth.signIn(); |
| 37 | + }, |
| 38 | + signOut: async () => { |
| 39 | + const googleAuth = await getAuthInstance(); |
| 40 | + await googleAuth.signOut(); |
| 41 | + }, |
| 42 | + user: null, |
| 43 | + }; |
| 44 | + |
14 | 45 | render () { |
15 | | - return renderProp(this.props, this.state); |
| 46 | + return h(context.Provider, {value: this.state}, this.props.children); |
16 | 47 | } |
17 | | -} |
| 48 | + } |
| 49 | + |
| 50 | + return { |
| 51 | + Provider, |
| 52 | + Consumer: context.Consumer as React.SFC<IGoogleAuthConsumerProps>, |
| 53 | + }; |
| 54 | +}; |
0 commit comments