-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcomponent.tsx
More file actions
299 lines (277 loc) · 10.2 KB
/
component.tsx
File metadata and controls
299 lines (277 loc) · 10.2 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// tslint:disable:no-any
import { ApolloClient } from 'apollo-client';
import { JSONSchema6 } from 'json-schema';
import * as React from 'react';
import {
IChangeEvent,
UiSchema,
WidgetProps
} from 'react-jsonschema-form';
import { getTheme, ApolloFormTheme, ErrorListComponent } from './renderers';
import { FormRenderer } from './renderers';
import {
applyConditionsToSchema,
cleanData,
getSchemaFromConfig,
isMutationConfig,
ApolloFormConfig,
ReactJsonschemaFormError
} from './utils';
// see https://github.com/wittydeveloper/react-apollo-form/wiki/Getting-started:-build-a-GraphQL-Form-in-5-minutes
export type ApolloFormProps<T> = {
data: any;
title?: string;
subTitle?: string;
config: ApolloFormConfig & { mutation?: { name: T } };
onSave?: (data: object) => void;
onChange?: (data: object) => void;
onCancel?: () => void;
ui?: UiSchema & ApolloFormUi;
children?: React.SFC<ApolloRenderProps>;
liveValidate?: boolean;
transformErrors?: (formName: string) => (errors: ReactJsonschemaFormError[]) => ReactJsonschemaFormError[];
};
export interface ApolloFormState {
isDirty: boolean;
isSaved: boolean;
hasError: boolean;
// we store the original schema
schema: JSONSchema6;
// and we store the transformed schema (with applied UI conditionals)
schemaWithConditionals: JSONSchema6;
data: any;
}
// see https://github.com/wittydeveloper/react-apollo-form/wiki/Form-Rendering-customisation-with-renderers
export interface ApolloRenderProps {
// renderers
header: () => React.ReactNode;
form: () => React.ReactNode;
buttons: () => React.ReactNode;
saveButton: () => React.ReactNode;
cancelButton: () => React.ReactNode;
// actions
cancel: () => void;
save: (args: any) => void;
// state
isDirty: boolean;
isSaved: boolean;
hasError: boolean;
data: any;
}
export interface ApolloFormConfigureTheme {
templates?: ApolloFormTheme['templates'];
widgets?: ApolloFormTheme['widgets'];
fields?: ApolloFormTheme['fields'];
renderers?: Partial<ApolloFormTheme['renderers']>;
}
export interface ApolloFormConfigureOptions {
client: ApolloClient<any>;
theme?: ApolloFormConfigureTheme;
jsonSchema: JSONSchema6;
i18n?: (key: string) => string;
}
// Augment SchemaUi for ApolloForm ui prop
export type ApolloFormUi = {
showErrorsList?: boolean;
showErrorsInline?: boolean;
errorListComponent?: ErrorListComponent;
};
export type ApolloFormComponent<T> = React.ComponentClass<ApolloFormProps<T>> & {
registerWidget: (name: string, comp: React.SFC<WidgetProps>) => void;
};
// tslint:disable-next-line:max-line-length
export function configure<MutationNamesType = {}>(opts: ApolloFormConfigureOptions): ApolloFormComponent<MutationNamesType> {
const jsonSchema: JSONSchema6 = opts.jsonSchema;
const theme = getTheme(opts.theme);
return class ApolloForm extends React.Component<ApolloFormProps<MutationNamesType>, ApolloFormState> {
submitBtn: HTMLInputElement | null = null;
state: ApolloFormState = {
isDirty: false,
isSaved: false,
hasError: false,
schema: {},
schemaWithConditionals: {},
data: {}
};
static registerWidget = (name: string, comp: React.SFC<WidgetProps>) => {
theme.widgets[name] = comp;
}
componentDidMount() {
const schema = getSchemaFromConfig(jsonSchema, this.props.config, this.props.title);
this.setState(() => ({
schema,
data: this.props.data,
schemaWithConditionals: applyConditionsToSchema(
schema,
this.props.ui,
this.props.data
)
}));
}
componentDidUpdate(prevProps: ApolloFormProps<MutationNamesType>) {
const { config } = this.props;
const { config: prevConfig } = prevProps;
if (config && isMutationConfig(config) && !!config.mutation) {
if (isMutationConfig(prevConfig) && !!prevConfig.mutation) {
const currentMutationName = config.mutation.name;
const previousMutationName = prevConfig.mutation.name;
if (currentMutationName !== previousMutationName) {
this.setState(
{
schema: getSchemaFromConfig(jsonSchema, config, this.props.title)
},
() => this.setState({
schemaWithConditionals: applyConditionsToSchema(
this.state.schema,
this.props.ui,
this.state.data
)
})
);
}
} else {
this.setState(
{
schema: getSchemaFromConfig(jsonSchema, config, this.props.title)
},
() => this.setState({
schemaWithConditionals: applyConditionsToSchema(
this.state.schema,
this.props.ui,
this.state.data
)
})
);
}
}
}
// build save handler for <Form> component
save = ({ formData }: any) => { // TODO: remove args
const { config, onSave } = this.props;
if (isMutationConfig(config)) {
const { mutation: { document, variables, context, refetchQueries } } = config;
const data = cleanData(formData, this.state.schema.properties || {});
opts.client.mutate({
mutation: document,
refetchQueries,
variables: {
...data,
...(variables || {})
},
context: context
}).then(() => {
this.setState(() => ({ isDirty: false, isSaved: true, hasError: false }));
if (onSave) {
onSave(data);
}
});
} else {
config.saveData(formData);
}
}
cancel = () => {
const { props } = this;
if (props.onCancel) {
props.onCancel();
}
}
onChange = (data: IChangeEvent) => {
const newSchema = applyConditionsToSchema(
this.state.schema,
this.props.ui,
data.formData
);
this.setState(
() => ({
isDirty: true,
data: cleanData(data.formData, newSchema.properties),
schemaWithConditionals: newSchema,
hasError: data.errors.length > 0,
isSaved: false
}),
() => {
if (this.props.onChange) {
this.props.onChange(this.state.data);
}
}
);
}
simulateSubmit = () => {
if (this.submitBtn) {
this.submitBtn.click();
}
}
childrenProps = (): ApolloRenderProps => ({
// renderers
header: () => theme.renderers.header({ title: this.props.title || 'Form' }),
form: this.renderForm,
buttons: () => theme.renderers.buttons({
cancelButtonRenderer: theme.renderers.cancelButton,
saveButtonRenderer: theme.renderers.saveButton,
cancel: this.cancel,
save: this.simulateSubmit,
hasError: this.state.hasError,
isSaved: this.state.isSaved,
isDirty: this.state.isDirty
}),
saveButton: () => theme.renderers.saveButton({
save: this.simulateSubmit,
hasError: this.state.hasError,
isDirty: this.state.isDirty,
isSaved: this.state.isSaved
}),
cancelButton: () => theme.renderers.cancelButton({ cancel: this.cancel }),
// actions
cancel: this.cancel,
save: this.simulateSubmit,
// state,
data: this.state.data,
isDirty: this.state.isDirty,
isSaved: this.state.isSaved,
hasError: this.state.hasError
})
renderLayout = () => {
const { props } = this;
const { buttons, header, form } = this.childrenProps();
return (
<div>
{header()}
{form()}
{buttons()}
</div>
);
}
renderForm = () => {
return (
<FormRenderer
theme={theme}
onChange={this.onChange}
save={this.save}
transformErrors={
this.props.transformErrors ?
this.props.transformErrors :
undefined
}
config={this.props.config}
ui={this.props.ui}
liveValidate={this.props.liveValidate}
schema={this.state.schemaWithConditionals}
data={this.state.data}
subTitle={this.props.subTitle}
isDirty={this.state.isDirty}
>
<input type="submit" style={{ display: 'none' }} ref={el => this.submitBtn = el} />
</FormRenderer>
);
}
render() {
const { props } = this;
const children = props.children as ApolloFormProps<MutationNamesType>['children'];
return (
children ?
children(this.childrenProps()) :
this.renderLayout()
);
}
};
}