summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/components/Frame.js
blob: 4efc7d3bd66a75c4f07b7c5de763e5ac7edefcb3 (plain)
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {
  Component,
} = require("resource://devtools/client/shared/vendor/react.js");
const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
const {
  getUnicodeUrl,
  getUnicodeUrlPath,
  getUnicodeHostname,
} = require("resource://devtools/client/shared/unicode-url.js");
const {
  getSourceNames,
  parseURL,
  getSourceMappedFile,
} = require("resource://devtools/client/shared/source-utils.js");
const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
const {
  MESSAGE_SOURCE,
} = require("resource://devtools/client/webconsole/constants.js");

const l10n = new LocalizationHelper(
  "devtools/client/locales/components.properties"
);
const webl10n = new LocalizationHelper(
  "devtools/client/locales/webconsole.properties"
);

function savedFrameToLocation(frame) {
  const { source: url, line, column, sourceId } = frame;
  return {
    url,
    line,
    column,
    // The sourceId will be a string if it's a source actor ID, otherwise
    // it is either a Spidermonkey-internal ID from a SavedFrame or missing,
    // and in either case we can't use the ID for anything useful.
    id: typeof sourceId === "string" ? sourceId : null,
  };
}

/**
 * Get the tooltip message.
 * @param {string|undefined} messageSource
 * @param {string} url
 * @returns {string}
 */
function getTooltipMessage(messageSource, url) {
  if (messageSource && messageSource === MESSAGE_SOURCE.CSS) {
    return l10n.getFormatStr("frame.viewsourceinstyleeditor", url);
  }
  return l10n.getFormatStr("frame.viewsourceindebugger", url);
}

class Frame extends Component {
  static get propTypes() {
    return {
      // Optional className that will be put into the element.
      className: PropTypes.string,
      // SavedFrame, or an object containing all the required properties.
      frame: PropTypes.shape({
        functionDisplayName: PropTypes.string,
        // This could be a SavedFrame with a numeric sourceId, or it could
        // be a SavedFrame-like client-side object, in which case the
        // "sourceId" will be a source actor ID.
        sourceId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        source: PropTypes.string.isRequired,
        line: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        column: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
      }).isRequired,
      // Clicking on the frame link -- probably should link to the debugger.
      onClick: PropTypes.func,
      // Option to display a function name before the source link.
      showFunctionName: PropTypes.bool,
      // Option to display a function name even if it's anonymous.
      showAnonymousFunctionName: PropTypes.bool,
      // Option to display a host name after the source link.
      showHost: PropTypes.bool,
      // Option to display a host name if the filename is empty or just '/'
      showEmptyPathAsHost: PropTypes.bool,
      // Option to display a full source instead of just the filename.
      showFullSourceUrl: PropTypes.bool,
      // Service to enable the source map feature for console.
      sourceMapURLService: PropTypes.object,
      // The source of the message
      messageSource: PropTypes.string,
    };
  }

  static get defaultProps() {
    return {
      showFunctionName: false,
      showAnonymousFunctionName: false,
      showHost: false,
      showEmptyPathAsHost: false,
      showFullSourceUrl: false,
    };
  }

  constructor(props) {
    super(props);
    this.state = {
      originalLocation: null,
    };
    this._locationChanged = this._locationChanged.bind(this);
  }

  // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
  UNSAFE_componentWillMount() {
    if (this.props.sourceMapURLService) {
      const location = savedFrameToLocation(this.props.frame);
      // Many things that make use of this component either:
      // a) Pass in no sourceId because they have no way to know.
      // b) Pass in no sourceId because the actor wasn't created when the
      //    server sent its response.
      //
      // and due to that, we need to use subscribeByLocation in order to
      // handle both cases with an without an ID.
      this.unsubscribeSourceMapURLService =
        this.props.sourceMapURLService.subscribeByLocation(
          location,
          this._locationChanged
        );
    }
  }

  componentWillUnmount() {
    if (this.unsubscribeSourceMapURLService) {
      this.unsubscribeSourceMapURLService();
    }
  }

  _locationChanged(originalLocation) {
    this.setState({ originalLocation });
  }

  /**
   * Get current location's source, line, and column.
   * @returns {{source: string, line: number|null, column: number|null}}
   */
  #getCurrentLocationInfo = () => {
    const { frame } = this.props;
    const { originalLocation } = this.state;

    const generatedLocation = savedFrameToLocation(frame);
    const currentLocation = originalLocation || generatedLocation;

