-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathhoc-utils.tsx
More file actions
70 lines (58 loc) · 1.95 KB
/
Copy pathhoc-utils.tsx
File metadata and controls
70 lines (58 loc) · 1.95 KB
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
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import type { OperationVariables } from "../../core/index.js";
import type { IDocumentDefinition } from "../parser/index.js";
export const defaultMapPropsToOptions = () => ({});
export const defaultMapResultToProps: <P>(props: P) => P = (props) => props;
export const defaultMapPropsToSkip = () => false;
export function getDisplayName<P>(WrappedComponent: React.ComponentType<P>) {
return WrappedComponent.displayName || WrappedComponent.name || "Component";
}
export function calculateVariablesFromProps<TProps>(
operation: IDocumentDefinition,
props: TProps
) {
let variables: OperationVariables = {};
for (let { variable, type } of operation.variables) {
if (!variable.name || !variable.name.value) continue;
const variableName = variable.name.value;
const variableProp = (props as any)[variableName];
if (typeof variableProp !== "undefined") {
variables[variableName] = variableProp;
continue;
}
// Allow optional props
if (type.kind !== "NonNullType") {
variables[variableName] = undefined;
}
}
return variables;
}
export type RefSetter<TChildProps> = (
ref: React.ComponentClass<TChildProps>
) => void | void;
// base class for hocs to easily manage refs
export class GraphQLBase<
TProps,
TChildProps,
TState = any,
> extends React.Component<TProps, TState> {
public withRef: boolean = false;
// wrapped instance
private wrappedInstance?: React.ComponentClass<TChildProps>;
constructor(props: TProps) {
super(props);
this.setWrappedInstance = this.setWrappedInstance.bind(this);
}
getWrappedInstance() {
invariant(
this.withRef,
`To access the wrapped instance, you need to specify ` +
`{ withRef: true } in the options`
);
return this.wrappedInstance;
}
setWrappedInstance(ref: React.ComponentClass<TChildProps>) {
this.wrappedInstance = ref;
}
}