frame.js 9.36 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
11
12
13
14
15
16
17
/* @flow */
import { enableTabClick } from '../utils/dom/enableTabClick';
import { createCode } from './code';
import { isInternalFile } from '../utils/isInternalFile';
import type { StackFrame } from '../utils/stack-frame';
import type { FrameSetting, OmitsObject } from './frames';
import { applyStyles } from '../utils/dom/css';
import {
18
19
  omittedFramesExpandedStyle,
  omittedFramesCollapsedStyle,
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
  functionNameStyle,
  depStyle,
  linkStyle,
  anchorStyle,
  hiddenStyle,
} from '../styles';

function getGroupToggle(
  document: Document,
  omitsCount: number,
  omitBundle: number
) {
  const omittedFrames = document.createElement('div');
  enableTabClick(omittedFrames);
  const text1 = document.createTextNode(
    '\u25B6 ' + omitsCount + ' stack frames were collapsed.'
  );
  omittedFrames.appendChild(text1);
  omittedFrames.addEventListener('click', function() {
    const hide = text1.textContent.match(/▲/);
    const list = document.getElementsByName('bundle-' + omitBundle);
    for (let index = 0; index < list.length; ++index) {
      const n = list[index];
      if (hide) {
        n.style.display = 'none';
      } else {
        n.style.display = '';
      }
    }
    if (hide) {
      text1.textContent = text1.textContent.replace(/▲/, '');
      text1.textContent = text1.textContent.replace(/expanded/, 'collapsed');
52
      applyStyles(omittedFrames, omittedFramesCollapsedStyle);
53
54
55
    } else {
      text1.textContent = text1.textContent.replace(/▶/, '');
      text1.textContent = text1.textContent.replace(/collapsed/, 'expanded');
56
      applyStyles(omittedFrames, omittedFramesExpandedStyle);
57
58
    }
  });
59
  applyStyles(omittedFrames, omittedFramesCollapsedStyle);
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
  return omittedFrames;
}

function insertBeforeBundle(
  document: Document,
  parent: Node,
  omitsCount: number,
  omitBundle: number,
  actionElement
) {
  const children = document.getElementsByName('bundle-' + omitBundle);
  if (children.length < 1) {
    return;
  }
  let first: ?Node = children[0];
  while (first != null && first.parentNode !== parent) {
    first = first.parentNode;
  }
  const div = document.createElement('div');
  enableTabClick(div);
  div.setAttribute('name', 'bundle-' + omitBundle);
  const text = document.createTextNode(
    '\u25BC ' + omitsCount + ' stack frames were expanded.'
  );
  div.appendChild(text);
  div.addEventListener('click', function() {
    return actionElement.click();
  });
88
  applyStyles(div, omittedFramesExpandedStyle);
89
90
91
92
93
  div.style.display = 'none';

  parent.insertBefore(div, first);
}

94
95
96
97
98
99
100
function frameDiv(
  document: Document,
  functionName,
  url,
  internalUrl,
  onSourceClick: ?Function
) {
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
  const frame = document.createElement('div');
  const frameFunctionName = document.createElement('div');

  let cleanedFunctionName;
  if (!functionName || functionName === 'Object.<anonymous>') {
    cleanedFunctionName = '(anonymous function)';
  } else {
    cleanedFunctionName = functionName;
  }

  const cleanedUrl = url.replace('webpack://', '.');

  if (internalUrl) {
    applyStyles(
      frameFunctionName,
      Object.assign({}, functionNameStyle, depStyle)
    );
  } else {
    applyStyles(frameFunctionName, functionNameStyle);
  }

  frameFunctionName.appendChild(document.createTextNode(cleanedFunctionName));
  frame.appendChild(frameFunctionName);

  const frameLink = document.createElement('div');
  applyStyles(frameLink, linkStyle);
  const frameAnchor = document.createElement('a');
  applyStyles(frameAnchor, anchorStyle);
  frameAnchor.appendChild(document.createTextNode(cleanedUrl));
  frameLink.appendChild(frameAnchor);
  frame.appendChild(frameLink);

133
134
  if (typeof onSourceClick === 'function') {
    let handler = onSourceClick;
135
    enableTabClick(frameAnchor);
136
137
138
139
140
141
    frameAnchor.style.cursor = 'pointer';
    frameAnchor.addEventListener('click', function() {
      handler();
    });
  }

142
143
144
  return frame;
}

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
function isBultinErrorName(errorName: ?string) {
  switch (errorName) {
    case 'EvalError':
    case 'InternalError':
    case 'RangeError':
    case 'ReferenceError':
    case 'SyntaxError':
    case 'TypeError':
    case 'URIError':
      return true;
    default:
      return false;
  }
}

function getPrettyURL(
  sourceFileName: ?string,
  sourceLineNumber: ?number,
  sourceColumnNumber: ?number,
  fileName: ?string,
  lineNumber: ?number,
  columnNumber: ?number,
  compiled: boolean
): string {
  let prettyURL;
  if (!compiled && sourceFileName && typeof sourceLineNumber === 'number') {
    // Remove everything up to the first /src/ or /node_modules/
    const trimMatch = /^[/|\\].*?[/|\\]((src|node_modules)[/|\\].*)/.exec(
      sourceFileName
    );
    if (trimMatch && trimMatch[1]) {
      prettyURL = trimMatch[1];
    } else {
      prettyURL = sourceFileName;
    }
    prettyURL += ':' + sourceLineNumber;
    // Note: we intentionally skip 0's because they're produced by cheap Webpack maps
    if (sourceColumnNumber) {
      prettyURL += ':' + sourceColumnNumber;
    }
  } else if (fileName && typeof lineNumber === 'number') {
    prettyURL = fileName + ':' + lineNumber;
    // Note: we intentionally skip 0's because they're produced by cheap Webpack maps
    if (columnNumber) {
      prettyURL += ':' + columnNumber;
    }
  } else {
    prettyURL = 'unknown';
  }
  return prettyURL;
}

