/
RelayPlayground.js
374 lines (365 loc) · 11.8 KB
/
RelayPlayground.js
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/* eslint-disable no-unused-vars, no-eval */
import './RelayPlayground.css';
import 'codemirror/mode/javascript/javascript';
import React from 'react';
import PropTypes from 'prop-types';
import Codemirror from 'react-codemirror';
import ReactDOM from 'react-dom';
import Relay from 'react-relay'; window.Relay = Relay;
import RelayLocalSchema from 'relay-local-schema';
import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin';
import debounce from 'lodash.debounce';
import defer from 'lodash.defer';
import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher';
import errorCatcherPlugin from 'babel-plugin-react-error-catcher';
import evalSchema from './evalSchema';
import getBabelRelayPlugin from 'babel-relay-plugin';
import {transform} from 'babel-core';
import {introspectionQuery} from 'graphql/utilities';
import {graphql} from 'graphql';
const CODE_EDITOR_OPTIONS = {
extraKeys: {
Tab(cm) {
// Insert spaces when the tab key is pressed
const spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
cm.replaceSelection(spaces);
},
},
indentWithTabs: false,
lineNumbers: true,
mode: 'javascript',
tabSize: 2,
theme: 'solarized light',
};
const ERROR_TYPES = {
graphql: 'GraphQL Validation',
query: 'Query',
runtime: 'Runtime',
schema: 'Schema',
syntax: 'Syntax',
};
const RENDER_STEP_EXAMPLE_CODE =
`ReactDOM.render(
<Relay.RootContainer
Component={MyRelayContainer}
route={new MyHomeRoute()}
/>,
mountNode
);`;
function errorFromGraphQLResultAndQuery(errors, request) {
const queryString = request.getQueryString();
const variables = request.getVariables();
let errorText = `
${errors.map(e => e.message).join('\n')}
Query: ${queryString}
`;
if (variables) {
errorText += `Variables: ${JSON.stringify(variables)}`;
}
return {stack: errorText.trim()};
}
class PlaygroundRenderer extends React.Component {
componentDidMount() {
this._container = document.createElement('div');
this.refs.mountPoint.appendChild(this._container);
this._updateTimeoutId = defer(this._update);
}
componentDidUpdate(prevProps) {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
this._updateTimeoutId = defer(this._update);
}
componentWillUnmount() {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
try {
ReactDOM.unmountComponentAtNode(this._container);
} catch (e) {}
}
_update = () => {
ReactDOM.render(React.Children.only(this.props.children), this._container);
}
render() {
return <div ref="mountPoint" />;
}
}
export default class RelayPlayground extends React.Component {
static defaultProps = {
autoExecute: false,
};
static propTypes = {
autoExecute: PropTypes.bool.isRequired,
initialAppSource: PropTypes.string,
initialSchemaSource: PropTypes.string,
onAppSourceChange: PropTypes.func,
onSchemaSourceChange: PropTypes.func,
};
state = {
appElement: null,
appSource: this.props.initialAppSource,
busy: false,
editTarget: 'app',
error: null,
schemaSource: this.props.initialSchemaSource,
shouldExecuteCode: this.props.autoExecute,
};
componentDidMount() {
// Hijack console.warn to collect GraphQL validation warnings (we hope)
this._originalConsoleWarn = console.warn;
let collectedWarnings = [];
console.warn = (...args) => {
collectedWarnings.push([Date.now(), args]);
this._originalConsoleWarn.apply(console, args);
};
// Hijack window.onerror to catch any stray fatals
this._originalWindowOnerror = window.onerror;
window.onerror = (message, url, lineNumber, something, error) => {
// GraphQL validation warnings are followed closely by a thrown exception.
// Console warnings that appear too far before this exception are probably
// not related to GraphQL. Throw those out.
if (/GraphQL validation error/.test(message)) {
const recentWarnings = collectedWarnings
.filter(([createdAt, args]) => Date.now() - createdAt <= 500)
.reduce((memo, [createdAt, args]) => memo.concat(args), []);
this.setState({
error: {stack: recentWarnings.join('\n')},
errorType: ERROR_TYPES.graphql,
});
} else {
this.setState({error, errorType: ERROR_TYPES.runtime});
}
collectedWarnings = [];
return false;
};
if (this.state.shouldExecuteCode) {
this._updateSchema(this.state.schemaSource, this.state.appSource);
}
}
componentDidUpdate(prevProps, prevState) {
const recentlyEnabledCodeExecution =
!prevState.shouldExecuteCode && this.state.shouldExecuteCode;
const appChanged = this.state.appSource !== prevState.appSource;
const schemaChanged = this.state.schemaSource !== prevState.schemaSource;
if (
this.state.shouldExecuteCode &&
(recentlyEnabledCodeExecution || appChanged || schemaChanged)
) {
this.setState({busy: true});
this._handleSourceCodeChange(
this.state.appSource,
recentlyEnabledCodeExecution || schemaChanged
? this.state.schemaSource
: null,
);
}
}
componentWillUnmount() {
clearTimeout(this._errorReporterTimeout);
clearTimeout(this._warningScrubberTimeout);
this._handleSourceCodeChange.cancel();
console.warn = this._originalConsoleWarn;
window.onerror = this._originalWindowOnerror;
}
_handleExecuteClick = () => {
this.setState({shouldExecuteCode: true});
}
_handleSourceCodeChange = debounce((appSource, schemaSource) => {
if (schemaSource != null) {
this._updateSchema(schemaSource, appSource);
} else {
this._updateApp(appSource);
}
}, 300, {trailing: true})
_updateApp(appSource) {
clearTimeout(this._errorReporterTimeout);
// We're running in a browser. Create a require() shim to catch any imports.
const require = (path) => {
switch (path) {
// The errorCatcherPlugin injects a series of import statements into the
// program body. Return locally bound variables in these three cases:
case '//error-catcher.js':
return (React, filename, displayName, reporter) => {
// When it fatals, render an empty <span /> in place of the app.
return errorCatcher(React, filename, <span />, reporter);
};
case 'react':
return React;
case 'reporterProxy':
return (error, instance, filename, displayName) => {
this._errorReporterTimeout = defer(
this.setState.bind(this),
{error, errorType: ERROR_TYPES.runtime}
);
};
default: throw new Error(`Cannot find module "${path}"`);
}
};
try {
const {code} = transform(appSource, {
filename: 'RelayPlayground',
plugins : [
babelRelayPlaygroundPlugin,
this._babelRelayPlugin,
errorCatcherPlugin('reporterProxy'),
],
retainLines: true,
sourceMaps: 'inline',
stage: 0,
});
const result = eval(code);
if (
React.isValidElement(result) &&
result.type.name === 'RelayRootContainer'
) {
this.setState({
appElement: React.cloneElement(result, {forceFetch: true}),
});
} else {
this.setState({
appElement: (
<div>
<h2>
Render a Relay.RootContainer into <code>mountNode</code> to get
started.
</h2>
<p>
Example:
</p>
<pre>{RENDER_STEP_EXAMPLE_CODE}</pre>
</div>
),
});
}
this.setState({error: null});
} catch (error) {
this.setState({error, errorType: ERROR_TYPES.syntax});
}
this.setState({busy: false});
}
_updateCode = (newSource) => {
const sourceStorageKey = `${this.state.editTarget}Source`;
this.setState({[sourceStorageKey]: newSource});
if (this.state.editTarget === 'app' && this.props.onAppSourceChange) {
this.props.onAppSourceChange(newSource);
}
if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) {
this.props.onSchemaSourceChange(newSource);
}
}
_updateEditTarget(editTarget) {
this.setState({editTarget});
}
_updateSchema(schemaSource, appSource) {
try {
var Schema = evalSchema(schemaSource);
} catch (error) {
this.setState({error, errorType: ERROR_TYPES.schema});
return;
}
graphql(Schema, introspectionQuery).then((result) => {
if (
this.state.schemaSource !== schemaSource ||
this.state.appSource !== appSource
) {
// This version of the code is stale. Bail out.
return;
}
this._babelRelayPlugin = getBabelRelayPlugin(result.data);
Relay.injectNetworkLayer(
new RelayLocalSchema.NetworkLayer({
schema: Schema,
onError: (errors, request) => {
this.setState({
error: errorFromGraphQLResultAndQuery(errors, request),
errorType: ERROR_TYPES.query,
});
},
})
);
this._updateApp(appSource);
});
}
renderApp() {
if (!this.state.shouldExecuteCode) {
return (
<div className="rpExecutionGuard">
<div className="rpExecutionGuardMessage">
<h2>For your security, this playground did not auto-execute</h2>
<p>
Clicking <strong>execute</strong> will run the code in the two
tabs to the left.
</p>
<button onClick={this._handleExecuteClick}>Execute</button>
</div>
</div>
);
} else if (this.state.error) {
return (
<div className="rpError">
<h1>{this.state.errorType} Error</h1>
<pre className="rpErrorStack">{this.state.error.stack}</pre>
</div>
);
} else if (this.state.appElement) {
return <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer>;
}
return null;
}
render() {
const sourceCode = this.state.editTarget === 'schema'
? this.state.schemaSource
: this.state.appSource;
return (
<div className="rpShell">
<section className="rpCodeEditor">
<nav className="rpCodeEditorNav">
<button
className={this.state.editTarget === 'app' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'app')}>
Code
</button>
<button
className={this.state.editTarget === 'schema' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'schema')}>
Schema
</button>
</nav>
{/* What is going on with the choice of key in Codemirror?
* https://github.com/JedWatson/react-codemirror/issues/12
*/}
<Codemirror
key={`${this.state.editTarget}-${this.state.shouldExecuteCode}`}
onChange={this._updateCode}
options={{
...CODE_EDITOR_OPTIONS,
readOnly: !this.state.shouldExecuteCode,
}}
value={sourceCode}
/>
</section>
<section className="rpResult">
<h1 className="rpResultHeader">
Relay Playground
<span className={
'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '')
} />
</h1>
<div className="rpResultOutput">
{this.renderApp()}
</div>
</section>
</div>
);
}
}