1 | import {GlobalVariable} from "@gongt/ts-stl-library/pattern/global-page-data";
|
2 | import * as PropTypes from "prop-types";
|
3 | import * as React from "react";
|
4 | import {WrapComponent} from "./render";
|
5 |
|
6 | export interface PropsType {
|
7 | global: GlobalVariable;
|
8 | }
|
9 |
|
10 | export interface GlobalContextContent {
|
11 | global: GlobalVariable;
|
12 | }
|
13 |
|
14 | export interface GlobalContext {
|
15 | context: GlobalContextContent;
|
16 | }
|
17 |
|
18 | export function WithGlobalContext<T extends React.ComponentClass<any>>(component: T): T {
|
19 | if (!component.contextTypes) {
|
20 | component.contextTypes = {};
|
21 | }
|
22 | if (!component.contextTypes.global) {
|
23 | component.contextTypes.global = PropTypes.object;
|
24 | }
|
25 | return component;
|
26 | }
|
27 |
|
28 | @WithGlobalContext
|
29 | export class ReactEmptyWrapper extends React.Component<WrapComponent, {}> {
|
30 | state: {subProps: any} = {subProps: null};
|
31 |
|
32 | static propTypes = {
|
33 | Component: PropTypes.instanceOf(React.Component).isRequired,
|
34 | componentName: PropTypes.string,
|
35 | props: PropTypes.func,
|
36 | };
|
37 |
|
38 | constructor(props, context) {
|
39 | super(props, context);
|
40 | this.state.subProps = this.props.props(this.context.global);
|
41 | }
|
42 |
|
43 | componentWillReceiveProps(nextProps, nextContext) {
|
44 | this.setState({
|
45 | subProps: this.props.props(this.context.global),
|
46 | });
|
47 | }
|
48 |
|
49 | render() {
|
50 | const Cm = this.props.Component;
|
51 | if (!Cm) {
|
52 | return <div>
|
53 | <h1 style={{color: 'red'}}>
|
54 | ReactEmptyWrapper: Invalid Child Component: {this.props.componentName}.
|
55 | </h1>
|
56 | {React.Children.only(this.props.children)}
|
57 | </div>;
|
58 | }
|
59 | console.log('ReactEmptyWrapper render(): ', Cm.displayName || Cm.name);
|
60 | return <Cm {...this.state.subProps}>
|
61 | {React.Children.only(this.props.children)}
|
62 | </Cm>;
|
63 | }
|
64 | }
|
65 |
|
66 | export class GlobalContextProvider extends React.Component<PropsType, {}> {
|
67 | static childContextTypes: React.ValidationMap<any> = {
|
68 | global: PropTypes.object,
|
69 | };
|
70 |
|
71 | getChildContext(): GlobalContextContent {
|
72 | return {
|
73 | global: this.props.global,
|
74 | };
|
75 | }
|
76 |
|
77 | render() {
|
78 | return React.Children.only(this.props.children);
|
79 | }
|
80 | }
|