197
198
199
200
201
202
203
204
205
function createFrame(
  document: Document,
  frameSetting: FrameSetting,
  frame: StackFrame,
  contextSize: number,
  critical: boolean,
  omits: OmitsObject,
  omitBundle: number,
  parentContainer: HTMLDivElement,
206
207
  lastElement: boolean,
  errorName: ?string
208
209
) {
  const { compiled } = frameSetting;
210
  let { functionName, _originalFileName: sourceFileName } = frame;
211
212
213
214
215
216
217
218
219
220
  const {
    fileName,
    lineNumber,
    columnNumber,
    _scriptCode: scriptLines,
    _originalLineNumber: sourceLineNumber,
    _originalColumnNumber: sourceColumnNumber,
    _originalScriptCode: sourceLines,
  } = frame;

221
222
223
224
  // TODO: find a better place for this.
  // Chrome has a bug with inferring function.name:
  // https://github.com/facebookincubator/create-react-app/issues/2097
  // Let's ignore a meaningless name we get for top-level modules.
225
226
227
228
  if (
    functionName === 'Object.friendlySyntaxErrorLabel' ||
    functionName === 'Object.exports.__esModule'
  ) {
229
230
231
    functionName = '(anonymous function)';
  }

232
233
234
235
236
237
238
239
240
  const prettyURL = getPrettyURL(
    sourceFileName,
    sourceLineNumber,
    sourceColumnNumber,
    fileName,
    lineNumber,
    columnNumber,
    compiled
  );
241

242
243
244
  let needsHidden = false;
  const isInternalUrl = isInternalFile(sourceFileName, fileName);
  const isThrownIntentionally = !isBultinErrorName(errorName);
245
246
  const shouldCollapse =
    isInternalUrl && (isThrownIntentionally || omits.hasReachedAppCode);
247
248
249

  if (!isInternalUrl) {
    omits.hasReachedAppCode = true;
250
251
  }

252
  if (shouldCollapse) {
253
254
255
    ++omits.value;
    needsHidden = true;
  }
256

257
  let collapseElement = null;
258
  if (!shouldCollapse || lastElement) {
259
260
261
262
263
264
265
266
267
268
269
270
    if (omits.value > 0) {
      const capV = omits.value;
      const omittedFrames = getGroupToggle(document, capV, omitBundle);
      window.requestAnimationFrame(() => {
        insertBeforeBundle(
          document,
          parentContainer,
          capV,
          omitBundle,
          omittedFrames
        );
      });
271
      if (lastElement && shouldCollapse) {
272
273
274
275
276
277
278
279
280
        collapseElement = omittedFrames;
      } else {
        parentContainer.appendChild(omittedFrames);
      }
      ++omits.bundle;
    }
    omits.value = 0;
  }

281
282
  let onSourceClick = null;
  if (sourceFileName) {
283
    // e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1"
284
285
    const isInternalWebpackBootstrapCode =
      sourceFileName.trim().indexOf(' ') !== -1;
286
287
    if (!isInternalWebpackBootstrapCode) {
      onSourceClick = () => {
288
        // Keep this in sync with react-error-overlay/middleware.js
289
290
291
292
293
294
295
296
        fetch(
          '/__open-stack-frame-in-editor?fileName=' +
            window.encodeURIComponent(sourceFileName) +
            '&lineNumber=' +
            window.encodeURIComponent(sourceLineNumber || 1)
        ).then(() => {}, () => {});
      };
    }
297
298
299
300
301
302
303
304
305
  }

  const elem = frameDiv(
    document,
    functionName,
    prettyURL,
    shouldCollapse,
    onSourceClick
  );
306
307
308
309
310
311
  if (needsHidden) {
    applyStyles(elem, hiddenStyle);
    elem.setAttribute('name', 'bundle-' + omitBundle);
  }

  let hasSource = false;
312
  if (!shouldCollapse) {
313
    if (
314
315
316
317
      compiled &&
      scriptLines &&
      scriptLines.length !== 0 &&
      lineNumber != null
318
319
320
321
322
323
324
325
    ) {
      elem.appendChild(
        createCode(
          document,
          scriptLines,
          lineNumber,
          columnNumber,
          contextSize,
326
          critical,
327
          onSourceClick
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        )
      );
      hasSource = true;
    } else if (
      !compiled &&
      sourceLines &&
      sourceLines.length !== 0 &&
      sourceLineNumber != null
    ) {
      elem.appendChild(
        createCode(
          document,
          sourceLines,
          sourceLineNumber,
          sourceColumnNumber,
          contextSize,
344
          critical,
345
          onSourceClick
346
347
348
349
350
351
352
353
354
355
        )
      );
      hasSource = true;
    }
  }

  return { elem: elem, hasSource: hasSource, collapseElement: collapseElement };
}

export { createFrame };