index.js 4.89 KB
Newer Older
Dan Abramov's avatar
Dan Abramov committed
1
2
3
4
5
6
7
8
9
/**
 * Copyright (c) 2015-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.
 */

10
/* @flow */
11
import React from 'react';
12
import type { Element } from 'react';
13
14
15
16
17
18
import ReactDOM from 'react-dom';
import CompileErrorContainer from './containers/CompileErrorContainer';
import RuntimeErrorContainer from './containers/RuntimeErrorContainer';
import { listenToRuntimeErrors } from './listenToRuntimeErrors';
import { iframeStyle, overlayStyle } from './styles';
import { applyStyles } from './utils/dom/css';
19

20
21
22
23
24
import type { ErrorRecord } from './listenToRuntimeErrors';

type RuntimeReportingOptions = {|
  onError: () => void,
  launchEditorEndpoint: string,
25
  filename?: string,
26
27
28
29
30
|};

let iframe: null | HTMLIFrameElement = null;
let isLoadingIframe: boolean = false;

31
let renderedElement: null | Element<any> = null;
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
let currentBuildError: null | string = null;
let currentRuntimeErrorRecords: Array<ErrorRecord> = [];
let currentRuntimeErrorOptions: null | RuntimeReportingOptions = null;
let stopListeningToRuntimeErrors: null | (() => void) = null;

export function reportBuildError(error: string) {
  currentBuildError = error;
  update();
}

export function dismissBuildError() {
  currentBuildError = null;
  update();
}

export function startReportingRuntimeErrors(options: RuntimeReportingOptions) {
  if (stopListeningToRuntimeErrors !== null) {
    throw new Error('Already listening');
  }
  currentRuntimeErrorOptions = options;
  listenToRuntimeErrors(errorRecord => {
    try {
      if (typeof options.onError === 'function') {
        options.onError.call(null);
      }
    } finally {
      handleRuntimeError(errorRecord);
    }
60
  }, options.filename);
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

function handleRuntimeError(errorRecord) {
  if (
    currentRuntimeErrorRecords.some(({ error }) => error === errorRecord.error)
  ) {
    // Deduplicate identical errors.
    // This fixes https://github.com/facebookincubator/create-react-app/issues/3011.
    return;
  }
  currentRuntimeErrorRecords = currentRuntimeErrorRecords.concat([errorRecord]);
  update();
}

function dismissRuntimeErrors() {
  currentRuntimeErrorRecords = [];
  update();
}

export function stopReportingRuntimeErrors() {
  if (stopListeningToRuntimeErrors === null) {
    throw new Error('Not currently listening');
  }
  currentRuntimeErrorOptions = null;
  try {
    stopListeningToRuntimeErrors();
  } finally {
    stopListeningToRuntimeErrors = null;
  }
}

function update() {
  renderedElement = render();
  // Loading iframe can be either sync or async depending on the browser.
  if (isLoadingIframe) {
    // Iframe is loading.
    // First render will happen soon--don't need to do anything.
    return;
  }
  if (iframe) {
    // Iframe has already loaded.
    // Just update it.
    updateIframeContent();
    return;
  }
  // We need to schedule the first render.
  isLoadingIframe = true;
  const loadingIframe = window.document.createElement('iframe');
  applyStyles(loadingIframe, iframeStyle);
  loadingIframe.onload = function() {
    const iframeDocument = loadingIframe.contentDocument;
    if (iframeDocument != null && iframeDocument.body != null) {
      iframeDocument.body.style.margin = '0';
      // Keep popup within body boundaries for iOS Safari
      iframeDocument.body.style['max-width'] = '100vw';
      const iframeRoot = iframeDocument.createElement('div');
      applyStyles(iframeRoot, overlayStyle);
      iframeDocument.body.appendChild(iframeRoot);

      // Ready! Now we can update the UI.
      iframe = loadingIframe;
      isLoadingIframe = false;
      updateIframeContent();
    }
  };
  const appDocument = window.document;
  appDocument.body.appendChild(loadingIframe);
}

function render() {
  if (currentBuildError) {
    return <CompileErrorContainer error={currentBuildError} />;
  }
  if (currentRuntimeErrorRecords.length > 0) {
    if (!currentRuntimeErrorOptions) {
      throw new Error('Expected options to be injected.');
    }
    return (
      <RuntimeErrorContainer
        errorRecords={currentRuntimeErrorRecords}
        close={dismissRuntimeErrors}
        launchEditorEndpoint={currentRuntimeErrorOptions.launchEditorEndpoint}
      />
    );
  }
  return null;
}

function updateIframeContent() {
  if (iframe === null) {
    throw new Error('Iframe has not been created yet.');
  }
  const iframeBody = iframe.contentDocument.body;
  if (!iframeBody) {
    throw new Error('Expected iframe to have a body.');
  }
  const iframeRoot = iframeBody.firstChild;
  if (renderedElement === null) {
    // Destroy iframe and force it to be recreated on next error
    window.document.body.removeChild(iframe);
    ReactDOM.unmountComponentAtNode(iframeRoot);
    iframe = null;
    return;
  }
  // Update the overlay
  ReactDOM.render(renderedElement, iframeRoot);
}