    const source = currentLocation.url || "";
    const line =
      currentLocation.line != void 0 ? Number(currentLocation.line) : null;
    const column =
      currentLocation.column != void 0 ? Number(currentLocation.column) : null;
    return {
      source,
      line,
      column,
    };
  };

  /**
   * Get unicode hostname of the source link.
   * @returns {string}
   */
  #getCurrentLocationUnicodeHostName = () => {
    const { source } = this.#getCurrentLocationInfo();

    const { host } = getSourceNames(source);
    return host ? getUnicodeHostname(host) : "";
  };

  /**
   * Check if the current location is linkable.
   * @returns {boolean}
   */
  #isCurrentLocationLinkable = () => {
    const { frame } = this.props;
    const { originalLocation } = this.state;

    const generatedLocation = savedFrameToLocation(frame);

    // Reparse the URL to determine if we should link this; `getSourceNames`
    // has already cached this indirectly. We don't want to attempt to
    // link to "self-hosted" and "(unknown)".
    // Source mapped sources might not necessary linkable, but they
    // are still valid in the debugger.
    // If we have a source ID then we can show the source in the debugger.
    return !!(
      originalLocation ||
      generatedLocation.id ||
      !!parseURL(generatedLocation.url)
    );
  };

  /**
   * Get the props of the top element.
   */
  #getTopElementProps = () => {
    const { className } = this.props;

    const { source, line, column } = this.#getCurrentLocationInfo();
    const { long } = getSourceNames(source);
    const props = {
      "data-url": long,
      className: "frame-link" + (className ? ` ${className}` : ""),
    };

    // If we have a line number > 0.
    if (line) {
      // Add `data-line` attribute for testing
      props["data-line"] = line;

      // Intentionally exclude 0
      if (column) {
        // Add `data-column` attribute for testing
        props["data-column"] = column;
      }
    }
    return props;
  };

  /**
   * Get the props of the source element.
   */
  #getSourceElementsProps = () => {
    const { frame, onClick, messageSource } = this.props;

    const generatedLocation = savedFrameToLocation(frame);
    const { source, line, column } = this.#getCurrentLocationInfo();
    const { long } = getSourceNames(source);
    let url = getUnicodeUrl(long);

    // Exclude all falsy values, including `0`, as line numbers start with 1.
    if (line) {
      url += `:${line}`;
      // Intentionally exclude 0
      if (column) {
        url += `:${column}`;
      }
    }

    const isLinkable = this.#isCurrentLocationLinkable();

    // Inner el is useful for achieving ellipsis on the left and correct LTR/RTL
    // ordering. See CSS styles for frame-link-source-[inner] and bug 1290056.
    const tooltipMessage = getTooltipMessage(messageSource, url);

    const sourceElConfig = {
      key: "source",
      className: "frame-link-source",
      title: isLinkable ? tooltipMessage : url,
    };

    if (isLinkable) {
      return {
        ...sourceElConfig,
        onClick: e => {
          e.preventDefault();
          e.stopPropagation();

          onClick(generatedLocation);
        },
        href: source,
        draggable: false,
      };
    }

    return sourceElConfig;
  };

  /**
   * Render the source elements.
   * @returns {React.ReactNode}
   */
  #renderSourceElements = () => {
    const { line, column } = this.#getCurrentLocationInfo();

    const sourceElements = [this.#renderDisplaySource()];

    if (line) {
      let lineInfo = `:${line}`;

      // Intentionally exclude 0
      if (column) {
        lineInfo += `:${column}`;
      }

      sourceElements.push(
        dom.span(
          {
            key: "line",
            className: "frame-link-line",
          },
          lineInfo
        )
      );
    }

    if (this.#isCurrentLocationLinkable()) {
      return dom.a(this.#getSourceElementsProps(), sourceElements);
    }
    // If source is not a URL (self-hosted, eval, etc.), don't make
    // it an anchor link, as we can't link to it.
    return dom.span(this.#getSourceElementsProps(), sourceElements);
  };

  /**
   * Render the display source.
   * @returns {React.ReactNode}
   */
  #renderDisplaySource = () => {
    const { showEmptyPathAsHost, showFullSourceUrl } = this.props;
    const { originalLocation } = this.state;

    const { source } = this.#getCurrentLocationInfo();
    const { short, long, host } = getSourceNames(source);
    const unicodeShort = getUnicodeUrlPath(short);
    const unicodeLong = getUnicodeUrl(long);
    let displaySource = showFullSourceUrl ? unicodeLong : unicodeShort;
    if (originalLocation) {
      displaySource = getSourceMappedFile(displaySource);

      // In case of pretty-printed HTML file, we would only get the formatted suffix; replace
      // it with the full URL instead
      if (showEmptyPathAsHost && displaySource == ":formatted") {
        displaySource = host + displaySource;
      }
    } else if (
      showEmptyPathAsHost &&
      (displaySource === "" || displaySource === "/")
    ) {
      displaySource = host;
    }

    return dom.span(
      {
        key: "filename",
        className: "frame-link-filename",
      },
      displaySource
    );
  };

  /**
   * Render the function display name.
   * @returns {React.ReactNode}
   */
  #renderFunctionDisplayName = () => {
    const { frame, showFunctionName, showAnonymousFunctionName } = this.props;
    if (!showFunctionName) {
      return null;
    }
    const functionDisplayName = frame.functionDisplayName;
    if (functionDisplayName || showAnonymousFunctionName) {
      return [
        dom.span(
          {
            key: "function-display-name",
            className: "frame-link-function-display-name",
          },
          functionDisplayName || webl10n.getStr("stacktrace.anonymousFunction")
        ),
        " ",
      ];
    }
    return null;
  };

  render() {
    const { showHost } = this.props;

    const elements = [
      this.#renderFunctionDisplayName(),
      this.#renderSourceElements(),
    ];

    const unicodeHost = showHost
      ? this.#getCurrentLocationUnicodeHostName()
      : null;
    if (unicodeHost) {
      elements.push(" ");
      elements.push(
        dom.span(
          {
            key: "host",
            className: "frame-link-host",
          },
          unicodeHost
        )
      );
    }

    return dom.span(this.#getTopElementProps(), ...elements);
  }
}

module.exports = Frame;