summaryrefslogtreecommitdiffstats
path: root/devtools/client/netmonitor/src/components
diff options
context:
space:
mode:
Diffstat (limited to 'devtools/client/netmonitor/src/components')
-rw-r--r--devtools/client/netmonitor/src/components/App.js119
-rw-r--r--devtools/client/netmonitor/src/components/CustomRequestPanel.js371
-rw-r--r--devtools/client/netmonitor/src/components/DropHarHandler.js141
-rw-r--r--devtools/client/netmonitor/src/components/MonitorPanel.js271
-rw-r--r--devtools/client/netmonitor/src/components/NetworkActionBar.js136
-rw-r--r--devtools/client/netmonitor/src/components/SecurityState.js78
-rw-r--r--devtools/client/netmonitor/src/components/SourceEditor.js137
-rw-r--r--devtools/client/netmonitor/src/components/StatisticsPanel.js413
-rw-r--r--devtools/client/netmonitor/src/components/StatusBar.js175
-rw-r--r--devtools/client/netmonitor/src/components/StatusCode.js129
-rw-r--r--devtools/client/netmonitor/src/components/TabboxPanel.js242
-rw-r--r--devtools/client/netmonitor/src/components/Toolbar.js688
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnData.js60
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnEventName.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnFinBit.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnOpCode.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnRetry.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnSize.js43
-rw-r--r--devtools/client/netmonitor/src/components/messages/ColumnTime.js56
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js122
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListContent.js398
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js62
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListHeader.js121
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js61
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessageListItem.js127
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessagePayload.js403
-rw-r--r--devtools/client/netmonitor/src/components/messages/MessagesView.js173
-rw-r--r--devtools/client/netmonitor/src/components/messages/RawData.js34
-rw-r--r--devtools/client/netmonitor/src/components/messages/StatusBar.js130
-rw-r--r--devtools/client/netmonitor/src/components/messages/Toolbar.js152
-rw-r--r--devtools/client/netmonitor/src/components/messages/cbor.js270
-rw-r--r--devtools/client/netmonitor/src/components/messages/moz.build32
-rw-r--r--devtools/client/netmonitor/src/components/messages/msgpack.js365
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/moz.build11
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js82
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js120
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js33
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js13
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build12
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js48
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js84
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js292
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js56
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build7
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js25
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js204
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js40
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js230
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js274
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build8
-rw-r--r--devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js73
-rw-r--r--devtools/client/netmonitor/src/components/moz.build28
-rw-r--r--devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js511
-rw-r--r--devtools/client/netmonitor/src/components/new-request/InputMap.js211
-rw-r--r--devtools/client/netmonitor/src/components/new-request/moz.build8
-rw-r--r--devtools/client/netmonitor/src/components/previews/FontPreview.js135
-rw-r--r--devtools/client/netmonitor/src/components/previews/HtmlPreview.js75
-rw-r--r--devtools/client/netmonitor/src/components/previews/ImagePreview.js91
-rw-r--r--devtools/client/netmonitor/src/components/previews/SourcePreview.js178
-rw-r--r--devtools/client/netmonitor/src/components/previews/UrlPreview.js290
-rw-r--r--devtools/client/netmonitor/src/components/previews/moz.build11
-rw-r--r--devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js350
-rw-r--r--devtools/client/netmonitor/src/components/request-blocking/moz.build7
-rw-r--r--devtools/client/netmonitor/src/components/request-details/CachePanel.js144
-rw-r--r--devtools/client/netmonitor/src/components/request-details/CookiesPanel.js225
-rw-r--r--devtools/client/netmonitor/src/components/request-details/HeadersPanel.js850
-rw-r--r--devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js106
-rw-r--r--devtools/client/netmonitor/src/components/request-details/PropertiesView.js247
-rw-r--r--devtools/client/netmonitor/src/components/request-details/RequestPanel.js301
-rw-r--r--devtools/client/netmonitor/src/components/request-details/ResponsePanel.js496
-rw-r--r--devtools/client/netmonitor/src/components/request-details/SecurityPanel.js283
-rw-r--r--devtools/client/netmonitor/src/components/request-details/StackTracePanel.js81
-rw-r--r--devtools/client/netmonitor/src/components/request-details/TimingsPanel.js229
-rw-r--r--devtools/client/netmonitor/src/components/request-details/moz.build16
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestList.js50
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js38
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js61
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js66
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js91
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js65
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js33
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js36
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js43
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js43
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js59
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js38
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js61
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js39
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js91
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js99
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js45
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js89
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js209
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListContent.js524
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js107
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListHeader.js731
-rw-r--r--devtools/client/netmonitor/src/components/request-list/RequestListItem.js412
-rw-r--r--devtools/client/netmonitor/src/components/request-list/moz.build29
-rw-r--r--devtools/client/netmonitor/src/components/search/SearchPanel.js264
-rw-r--r--devtools/client/netmonitor/src/components/search/StatusBar.js97
-rw-r--r--devtools/client/netmonitor/src/components/search/Toolbar.js160
-rw-r--r--devtools/client/netmonitor/src/components/search/moz.build10
-rw-r--r--devtools/client/netmonitor/src/components/search/search-provider.js91
110 files changed, 16033 insertions, 0 deletions
diff --git a/devtools/client/netmonitor/src/components/App.js b/devtools/client/netmonitor/src/components/App.js
new file mode 100644
index 0000000000..4f25f2d89d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/App.js
@@ -0,0 +1,119 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+
+// Components
+loader.lazyGetter(this, "AppErrorBoundary", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/AppErrorBoundary.js")
+ );
+});
+loader.lazyGetter(this, "MonitorPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/MonitorPanel.js")
+ );
+});
+loader.lazyGetter(this, "StatisticsPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatisticsPanel.js")
+ );
+});
+loader.lazyGetter(this, "DropHarHandler", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/DropHarHandler.js")
+ );
+});
+
+// Localized strings for (devtools/client/locales/en-US/startup.properties)
+loader.lazyGetter(this, "L10N", function () {
+ const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
+ return new LocalizationHelper("devtools/client/locales/startup.properties");
+});
+
+const { div } = dom;
+
+/**
+ * App component
+ * The top level component for representing main panel
+ */
+class App extends Component {
+ static get propTypes() {
+ return {
+ // List of actions passed to HAR importer.
+ actions: PropTypes.object.isRequired,
+ // The backend connector object.
+ connector: PropTypes.object.isRequired,
+ // Callback for opening links in the UI
+ openLink: PropTypes.func,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ // Service to enable the source map feature.
+ sourceMapURLService: PropTypes.object,
+ // True if the stats panel is opened.
+ statisticsOpen: PropTypes.bool.isRequired,
+ // Document which settings menu will be injected to
+ toolboxDoc: PropTypes.object.isRequired,
+ // Syncing blocked requests
+ addBlockedUrl: PropTypes.func,
+ };
+ }
+ // Rendering
+
+ render() {
+ const {
+ actions,
+ connector,
+ openLink,
+ openSplitConsole,
+ sourceMapURLService,
+ statisticsOpen,
+ toolboxDoc,
+ } = this.props;
+
+ return div(
+ { className: "network-monitor" },
+ AppErrorBoundary(
+ {
+ componentName: "Netmonitor",
+ panel: L10N.getStr("netmonitor.label"),
+ },
+ !statisticsOpen
+ ? DropHarHandler(
+ {
+ actions,
+ openSplitConsole,
+ },
+ MonitorPanel({
+ actions,
+ connector,
+ openSplitConsole,
+ sourceMapURLService,
+ openLink,
+ toolboxDoc,
+ })
+ )
+ : StatisticsPanel({
+ connector,
+ })
+ )
+ );
+ }
+}
+
+// Exports
+
+module.exports = connect(state => ({
+ statisticsOpen: state.ui.statisticsOpen,
+}))(App);
diff --git a/devtools/client/netmonitor/src/components/CustomRequestPanel.js b/devtools/client/netmonitor/src/components/CustomRequestPanel.js
new file mode 100644
index 0000000000..66f63b7d8d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/CustomRequestPanel.js
@@ -0,0 +1,371 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getUrlQuery,
+ parseQueryString,
+ writeHeaderText,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { button, div, input, label, textarea } = dom;
+
+const CUSTOM_CANCEL = L10N.getStr("netmonitor.custom.cancel");
+const CUSTOM_HEADERS = L10N.getStr("netmonitor.custom.headers");
+const CUSTOM_NEW_REQUEST = L10N.getStr("netmonitor.custom.newRequest");
+const CUSTOM_NEW_REQUEST_METHOD_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestMethodLabel"
+);
+const CUSTOM_NEW_REQUEST_URL_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestUrlLabel"
+);
+const CUSTOM_POSTDATA = L10N.getStr("netmonitor.custom.postData");
+const CUSTOM_QUERY = L10N.getStr("netmonitor.custom.query");
+const CUSTOM_SEND = L10N.getStr("netmonitor.custom.send");
+
+/*
+ * Custom request panel component
+ * A network request editor which simply provide edit and resend interface
+ * for network development.
+ */
+class CustomRequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ removeSelectedCustomRequest: PropTypes.func.isRequired,
+ request: PropTypes.object.isRequired,
+ sendCustomRequest: PropTypes.func.isRequired,
+ updateRequest: PropTypes.func.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ this.initialRequestMethod = request.method;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ /**
+ * Parse a text representation of a name[divider]value list with
+ * the given name regex and divider character.
+ *
+ * @param {string} text - Text of list
+ * @return {array} array of headers info {name, value}
+ */
+ parseRequestText(text, namereg, divider) {
+ const regex = new RegExp(`(${namereg})\\${divider}\\s*(\\S.*)`);
+ const pairs = [];
+
+ for (const line of text.split("\n")) {
+ const matches = regex.exec(line);
+ if (matches) {
+ const [, name, value] = matches;
+ pairs.push({ name, value });
+ }
+ }
+ return pairs;
+ }
+
+ /**
+ * Update Custom Request Fields
+ *
+ * @param {Object} evt click event
+ * @param {Object} request current request
+ * @param {updateRequest} updateRequest action
+ */
+ updateCustomRequestFields(evt, request, updateRequest) {
+ const val = evt.target.value;
+ let data;
+
+ switch (evt.target.id) {
+ case "custom-headers-value":
+ data = {
+ requestHeaders: {
+ customHeadersValue: val || "",
+ // Parse text representation of multiple HTTP headers
+ headers: this.parseRequestText(val, "\\S+?", ":"),
+ },
+ };
+ break;
+ case "custom-method-value":
+ // If val is empty when leaving the "method" field, set the method to
+ // its original value
+ data =
+ evt.type === "blur" && val === ""
+ ? { method: this.initialRequestMethod }
+ : { method: val.trim() };
+ break;
+ case "custom-postdata-value":
+ // Update "content-length" header value to reflect change
+ // in post data field.
+ const { requestHeaders } = request;
+ const newHeaders = requestHeaders.headers.map(header => {
+ if (header.name.toLowerCase() == "content-length") {
+ return {
+ name: header.name,
+ value: val.length,
+ };
+ }
+ return header;
+ });
+
+ data = {
+ requestPostData: {
+ postData: { text: val },
+ },
+ requestHeaders: {
+ headers: newHeaders,
+ },
+ };
+ break;
+ case "custom-query-value":
+ let customQueryValue = val || "";
+ // Parse readable text list of a query string
+ const queryArray = customQueryValue
+ ? this.parseRequestText(customQueryValue, ".+?", "=")
+ : [];
+ // Write out a list of query params into a query string
+ const queryString = queryArray
+ .map(({ name, value }) => name + "=" + value)
+ .join("&");
+ const url = queryString
+ ? [request.url.split("?")[0], queryString].join("?")
+ : request.url.split("?")[0];
+ // Remove temp customQueryValue while query string is parsable
+ if (
+ customQueryValue === "" ||
+ queryArray.length === customQueryValue.split("\n").length
+ ) {
+ customQueryValue = null;
+ }
+ data = {
+ customQueryValue,
+ url,
+ };
+ break;
+ case "custom-url-value":
+ data = {
+ customQueryValue: null,
+ url: val,
+ };
+ break;
+ default:
+ break;
+ }
+ if (data) {
+ // All updateRequest batch mode should be disabled to make UI editing in sync
+ updateRequest(request.id, data, false);
+ }
+ }
+
+ render() {
+ const {
+ removeSelectedCustomRequest,
+ request = {},
+ sendCustomRequest,
+ updateRequest,
+ } = this.props;
+ const { method, customQueryValue, requestHeaders, requestPostData, url } =
+ request;
+
+ let headers = "";
+ if (requestHeaders) {
+ headers = requestHeaders.customHeadersValue
+ ? requestHeaders.customHeadersValue
+ : writeHeaderText(requestHeaders.headers).trim();
+ }
+ const queryArray = url ? parseQueryString(getUrlQuery(url)) : [];
+ let params = customQueryValue;
+ if (!params) {
+ params = queryArray
+ ? queryArray.map(({ name, value }) => name + "=" + value).join("\n")
+ : "";
+ }
+ const postData = requestPostData?.postData.text
+ ? requestPostData.postData.text
+ : "";
+
+ return div(
+ { className: "custom-request-panel" },
+ div(
+ { className: "custom-request-label custom-header" },
+ CUSTOM_NEW_REQUEST
+ ),
+ div(
+ { className: "custom-request-panel-content" },
+ div(
+ { className: "tabpanel-summary-container custom-request" },
+ div(
+ { className: "custom-request-button-container" },
+ button(
+ {
+ className: "devtools-button",
+ id: "custom-request-close-button",
+ onClick: removeSelectedCustomRequest,
+ },
+ CUSTOM_CANCEL
+ ),
+ button(
+ {
+ className: "devtools-button",
+ id: "custom-request-send-button",
+ onClick: sendCustomRequest,
+ },
+ CUSTOM_SEND
+ )
+ )
+ ),
+ div(
+ {
+ className: "tabpanel-summary-container custom-method-and-url",
+ id: "custom-method-and-url",
+ },
+ label(
+ {
+ className: "custom-method-value-label custom-request-label",
+ htmlFor: "custom-method-value",
+ },
+ CUSTOM_NEW_REQUEST_METHOD_LABEL
+ ),
+ input({
+ className: "custom-method-value",
+ id: "custom-method-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ onBlur: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ value: method,
+ }),
+ label(
+ {
+ className: "custom-url-value-label custom-request-label",
+ htmlFor: "custom-url-value",
+ },
+ CUSTOM_NEW_REQUEST_URL_LABEL
+ ),
+ input({
+ className: "custom-url-value",
+ id: "custom-url-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ value: url || "http://",
+ })
+ ),
+ // Hide query field when there is no params
+ params
+ ? div(
+ {
+ className: "tabpanel-summary-container custom-section",
+ id: "custom-query",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-query-value",
+ },
+ CUSTOM_QUERY
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-query-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 4,
+ value: params,
+ wrap: "off",
+ })
+ )
+ : null,
+ div(
+ {
+ id: "custom-headers",
+ className: "tabpanel-summary-container custom-section",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-headers-value",
+ },
+ CUSTOM_HEADERS
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-headers-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 8,
+ value: headers,
+ wrap: "off",
+ })
+ ),
+ div(
+ {
+ id: "custom-postdata",
+ className: "tabpanel-summary-container custom-section",
+ },
+ label(
+ {
+ className: "custom-request-label",
+ htmlFor: "custom-postdata-value",
+ },
+ CUSTOM_POSTDATA
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "custom-postdata-value",
+ onChange: evt =>
+ this.updateCustomRequestFields(evt, request, updateRequest),
+ rows: 6,
+ value: postData,
+ wrap: "off",
+ })
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({ request: getSelectedRequest(state) }),
+ (dispatch, props) => ({
+ removeSelectedCustomRequest: () =>
+ dispatch(Actions.removeSelectedCustomRequest()),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+ })
+)(CustomRequestPanel);
diff --git a/devtools/client/netmonitor/src/components/DropHarHandler.js b/devtools/client/netmonitor/src/components/DropHarHandler.js
new file mode 100644
index 0000000000..6c51a6b80e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/DropHarHandler.js
@@ -0,0 +1,141 @@
+/* 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 {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+loader.lazyRequireGetter(
+ this,
+ "HarMenuUtils",
+ "resource://devtools/client/netmonitor/src/har/har-menu-utils.js",
+ true
+);
+
+const { div } = dom;
+
+const DROP_HAR_FILES = L10N.getStr("netmonitor.label.dropHarFiles");
+
+/**
+ * Helper component responsible for handling and importing
+ * dropped *.har files.
+ */
+class DropHarHandler extends Component {
+ static get propTypes() {
+ return {
+ // List of actions passed to HAR importer.
+ actions: PropTypes.object.isRequired,
+ // Child component.
+ children: PropTypes.element.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ // Drag and drop event handlers.
+ this.onDragEnter = this.onDragEnter.bind(this);
+ this.onDragOver = this.onDragOver.bind(this);
+ this.onDragLeave = this.onDragLeave.bind(this);
+ this.onDrop = this.onDrop.bind(this);
+ }
+
+ // Drag Events
+
+ onDragEnter(event) {
+ event.preventDefault();
+ if (event.dataTransfer.files.length === 0) {
+ return;
+ }
+
+ startDragging(findDOMNode(this));
+ }
+
+ onDragLeave(event) {
+ const node = findDOMNode(this);
+ if (!node.contains(event.relatedTarget)) {
+ stopDragging(node);
+ }
+ }
+
+ onDragOver(event) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ }
+
+ onDrop(event) {
+ event.preventDefault();
+ stopDragging(findDOMNode(this));
+
+ const { files } = event.dataTransfer;
+ if (!files) {
+ return;
+ }
+
+ const { actions, openSplitConsole } = this.props;
+
+ // Import only the first dragged file for now
+ // See also:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1438792
+ if (files.length) {
+ const file = files[0];
+ readFile(file).then(har => {
+ if (har) {
+ HarMenuUtils.appendPreview(har, actions, openSplitConsole);
+ }
+ });
+ }
+ }
+
+ // Rendering
+
+ render() {
+ return div(
+ {
+ onDragEnter: this.onDragEnter,
+ onDragOver: this.onDragOver,
+ onDragLeave: this.onDragLeave,
+ onDrop: this.onDrop,
+ },
+ this.props.children,
+ div({ className: "dropHarFiles" }, div({}, DROP_HAR_FILES))
+ );
+ }
+}
+
+// Helpers
+
+function readFile(file) {
+ return new Promise(resolve => {
+ const fileReader = new FileReader();
+ fileReader.onloadend = () => {
+ resolve(fileReader.result);
+ };
+ fileReader.readAsText(file);
+ });
+}
+
+function startDragging(node) {
+ node.setAttribute("dragging", "true");
+}
+
+function stopDragging(node) {
+ node.removeAttribute("dragging");
+}
+
+// Exports
+
+module.exports = DropHarHandler;
diff --git a/devtools/client/netmonitor/src/components/MonitorPanel.js b/devtools/client/netmonitor/src/components/MonitorPanel.js
new file mode 100644
index 0000000000..47b3758efe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/MonitorPanel.js
@@ -0,0 +1,271 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ updateFormDataSections,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getSelectedRequest,
+ isSelectedRequestVisible,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const SplitBox = createFactory(
+ require("resource://devtools/client/shared/components/splitter/SplitBox.js")
+);
+const RequestList = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestList.js")
+);
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/Toolbar.js")
+);
+
+loader.lazyGetter(this, "NetworkDetailsBar", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js")
+ );
+});
+
+loader.lazyGetter(this, "NetworkActionBar", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/NetworkActionBar.js")
+ );
+});
+
+// MediaQueryList object responsible for switching sidebar splitter
+// between landscape and portrait mode (depending on browser window size).
+const MediaQueryVert = window.matchMedia("(min-width: 700px)");
+
+// MediaQueryList object responsible for switching the toolbar
+// between single and 2-rows layout (depending on browser window size).
+const MediaQuerySingleRow = window.matchMedia("(min-width: 1020px)");
+
+/**
+ * Monitor panel component
+ * The main panel for displaying various network request information
+ */
+class MonitorPanel extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ isEmpty: PropTypes.bool.isRequired,
+ networkDetailsOpen: PropTypes.bool.isRequired,
+ openNetworkDetails: PropTypes.func.isRequired,
+ toolboxDoc: PropTypes.object.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ onNetworkDetailsResized: PropTypes.func.isRequired,
+ request: PropTypes.object,
+ selectedRequestVisible: PropTypes.bool.isRequired,
+ sourceMapURLService: PropTypes.object,
+ openLink: PropTypes.func,
+ updateRequest: PropTypes.func.isRequired,
+ networkActionOpen: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ isSingleRow: MediaQuerySingleRow.matches,
+ isVerticalSpliter: MediaQueryVert.matches,
+ };
+
+ this.onLayoutChange = this.onLayoutChange.bind(this);
+ this.onNetworkDetailsResized = this.onNetworkDetailsResized.bind(this);
+ }
+
+ componentDidMount() {
+ MediaQuerySingleRow.addListener(this.onLayoutChange);
+ MediaQueryVert.addListener(this.onLayoutChange);
+ this.persistDetailsPanelSize();
+ this.persistActionBarSize();
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ updateFormDataSections(nextProps);
+ }
+
+ componentDidUpdate() {
+ const { selectedRequestVisible, openNetworkDetails } = this.props;
+ if (!selectedRequestVisible) {
+ openNetworkDetails(false);
+ }
+ }
+
+ componentWillUnmount() {
+ MediaQuerySingleRow.removeListener(this.onLayoutChange);
+ MediaQueryVert.removeListener(this.onLayoutChange);
+ this.persistDetailsPanelSize();
+ this.persistActionBarSize();
+ }
+
+ persistDetailsPanelSize() {
+ const { clientWidth, clientHeight } = findDOMNode(this.refs.endPanel) || {};
+
+ if (this.state.isVerticalSpliter && clientWidth) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-network-details-width",
+ clientWidth
+ );
+ }
+ if (!this.state.isVerticalSpliter && clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-network-details-height",
+ clientHeight
+ );
+ }
+ }
+
+ persistActionBarSize() {
+ const { clientWidth, clientHeight } =
+ findDOMNode(this.refs.actionBar) || {};
+ if (clientWidth) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-search-width",
+ clientWidth
+ );
+ }
+ if (clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.panes-search-height",
+ clientHeight
+ );
+ }
+ }
+
+ onLayoutChange() {
+ this.setState({
+ isSingleRow: MediaQuerySingleRow.matches,
+ isVerticalSpliter: MediaQueryVert.matches,
+ });
+ }
+
+ onNetworkDetailsResized(width, height) {
+ // Cleaning width and height parameters, because SplitBox passes ALWAYS two values,
+ // while depending on orientation ONLY ONE dimension is managed by it at a time.
+ const { isVerticalSpliter } = this.state;
+ return this.props.onNetworkDetailsResized(
+ isVerticalSpliter ? width : null,
+ isVerticalSpliter ? null : height
+ );
+ }
+
+ renderActionBar() {
+ const { connector, isEmpty, networkActionOpen } = this.props;
+
+ const initialWidth = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-search-width"
+ );
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-search-height"
+ );
+
+ return SplitBox({
+ className: "devtools-responsive-container",
+ initialWidth,
+ initialHeight,
+ minSize: "250px",
+ maxSize: "80%",
+ splitterSize: networkActionOpen ? 1 : 0,
+ startPanel:
+ networkActionOpen &&
+ NetworkActionBar({
+ ref: "actionBar",
+ connector,
+ }),
+ endPanel: RequestList({ isEmpty, connector }),
+ endPanelControl: false,
+ vert: true,
+ });
+ }
+
+ render() {
+ const {
+ actions,
+ connector,
+ networkDetailsOpen,
+ openLink,
+ openSplitConsole,
+ sourceMapURLService,
+ toolboxDoc,
+ } = this.props;
+
+ const initialWidth = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-width"
+ );
+
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.panes-network-details-height"
+ );
+
+ return div(
+ { className: "monitor-panel" },
+ Toolbar({
+ actions,
+ connector,
+ openSplitConsole,
+ singleRow: this.state.isSingleRow,
+ toolboxDoc,
+ }),
+ SplitBox({
+ className: "devtools-responsive-container",
+ initialWidth,
+ initialHeight,
+ minSize: "50px",
+ maxSize: "80%",
+ splitterSize: networkDetailsOpen ? 1 : 0,
+ startPanel: this.renderActionBar(),
+ endPanel:
+ networkDetailsOpen &&
+ NetworkDetailsBar({
+ ref: "endPanel",
+ connector,
+ openLink,
+ sourceMapURLService,
+ }),
+ endPanelCollapsed: !networkDetailsOpen,
+ endPanelControl: true,
+ vert: this.state.isVerticalSpliter,
+ onControlledPanelResized: this.onNetworkDetailsResized,
+ })
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ isEmpty: !state.requests.requests.length,
+ networkDetailsOpen: state.ui.networkDetailsOpen,
+ networkActionOpen: state.ui.networkActionOpen,
+ request: getSelectedRequest(state),
+ selectedRequestVisible: isSelectedRequestVisible(state),
+ }),
+ dispatch => ({
+ openNetworkDetails: open => dispatch(Actions.openNetworkDetails(open)),
+ onNetworkDetailsResized: (width, height) =>
+ dispatch(Actions.resizeNetworkDetails(width, height)),
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+ })
+)(MonitorPanel);
diff --git a/devtools/client/netmonitor/src/components/NetworkActionBar.js b/devtools/client/netmonitor/src/components/NetworkActionBar.js
new file mode 100644
index 0000000000..92110e9ec5
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/NetworkActionBar.js
@@ -0,0 +1,136 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ div,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const Tabbar = createFactory(
+ require("resource://devtools/client/shared/components/tabs/TabBar.js")
+);
+const TabPanel = createFactory(
+ require("resource://devtools/client/shared/components/tabs/Tabs.js").TabPanel
+);
+
+loader.lazyGetter(this, "SearchPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/SearchPanel.js")
+ );
+});
+
+loader.lazyGetter(this, "RequestBlockingPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js")
+ );
+});
+
+loader.lazyGetter(this, "HTTPCustomRequestPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js")
+ );
+});
+
+class NetworkActionBar extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ selectActionBarTab: PropTypes.func.isRequired,
+ toggleNetworkActionBar: PropTypes.func.isRequired,
+ };
+ }
+
+ render() {
+ const {
+ connector,
+ selectedActionBarTabId,
+ selectActionBarTab,
+ toggleNetworkActionBar,
+ } = this.props;
+
+ // The request blocking and search panels are available behind a pref
+ const showBlockingPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ );
+ const showSearchPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.search"
+ );
+ const showNewCustomRequestPanel = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "network-action-bar" },
+ Tabbar(
+ {
+ activeTabId: selectedActionBarTabId,
+ onSelect: id => selectActionBarTab(id),
+ sidebarToggleButton: {
+ collapsed: false,
+ collapsePaneTitle: L10N.getStr("collapseActionPane"),
+ expandPaneTitle: "",
+ onClick: toggleNetworkActionBar,
+ alignRight: true,
+ canVerticalSplit: false,
+ },
+ },
+ showNewCustomRequestPanel &&
+ TabPanel(
+ {
+ id: PANELS.HTTP_CUSTOM_REQUEST,
+ title: L10N.getStr("netmonitor.actionbar.HTTPCustomRequest"),
+ className: "network-action-bar-HTTP-custom-request",
+ },
+ HTTPCustomRequestPanel({ connector })
+ ),
+ showSearchPanel &&
+ TabPanel(
+ {
+ id: PANELS.SEARCH,
+ title: L10N.getStr("netmonitor.actionbar.search"),
+ className: "network-action-bar-search",
+ },
+ SearchPanel({ connector })
+ ),
+ showBlockingPanel &&
+ TabPanel(
+ {
+ id: PANELS.BLOCKING,
+ title: L10N.getStr("netmonitor.actionbar.requestBlocking2"),
+ className: "network-action-bar-blocked",
+ },
+ RequestBlockingPanel()
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ selectedActionBarTabId: state.ui.selectedActionBarTabId,
+ }),
+ dispatch => ({
+ selectActionBarTab: id => dispatch(Actions.selectActionBarTab(id)),
+ toggleNetworkActionBar: () => dispatch(Actions.toggleNetworkActionBar()),
+ })
+)(NetworkActionBar);
diff --git a/devtools/client/netmonitor/src/components/SecurityState.js b/devtools/client/netmonitor/src/components/SecurityState.js
new file mode 100644
index 0000000000..74e098d290
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/SecurityState.js
@@ -0,0 +1,78 @@
+/* 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 {
+ div,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const UPDATED_DOMAIN_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class SecurityState extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_DOMAIN_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ securityState,
+ urlDetails: { isLocal },
+ } = item;
+ const iconClassList = ["requests-security-state-icon"];
+
+ let iconTitle;
+ let realSecurityState = securityState;
+
+ // Locally delivered files such as http://localhost and file:// paths
+ // are considered to have been delivered securely.
+ if (isLocal) {
+ realSecurityState = "secure";
+ }
+
+ if (realSecurityState) {
+ iconClassList.push(`security-state-${realSecurityState}`);
+ iconTitle = L10N.getStr(`netmonitor.security.state.${realSecurityState}`);
+ }
+
+ return div(
+ { className: "requests-security-icon-group" },
+ div({
+ className: iconClassList.join(" "),
+ onMouseDown: onSecurityIconMouseDown,
+ title: iconTitle,
+ }),
+ item.isThirdPartyTrackingResource &&
+ div({
+ className: "tracking-resource",
+ title: L10N.getStr("netmonitor.trackingResource.tooltip"),
+ })
+ );
+ }
+}
+
+module.exports = SecurityState;
diff --git a/devtools/client/netmonitor/src/components/SourceEditor.js b/devtools/client/netmonitor/src/components/SourceEditor.js
new file mode 100644
index 0000000000..89165e8a77
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/SourceEditor.js
@@ -0,0 +1,137 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+const { div } = dom;
+
+/**
+ * CodeMirror editor as a React component
+ */
+class SourceEditor extends Component {
+ static get propTypes() {
+ return {
+ // Source editor syntax highlight mode, which is a mime type defined in CodeMirror
+ mode: PropTypes.string,
+ // Source editor content
+ text: PropTypes.string,
+ // Auto scroll to specific line
+ scrollToLine: PropTypes.number,
+ // Reset target search result that has been used for navigation in this panel.
+ // This is done to avoid second navigation the next time.
+ resetTargetSearchResult: PropTypes.func,
+ };
+ }
+
+ componentDidMount() {
+ const { mode, text } = this.props;
+
+ this.editor = new Editor({
+ lineNumbers: true,
+ lineWrapping: false,
+ mode: null, // Disable auto syntax detection, but then we set mode asynchronously
+ readOnly: true,
+ theme: "mozilla",
+ value: text,
+ });
+
+ // Delay to CodeMirror initialization content to prevent UI freezing
+ this.editorTimeout = setTimeout(() => {
+ this.editorTimeout = null;
+ this.editor.appendToLocalElement(this.refs.editorElement);
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.scrollToLine();
+ });
+ });
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.mode !== this.props.mode ||
+ nextProps.text !== this.props.text ||
+ nextProps.scrollToLine !== this.props.scrollToLine
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ const { mode, scrollToLine, text } = this.props;
+
+ // Bail out if the editor has been destroyed in the meantime.
+ if (this.editor.isDestroyed()) {
+ return;
+ }
+
+ if (prevProps.text !== text) {
+ // Reset the existed 'mode' attribute in order to make setText() process faster
+ // to prevent drawing unnecessary syntax highlight.
+ this.editor.setMode(null);
+ this.editor.setText(text);
+
+ if (this.editorSetModeTimeout) {
+ clearTimeout(this.editorSetModeTimeout);
+ }
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.scrollToLine();
+ });
+ } else if (prevProps.scrollToLine !== scrollToLine) {
+ this.scrollToLine();
+ }
+ }
+
+ componentWillUnmount() {
+ clearTimeout(this.editorTimeout);
+ clearTimeout(this.editorSetModeTimeout);
+ this.editor.destroy();
+ }
+
+ scrollToLine() {
+ const { scrollToLine, resetTargetSearchResult } = this.props;
+
+ if (scrollToLine) {
+ this.editor.setCursor(
+ {
+ line: scrollToLine - 1,
+ },
+ "center"
+ );
+ }
+
+ resetTargetSearchResult();
+ }
+
+ render() {
+ return div({
+ ref: "editorElement",
+ className: "source-editor-mount devtools-monospace",
+ });
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(SourceEditor);
diff --git a/devtools/client/netmonitor/src/components/StatisticsPanel.js b/devtools/client/netmonitor/src/components/StatisticsPanel.js
new file mode 100644
index 0000000000..e3d6787819
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatisticsPanel.js
@@ -0,0 +1,413 @@
+/* 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 ReactDOM = require("resource://devtools/client/shared/vendor/react-dom.js");
+const {
+ FILTER_TAGS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ Component,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { Chart } = require("resource://devtools/client/shared/widgets/Chart.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ Filters,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-predicates.js");
+const {
+ getSizeWithDecimals,
+ getTimeWithDecimals,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getPerformanceAnalysisURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const MDNLink = createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+);
+
+const { button, div } = dom;
+const MediaQueryList = window.matchMedia("(min-width: 700px)");
+
+const NETWORK_ANALYSIS_PIE_CHART_DIAMETER = 200;
+const BACK_BUTTON = L10N.getStr("netmonitor.backButton");
+const CHARTS_CACHE_ENABLED = L10N.getStr("charts.cacheEnabled");
+const CHARTS_CACHE_DISABLED = L10N.getStr("charts.cacheDisabled");
+const CHARTS_LEARN_MORE = L10N.getStr("charts.learnMore");
+
+/*
+ * Statistics panel component
+ * Performance analysis tool which shows you how long the browser takes to
+ * download the different parts of your site.
+ */
+class StatisticsPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ closeStatistics: PropTypes.func.isRequired,
+ enableRequestFilterTypeOnly: PropTypes.func.isRequired,
+ hasLoad: PropTypes.bool,
+ requests: PropTypes.array,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ isVerticalSpliter: MediaQueryList.matches,
+ };
+
+ this.createMDNLink = this.createMDNLink.bind(this);
+ this.unmountMDNLinkContainers = this.unmountMDNLinkContainers.bind(this);
+ this.createChart = this.createChart.bind(this);
+ this.sanitizeChartDataSource = this.sanitizeChartDataSource.bind(this);
+ this.responseIsFresh = this.responseIsFresh.bind(this);
+ this.onLayoutChange = this.onLayoutChange.bind(this);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ this.mdnLinkContainerNodes = new Map();
+ }
+
+ componentDidMount() {
+ const { requests, connector } = this.props;
+ requests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "eventTimings",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { requests, connector } = nextProps;
+ requests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "eventTimings",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ componentDidUpdate(prevProps) {
+ MediaQueryList.addListener(this.onLayoutChange);
+
+ const { hasLoad, requests } = this.props;
+
+ // Display statistics about all requests for which we received enough data,
+ // as soon as the page is considered to be loaded
+ const ready = requests.length && hasLoad;
+
+ // Ignore requests which are missing data expected by this component:
+ // - pending/incomplete requests
+ // - blocked/errored requests
+ const validRequests = requests.filter(
+ req =>
+ req.contentSize !== undefined &&
+ req.mimeType &&
+ req.responseHeaders &&
+ req.status !== undefined &&
+ req.totalTime !== undefined
+ );
+
+ this.createChart({
+ id: "primedCacheChart",
+ title: CHARTS_CACHE_ENABLED,
+ data: ready ? this.sanitizeChartDataSource(validRequests, false) : null,
+ });
+
+ this.createChart({
+ id: "emptyCacheChart",
+ title: CHARTS_CACHE_DISABLED,
+ data: ready ? this.sanitizeChartDataSource(validRequests, true) : null,
+ });
+
+ this.createMDNLink("primedCacheChart", getPerformanceAnalysisURL());
+ this.createMDNLink("emptyCacheChart", getPerformanceAnalysisURL());
+ }
+
+ componentWillUnmount() {
+ MediaQueryList.removeListener(this.onLayoutChange);
+ this.unmountMDNLinkContainers();
+ }
+
+ createMDNLink(chartId, url) {
+ if (this.mdnLinkContainerNodes.has(chartId)) {
+ ReactDOM.unmountComponentAtNode(this.mdnLinkContainerNodes.get(chartId));
+ }
+
+ // MDNLink is a React component but Chart isn't. To get the link
+ // into the chart we mount a new ReactDOM at the appropriate
+ // location after the chart has been created.
+ const title = this.refs[chartId].querySelector(".table-chart-title");
+ const containerNode = document.createElement("span");
+ title.appendChild(containerNode);
+
+ ReactDOM.render(
+ MDNLink({
+ url,
+ title: CHARTS_LEARN_MORE,
+ }),
+ containerNode
+ );
+ this.mdnLinkContainerNodes.set(chartId, containerNode);
+ }
+
+ unmountMDNLinkContainers() {
+ for (const [, node] of this.mdnLinkContainerNodes) {
+ ReactDOM.unmountComponentAtNode(node);
+ }
+ }
+
+ createChart({ id, title, data }) {
+ // Create a new chart.
+ const chart = Chart.PieTable(document, {
+ diameter: NETWORK_ANALYSIS_PIE_CHART_DIAMETER,
+ title,
+ header: {
+ count: L10N.getStr("charts.requestsNumber"),
+ label: L10N.getStr("charts.type"),
+ size: L10N.getStr("charts.size"),
+ transferredSize: L10N.getStr("charts.transferred"),
+ time: L10N.getStr("charts.time"),
+ nonBlockingTime: L10N.getStr("charts.nonBlockingTime"),
+ },
+ data,
+ strings: {
+ size: value =>
+ L10N.getFormatStr(
+ "charts.size.kB",
+ getSizeWithDecimals(value / 1000)
+ ),
+ transferredSize: value =>
+ L10N.getFormatStr(
+ "charts.transferredSize.kB",
+ getSizeWithDecimals(value / 1000)
+ ),
+ time: value =>
+ L10N.getFormatStr("charts.totalS", getTimeWithDecimals(value / 1000)),
+ nonBlockingTime: value =>
+ L10N.getFormatStr("charts.totalS", getTimeWithDecimals(value / 1000)),
+ },
+ totals: {
+ cached: total => L10N.getFormatStr("charts.totalCached", total),
+ count: total => L10N.getFormatStr("charts.totalCount", total),
+ size: total =>
+ L10N.getFormatStr(
+ "charts.totalSize.kB",
+ getSizeWithDecimals(total / 1000)
+ ),
+ transferredSize: total =>
+ L10N.getFormatStr(
+ "charts.totalTransferredSize.kB",
+ getSizeWithDecimals(total / 1000)
+ ),
+ time: total => {
+ const seconds = total / 1000;
+ const string = getTimeWithDecimals(seconds);
+ return PluralForm.get(
+ seconds,
+ L10N.getStr("charts.totalSeconds")
+ ).replace("#1", string);
+ },
+ nonBlockingTime: total => {
+ const seconds = total / 1000;
+ const string = getTimeWithDecimals(seconds);
+ return PluralForm.get(
+ seconds,
+ L10N.getStr("charts.totalSecondsNonBlocking")
+ ).replace("#1", string);
+ },
+ },
+ sorted: true,
+ });
+
+ chart.on("click", ({ label }) => {
+ // Reset FilterButtons and enable one filter exclusively
+ this.props.closeStatistics();
+ this.props.enableRequestFilterTypeOnly(label);
+ });
+
+ const container = this.refs[id];
+
+ // Nuke all existing charts of the specified type.
+ while (container.hasChildNodes()) {
+ container.firstChild.remove();
+ }
+
+ container.appendChild(chart.node);
+ }
+
+ sanitizeChartDataSource(requests, emptyCache) {
+ const data = FILTER_TAGS.map(type => ({
+ cached: 0,
+ count: 0,
+ label: type,
+ size: 0,
+ transferredSize: 0,
+ time: 0,
+ nonBlockingTime: 0,
+ }));
+
+ for (const request of requests) {
+ let type;
+
+ if (Filters.html(request)) {
+ // "html"
+ type = 0;
+ } else if (Filters.css(request)) {
+ // "css"
+ type = 1;
+ } else if (Filters.js(request)) {
+ // "js"
+ type = 2;
+ } else if (Filters.fonts(request)) {
+ // "fonts"
+ type = 4;
+ } else if (Filters.images(request)) {
+ // "images"
+ type = 5;
+ } else if (Filters.media(request)) {
+ // "media"
+ type = 6;
+ } else if (Filters.ws(request)) {
+ // "ws"
+ type = 7;
+ } else if (Filters.xhr(request)) {
+ // Verify XHR last, to categorize other mime types in their own blobs.
+ // "xhr"
+ type = 3;
+ } else {
+ // "other"
+ type = 8;
+ }
+
+ if (emptyCache || !this.responseIsFresh(request)) {
+ data[type].time += request.totalTime || 0;
+ data[type].size += request.contentSize || 0;
+ data[type].transferredSize += request.transferredSize || 0;
+ const nonBlockingTime =
+ request.eventTimings.totalTime - request.eventTimings.timings.blocked;
+ data[type].nonBlockingTime += nonBlockingTime || 0;
+ } else {
+ data[type].cached++;
+ }
+ data[type].count++;
+ }
+
+ return data.filter(e => e.count > 0);
+ }
+
+ /**
+ * Checks if the "Expiration Calculations" defined in section 13.2.4 of the
+ * "HTTP/1.1: Caching in HTTP" spec holds true for a collection of headers.
+ *
+ * @param object
+ * An object containing the { responseHeaders, status } properties.
+ * @return boolean
+ * True if the response is fresh and loaded from cache.
+ */
+ responseIsFresh({ responseHeaders, status }) {
+ // Check for a "304 Not Modified" status and response headers availability.
+ if (status != 304 || !responseHeaders) {
+ return false;
+ }
+
+ const list = responseHeaders.headers;
+ const cacheControl = list.find(
+ e => e.name.toLowerCase() === "cache-control"
+ );
+ const expires = list.find(e => e.name.toLowerCase() === "expires");
+
+ // Check the "Cache-Control" header for a maximum age value.
+ if (cacheControl) {
+ const maxAgeMatch =
+ cacheControl.value.match(/s-maxage\s*=\s*(\d+)/) ||
+ cacheControl.value.match(/max-age\s*=\s*(\d+)/);
+
+ if (maxAgeMatch && maxAgeMatch.pop() > 0) {
+ return true;
+ }
+ }
+
+ // Check the "Expires" header for a valid date.
+ if (expires && Date.parse(expires.value)) {
+ return true;
+ }
+
+ return false;
+ }
+
+ onLayoutChange() {
+ this.setState({
+ isVerticalSpliter: MediaQueryList.matches,
+ });
+ }
+
+ render() {
+ const { closeStatistics } = this.props;
+ const splitterClassName = ["splitter"];
+
+ if (this.state.isVerticalSpliter) {
+ splitterClassName.push("devtools-side-splitter");
+ } else {
+ splitterClassName.push("devtools-horizontal-splitter");
+ }
+
+ return div(
+ { className: "statistics-panel" },
+ button(
+ {
+ className: "back-button devtools-button",
+ "data-text-only": "true",
+ title: BACK_BUTTON,
+ onClick: closeStatistics,
+ },
+ BACK_BUTTON
+ ),
+ div(
+ { className: "charts-container" },
+ div({
+ ref: "primedCacheChart",
+ className: "charts primed-cache-chart",
+ }),
+ div({ className: splitterClassName.join(" ") }),
+ div({ ref: "emptyCacheChart", className: "charts empty-cache-chart" })
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ // `firstDocumentLoadTimestamp` is set on timing markers when we receive
+ // DOCUMENT_EVENT's dom-complete, which is equivalent to page `load` event.
+ hasLoad: state.timingMarkers.firstDocumentLoadTimestamp != -1,
+ requests: [...state.requests.requests],
+ }),
+ (dispatch, props) => ({
+ closeStatistics: () =>
+ dispatch(Actions.openStatistics(props.connector, false)),
+ enableRequestFilterTypeOnly: label =>
+ dispatch(Actions.enableRequestFilterTypeOnly(label)),
+ })
+)(StatisticsPanel);
diff --git a/devtools/client/netmonitor/src/components/StatusBar.js b/devtools/client/netmonitor/src/components/StatusBar.js
new file mode 100644
index 0000000000..3a6c73e0db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatusBar.js
@@ -0,0 +1,175 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getDisplayedRequestsSummary,
+ getDisplayedTimingMarker,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getFormattedSize,
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { button, div } = dom;
+
+const REQUESTS_COUNT_EMPTY = L10N.getStr(
+ "networkMenu.summary.requestsCountEmpty"
+);
+const TOOLTIP_PERF = L10N.getStr("networkMenu.summary.tooltip.perf");
+const TOOLTIP_REQUESTS_COUNT = L10N.getStr(
+ "networkMenu.summary.tooltip.requestsCount"
+);
+const TOOLTIP_TRANSFERRED = L10N.getStr(
+ "networkMenu.summary.tooltip.transferred"
+);
+const TOOLTIP_FINISH = L10N.getStr("networkMenu.summary.tooltip.finish");
+const TOOLTIP_DOM_CONTENT_LOADED = L10N.getStr(
+ "networkMenu.summary.tooltip.domContentLoaded"
+);
+const TOOLTIP_LOAD = L10N.getStr("networkMenu.summary.tooltip.load");
+
+const UPDATED_SUMMARY_PROPS = ["count", "contentSize", "transferredSize", "ms"];
+
+const UPDATED_TIMING_PROPS = ["DOMContentLoaded", "load"];
+
+/**
+ * Status Bar component
+ * Displays the summary of total size and transferred size by all requests
+ * Also displays different timing markers
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openStatistics: PropTypes.func.isRequired,
+ summary: PropTypes.object.isRequired,
+ timingMarkers: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const { summary, timingMarkers } = this.props;
+ return (
+ !propertiesEqual(UPDATED_SUMMARY_PROPS, summary, nextProps.summary) ||
+ !propertiesEqual(
+ UPDATED_TIMING_PROPS,
+ timingMarkers,
+ nextProps.timingMarkers
+ )
+ );
+ }
+
+ render() {
+ const { openStatistics, summary, timingMarkers, connector } = this.props;
+ const { count, contentSize, transferredSize, ms } = summary;
+ const { DOMContentLoaded, load } = timingMarkers;
+
+ const toolbox = connector.getToolbox();
+ const countText =
+ count === 0
+ ? REQUESTS_COUNT_EMPTY
+ : PluralForm.get(
+ count,
+ L10N.getStr("networkMenu.summary.requestsCount2")
+ ).replace("#1", count);
+ const transferText = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.transferred",
+ getFormattedSize(contentSize),
+ getFormattedSize(transferredSize)
+ );
+ const finishText = L10N.getFormatStrWithNumbers(
+ "networkMenu.summary.finish",
+ getFormattedTime(ms)
+ );
+
+ return div(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ !toolbox.isBrowserToolbox
+ ? button(
+ {
+ className: "devtools-button requests-list-network-summary-button",
+ title: TOOLTIP_PERF,
+ onClick: openStatistics,
+ },
+ div({ className: "summary-info-icon" })
+ )
+ : null,
+ div(
+ {
+ className: "status-bar-label requests-list-network-summary-count",
+ title: TOOLTIP_REQUESTS_COUNT,
+ },
+ countText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className:
+ "status-bar-label requests-list-network-summary-transfer",
+ title: TOOLTIP_TRANSFERRED,
+ },
+ transferText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label requests-list-network-summary-finish",
+ title: TOOLTIP_FINISH,
+ },
+ finishText
+ ),
+ DOMContentLoaded > -1 &&
+ div(
+ {
+ className: "status-bar-label dom-content-loaded",
+ title: TOOLTIP_DOM_CONTENT_LOADED,
+ },
+ `DOMContentLoaded: ${getFormattedTime(DOMContentLoaded)}`
+ ),
+ load > -1 &&
+ div(
+ {
+ className: "status-bar-label load",
+ title: TOOLTIP_LOAD,
+ },
+ `load: ${getFormattedTime(load)}`
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ summary: getDisplayedRequestsSummary(state),
+ timingMarkers: {
+ DOMContentLoaded: getDisplayedTimingMarker(
+ state,
+ "firstDocumentDOMContentLoadedTimestamp"
+ ),
+ load: getDisplayedTimingMarker(state, "firstDocumentLoadTimestamp"),
+ },
+ }),
+ (dispatch, props) => ({
+ openStatistics: () =>
+ dispatch(Actions.openStatistics(props.connector, true)),
+ })
+)(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/StatusCode.js b/devtools/client/netmonitor/src/components/StatusCode.js
new file mode 100644
index 0000000000..7f4f082636
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/StatusCode.js
@@ -0,0 +1,129 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { div } = dom;
+
+const UPDATED_STATUS_PROPS = [
+ "fromCache",
+ "fromServiceWorker",
+ "status",
+ "statusText",
+];
+
+/**
+ * Status code component
+ * Displays HTTP status code icon
+ * Used in RequestListColumnStatus and HeadersPanel
+ */
+class StatusCode extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_STATUS_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item } = this.props;
+ const { fromCache, fromServiceWorker, status, statusText, blockedReason } =
+ item;
+ let code;
+
+ if (status) {
+ if (fromCache) {
+ code = "cached";
+ } else if (fromServiceWorker) {
+ code = "service worker";
+ } else {
+ code = status;
+ }
+ }
+
+ if (blockedReason) {
+ return div(
+ {
+ className:
+ "requests-list-status-code status-code status-code-blocked",
+ title: L10N.getStr("networkMenu.blockedTooltip"),
+ },
+ div({
+ className: "status-code-blocked-icon",
+ })
+ );
+ }
+
+ // `data-code` refers to the status-code
+ // `data-status-code` can be one of "cached", "service worker"
+ // or the status-code itself
+ // For example - if a resource is cached, `data-code` would be 200
+ // and the `data-status-code` would be "cached"
+ return div(
+ {
+ className: "requests-list-status-code status-code",
+ onMouseOver({ target }) {
+ if (status && statusText && !target.title) {
+ target.title = getStatusTooltip(item);
+ }
+ },
+ "data-status-code": code,
+ "data-code": status,
+ },
+ status
+ );
+ }
+}
+
+function getStatusTooltip(item) {
+ const { fromCache, fromServiceWorker, status, statusText } = item;
+ let title;
+ if (fromCache && fromServiceWorker) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.cachedworker",
+ status,
+ statusText
+ );
+ } else if (fromCache) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.cached",
+ status,
+ statusText
+ );
+ } else if (fromServiceWorker) {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.worker",
+ status,
+ statusText
+ );
+ } else {
+ title = L10N.getFormatStr(
+ "netmonitor.status.tooltip.simple",
+ status,
+ statusText
+ );
+ }
+ return title;
+}
+
+module.exports = StatusCode;
diff --git a/devtools/client/netmonitor/src/components/TabboxPanel.js b/devtools/client/netmonitor/src/components/TabboxPanel.js
new file mode 100644
index 0000000000..9395b53307
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/TabboxPanel.js
@@ -0,0 +1,242 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const Tabbar = createFactory(
+ require("resource://devtools/client/shared/components/tabs/TabBar.js")
+);
+const TabPanel = createFactory(
+ require("resource://devtools/client/shared/components/tabs/Tabs.js").TabPanel
+);
+const CookiesPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/CookiesPanel.js")
+);
+const HeadersPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/HeadersPanel.js")
+);
+const RequestPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/RequestPanel.js")
+);
+const CachePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/CachePanel.js")
+);
+const ResponsePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/ResponsePanel.js")
+);
+const SecurityPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/SecurityPanel.js")
+);
+const StackTracePanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/StackTracePanel.js")
+);
+const TimingsPanel = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/TimingsPanel.js")
+);
+
+const COLLAPSE_DETAILS_PANE = L10N.getStr("collapseDetailsPane");
+const ALL_TABS_MENU_BUTTON_TOOLTIP = L10N.getStr("allTabsMenuButton.tooltip");
+const CACHE_TITLE = L10N.getStr("netmonitor.tab.cache");
+const COOKIES_TITLE = L10N.getStr("netmonitor.tab.cookies");
+const HEADERS_TITLE = L10N.getStr("netmonitor.tab.headers");
+const REQUEST_TITLE = L10N.getStr("netmonitor.tab.request");
+const RESPONSE_TITLE = L10N.getStr("netmonitor.tab.response");
+const SECURITY_TITLE = L10N.getStr("netmonitor.tab.security");
+const STACK_TRACE_TITLE = L10N.getStr("netmonitor.tab.stackTrace");
+const TIMINGS_TITLE = L10N.getStr("netmonitor.tab.timings");
+
+/**
+ * Tabbox panel component
+ * Display the network request details
+ */
+class TabboxPanel extends Component {
+ static get propTypes() {
+ return {
+ activeTabId: PropTypes.string,
+ cloneSelectedRequest: PropTypes.func,
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object,
+ selectTab: PropTypes.func.isRequired,
+ sourceMapURLService: PropTypes.object,
+ hideToggleButton: PropTypes.bool,
+ toggleNetworkDetails: PropTypes.func,
+ openNetworkDetails: PropTypes.func.isRequired,
+ showMessagesView: PropTypes.bool,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+ static get defaultProps() {
+ return {
+ showMessagesView: true,
+ };
+ }
+ componentDidMount() {
+ this.closeOnEscRef = this.closeOnEsc.bind(this);
+ window.addEventListener("keydown", this.closeOnEscRef);
+ }
+
+ componentWillUnmount() {
+ window.removeEventListener("keydown", this.closeOnEscRef);
+ }
+
+ closeOnEsc(event) {
+ if (event.key == "Escape") {
+ event.preventDefault();
+ this.props.openNetworkDetails(false);
+ }
+ }
+
+ render() {
+ const {
+ activeTabId,
+ cloneSelectedRequest = () => {},
+ connector,
+ hideToggleButton,
+ openLink,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ targetSearchResult,
+ } = this.props;
+
+ if (!request) {
+ return null;
+ }
+
+ const isWs = request.cause.type === "websocket";
+ const isSse = request.isEventStream;
+
+ const showMessagesView = (isWs || isSse) && this.props.showMessagesView;
+
+ return Tabbar(
+ {
+ activeTabId,
+ menuDocument: window.parent.document,
+ onSelect: selectTab,
+ renderOnlySelected: true,
+ showAllTabsMenu: true,
+ allTabsMenuButtonTooltip: ALL_TABS_MENU_BUTTON_TOOLTIP,
+ sidebarToggleButton: hideToggleButton
+ ? null
+ : {
+ collapsed: false,
+ collapsePaneTitle: COLLAPSE_DETAILS_PANE,
+ expandPaneTitle: "",
+ onClick: toggleNetworkDetails,
+ },
+ },
+ TabPanel(
+ {
+ id: PANELS.HEADERS,
+ title: HEADERS_TITLE,
+ className: "panel-with-code",
+ },
+ HeadersPanel({
+ cloneSelectedRequest,
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.COOKIES,
+ title: COOKIES_TITLE,
+ className: "panel-with-code",
+ },
+ CookiesPanel({
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.REQUEST,
+ title: REQUEST_TITLE,
+ className: "panel-with-code",
+ },
+ RequestPanel({
+ connector,
+ openLink,
+ request,
+ targetSearchResult,
+ })
+ ),
+ TabPanel(
+ {
+ id: PANELS.RESPONSE,
+ title: RESPONSE_TITLE,
+ className: "panel-with-code",
+ },
+ ResponsePanel({
+ request,
+ openLink,
+ connector,
+ showMessagesView,
+ targetSearchResult,
+ })
+ ),
+ (request.fromCache || request.status == "304") &&
+ TabPanel(
+ {
+ id: PANELS.CACHE,
+ title: CACHE_TITLE,
+ },
+ CachePanel({ request, openLink, connector })
+ ),
+ TabPanel(
+ {
+ id: PANELS.TIMINGS,
+ title: TIMINGS_TITLE,
+ },
+ TimingsPanel({
+ connector,
+ request,
+ })
+ ),
+ request.cause?.stacktraceAvailable &&
+ TabPanel(
+ {
+ id: PANELS.STACK_TRACE,
+ title: STACK_TRACE_TITLE,
+ className: "panel-with-code",
+ },
+ StackTracePanel({ connector, openLink, request, sourceMapURLService })
+ ),
+ request.securityState &&
+ request.securityState !== "insecure" &&
+ TabPanel(
+ {
+ id: PANELS.SECURITY,
+ title: SECURITY_TITLE,
+ },
+ SecurityPanel({
+ connector,
+ openLink,
+ request,
+ })
+ )
+ );
+ }
+}
+
+module.exports = TabboxPanel;
diff --git a/devtools/client/netmonitor/src/components/Toolbar.js b/devtools/client/netmonitor/src/components/Toolbar.js
new file mode 100644
index 0000000000..0da3d826c2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/Toolbar.js
@@ -0,0 +1,688 @@
+/* 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,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ FILTER_SEARCH_DELAY,
+ FILTER_TAGS,
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getDisplayedRequests,
+ getRecordingState,
+ getTypeFilteredRequests,
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ autocompleteProvider,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+loader.lazyRequireGetter(
+ this,
+ "KeyShortcuts",
+ "resource://devtools/client/shared/key-shortcuts.js"
+);
+
+// MDN
+const {
+ getFilterBoxURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const LEARN_MORE_URL = getFilterBoxURL();
+
+// Components
+const NetworkThrottlingMenu = createFactory(
+ require("resource://devtools/client/shared/components/throttling/NetworkThrottlingMenu.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+const { button, div, input, label, span, hr } = dom;
+
+// Localization
+const FILTER_KEY_SHORTCUT = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.key"
+);
+const SEARCH_KEY_SHORTCUT = L10N.getStr("netmonitor.toolbar.search.key");
+const SEARCH_PLACE_HOLDER = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.label"
+);
+const COPY_KEY_SHORTCUT = L10N.getStr("netmonitor.toolbar.copy.key");
+const TOOLBAR_CLEAR = L10N.getStr("netmonitor.toolbar.clear");
+const TOOLBAR_TOGGLE_RECORDING = L10N.getStr(
+ "netmonitor.toolbar.toggleRecording"
+);
+const TOOLBAR_HTTP_CUSTOM_REQUEST = L10N.getStr(
+ "netmonitor.toolbar.HTTPCustomRequest"
+);
+const TOOLBAR_SEARCH = L10N.getStr("netmonitor.toolbar.search");
+const TOOLBAR_BLOCKING = L10N.getStr("netmonitor.toolbar.requestBlocking");
+const LEARN_MORE_TITLE = L10N.getStr(
+ "netmonitor.toolbar.filterFreetext.learnMore"
+);
+
+// Preferences
+const DEVTOOLS_DISABLE_CACHE_PREF = "devtools.cache.disabled";
+const DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF = "devtools.netmonitor.persistlog";
+const TOOLBAR_FILTER_LABELS = FILTER_TAGS.concat("all").reduce(
+ (o, tag) =>
+ Object.assign(o, {
+ [tag]: L10N.getStr(`netmonitor.toolbar.filter.${tag}`),
+ }),
+ {}
+);
+const DISABLE_CACHE_TOOLTIP = L10N.getStr(
+ "netmonitor.toolbar.disableCache.tooltip"
+);
+const DISABLE_CACHE_LABEL = L10N.getStr(
+ "netmonitor.toolbar.disableCache.label"
+);
+
+const MenuButton = createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuButton.js")
+);
+
+loader.lazyGetter(this, "MenuItem", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuItem.js")
+ );
+});
+
+loader.lazyGetter(this, "MenuList", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/menu/MenuList.js")
+ );
+});
+
+// Menu
+loader.lazyRequireGetter(
+ this,
+ "HarMenuUtils",
+ "resource://devtools/client/netmonitor/src/har/har-menu-utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+
+// Throttling
+const Types = require("resource://devtools/client/shared/components/throttling/types.js");
+const {
+ changeNetworkThrottling,
+} = require("resource://devtools/client/shared/components/throttling/actions.js");
+
+/**
+ * Network monitor toolbar component.
+ *
+ * Toolbar contains a set of useful tools to control network requests
+ * as well as set of filters for filtering the content.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ actions: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ toggleRecording: PropTypes.func.isRequired,
+ recording: PropTypes.bool.isRequired,
+ clearRequests: PropTypes.func.isRequired,
+ // List of currently displayed requests (i.e. filtered & sorted).
+ displayedRequests: PropTypes.array.isRequired,
+ requestFilterTypes: PropTypes.object.isRequired,
+ setRequestFilterText: PropTypes.func.isRequired,
+ enablePersistentLogs: PropTypes.func.isRequired,
+ togglePersistentLogs: PropTypes.func.isRequired,
+ persistentLogsEnabled: PropTypes.bool.isRequired,
+ disableBrowserCache: PropTypes.func.isRequired,
+ toggleBrowserCache: PropTypes.func.isRequired,
+ browserCacheDisabled: PropTypes.bool.isRequired,
+ toggleRequestFilterType: PropTypes.func.isRequired,
+ filteredRequests: PropTypes.array.isRequired,
+ // Set to true if there is enough horizontal space
+ // and the toolbar needs just one row.
+ singleRow: PropTypes.bool.isRequired,
+ // Callback for opening split console.
+ openSplitConsole: PropTypes.func,
+ networkThrottling: PropTypes.shape(Types.networkThrottling).isRequired,
+ // Executed when throttling changes (through toolbar button).
+ onChangeNetworkThrottling: PropTypes.func.isRequired,
+ toggleSearchPanel: PropTypes.func.isRequired,
+ toggleHTTPCustomRequestPanel: PropTypes.func.isRequired,
+ networkActionBarOpen: PropTypes.bool,
+ toggleRequestBlockingPanel: PropTypes.func.isRequired,
+ networkActionBarSelectedPanel: PropTypes.string.isRequired,
+ hasBlockedRequests: PropTypes.bool.isRequired,
+ selectedRequest: PropTypes.object,
+ toolboxDoc: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.autocompleteProvider = this.autocompleteProvider.bind(this);
+ this.onSearchBoxFocusKeyboardShortcut =
+ this.onSearchBoxFocusKeyboardShortcut.bind(this);
+ this.onSearchBoxFocus = this.onSearchBoxFocus.bind(this);
+ this.toggleRequestFilterType = this.toggleRequestFilterType.bind(this);
+ this.updatePersistentLogsEnabled =
+ this.updatePersistentLogsEnabled.bind(this);
+ this.updateBrowserCacheDisabled =
+ this.updateBrowserCacheDisabled.bind(this);
+ }
+
+ componentDidMount() {
+ Services.prefs.addObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersistentLogsEnabled
+ );
+ Services.prefs.addObserver(
+ DEVTOOLS_DISABLE_CACHE_PREF,
+ this.updateBrowserCacheDisabled
+ );
+
+ this.shortcuts = new KeyShortcuts({
+ window,
+ });
+
+ this.shortcuts.on(SEARCH_KEY_SHORTCUT, event => {
+ event.preventDefault();
+ this.props.toggleSearchPanel();
+ });
+
+ this.shortcuts.on(COPY_KEY_SHORTCUT, () => {
+ if (this.props.selectedRequest && this.props.selectedRequest.url) {
+ copyString(this.props.selectedRequest.url);
+ }
+ });
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.persistentLogsEnabled !== nextProps.persistentLogsEnabled ||
+ this.props.browserCacheDisabled !== nextProps.browserCacheDisabled ||
+ this.props.recording !== nextProps.recording ||
+ this.props.networkActionBarOpen !== nextProps.networkActionBarOpen ||
+ this.props.singleRow !== nextProps.singleRow ||
+ !Object.is(this.props.requestFilterTypes, nextProps.requestFilterTypes) ||
+ this.props.networkThrottling !== nextProps.networkThrottling ||
+ // Filtered requests are useful only when searchbox is focused
+ !!(this.refs.searchbox && this.refs.searchbox.focused) ||
+ this.props.networkActionBarSelectedPanel !==
+ nextProps.networkActionBarSelectedPanel ||
+ this.props.hasBlockedRequests !== nextProps.hasBlockedRequests
+ );
+ }
+
+ componentWillUnmount() {
+ Services.prefs.removeObserver(
+ DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF,
+ this.updatePersistentLogsEnabled
+ );
+ Services.prefs.removeObserver(
+ DEVTOOLS_DISABLE_CACHE_PREF,
+ this.updateBrowserCacheDisabled
+ );
+
+ if (this.shortcuts) {
+ this.shortcuts.destroy();
+ }
+ }
+
+ toggleRequestFilterType(evt) {
+ if (evt.type === "keydown" && (evt.key !== "" || evt.key !== "Enter")) {
+ return;
+ }
+ this.props.toggleRequestFilterType(evt.target.dataset.key);
+ }
+
+ updatePersistentLogsEnabled() {
+ // Make sure the UI is updated when the pref changes.
+ // It might happen when the user changed it through about:config or
+ // through another Toolbox instance (opened in another browser tab).
+ // In such case, skip telemetry recordings.
+ this.props.enablePersistentLogs(
+ Services.prefs.getBoolPref(DEVTOOLS_ENABLE_PERSISTENT_LOG_PREF),
+ true
+ );
+ }
+
+ updateBrowserCacheDisabled() {
+ this.props.disableBrowserCache(
+ Services.prefs.getBoolPref(DEVTOOLS_DISABLE_CACHE_PREF)
+ );
+ }
+
+ autocompleteProvider(filter) {
+ return autocompleteProvider(filter, this.props.filteredRequests);
+ }
+
+ onSearchBoxFocusKeyboardShortcut(event) {
+ // Don't take focus when the keyboard shortcut is triggered in a CodeMirror instance,
+ // so the CodeMirror search UI is displayed.
+ return !!event.target.closest(".CodeMirror");
+ }
+
+ onSearchBoxFocus() {
+ const { connector, filteredRequests } = this.props;
+
+ // Fetch responseCookies & responseHeaders for building autocomplete list
+ filteredRequests.forEach(request => {
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseCookies",
+ "responseHeaders",
+ ]);
+ });
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Render a clear button.
+ */
+ renderClearButton(clearRequests) {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon requests-list-clear-button",
+ title: TOOLBAR_CLEAR,
+ onClick: clearRequests,
+ });
+ }
+
+ /**
+ * Render a ToggleRecording button.
+ */
+ renderToggleRecordingButton(recording, toggleRecording) {
+ // Calculate class-list for toggle recording button.
+ // The button has two states: pause/play.
+ const toggleRecordingButtonClass = [
+ "devtools-button",
+ "requests-list-pause-button",
+ recording ? "devtools-pause-icon" : "devtools-play-icon",
+ ].join(" ");
+
+ return button({
+ className: toggleRecordingButtonClass,
+ title: TOOLBAR_TOGGLE_RECORDING,
+ onClick: toggleRecording,
+ });
+ }
+
+ /**
+ * Render a blocking button.
+ */
+ renderBlockingButton(toggleSearchPanel) {
+ const {
+ networkActionBarOpen,
+ toggleRequestBlockingPanel,
+ networkActionBarSelectedPanel,
+ hasBlockedRequests,
+ } = this.props;
+
+ // The blocking feature is available behind a pref.
+ if (
+ !Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.requestBlocking"
+ )
+ ) {
+ return null;
+ }
+
+ const className = ["devtools-button", "requests-list-blocking-button"];
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.BLOCKING
+ ) {
+ className.push("checked");
+ }
+
+ if (hasBlockedRequests) {
+ className.push("requests-list-blocking-button-enabled");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_BLOCKING,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleRequestBlockingPanel,
+ });
+ }
+
+ /**
+ * Render a search button.
+ */
+ renderSearchButton(toggleSearchPanel) {
+ const { networkActionBarOpen, networkActionBarSelectedPanel } = this.props;
+
+ // The search feature is available behind a pref.
+ if (!Services.prefs.getBoolPref("devtools.netmonitor.features.search")) {
+ return null;
+ }
+
+ const className = [
+ "devtools-button",
+ "devtools-search-icon",
+ "requests-list-search-button",
+ ];
+
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.SEARCH
+ ) {
+ className.push("checked");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_SEARCH,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleSearchPanel,
+ });
+ }
+
+ /**
+ * Render a new HTTP Custom Request button.
+ */
+ renderHTTPCustomRequestButton() {
+ const {
+ networkActionBarOpen,
+ networkActionBarSelectedPanel,
+ toggleHTTPCustomRequestPanel,
+ } = this.props;
+
+ // The new HTTP Custom Request feature is available behind a pref.
+ if (
+ !Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ )
+ ) {
+ return null;
+ }
+
+ const className = [
+ "devtools-button",
+ "devtools-http-custom-request-icon",
+ "requests-list-http-custom-request-button",
+ ];
+
+ if (
+ networkActionBarOpen &&
+ networkActionBarSelectedPanel === PANELS.HTTP_CUSTOM_REQUEST
+ ) {
+ className.push("checked");
+ }
+
+ return button({
+ className: className.join(" "),
+ title: TOOLBAR_HTTP_CUSTOM_REQUEST,
+ "aria-pressed": networkActionBarOpen,
+ onClick: toggleHTTPCustomRequestPanel,
+ });
+ }
+
+ /**
+ * Render filter buttons.
+ */
+ renderFilterButtons(requestFilterTypes) {
+ // Render list of filter-buttons.
+ const buttons = Object.entries(requestFilterTypes).map(([type, checked]) =>
+ button(
+ {
+ className: `devtools-togglebutton requests-list-filter-${type}-button`,
+ key: type,
+ onClick: this.toggleRequestFilterType,
+ onKeyDown: this.toggleRequestFilterType,
+ "aria-pressed": checked,
+ "data-key": type,
+ },
+ TOOLBAR_FILTER_LABELS[type]
+ )
+ );
+ return div({ className: "requests-list-filter-buttons" }, buttons);
+ }
+
+ /**
+ * Render a Cache checkbox.
+ */
+ renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache) {
+ return label(
+ {
+ className: "devtools-checkbox-label devtools-cache-checkbox",
+ title: DISABLE_CACHE_TOOLTIP,
+ },
+ input({
+ id: "devtools-cache-checkbox",
+ className: "devtools-checkbox",
+ type: "checkbox",
+ checked: browserCacheDisabled,
+ onChange: toggleBrowserCache,
+ }),
+ DISABLE_CACHE_LABEL
+ );
+ }
+
+ /**
+ * Render network throttling menu button.
+ */
+ renderThrottlingMenu() {
+ const { networkThrottling, onChangeNetworkThrottling } = this.props;
+
+ return NetworkThrottlingMenu({
+ networkThrottling,
+ onChangeNetworkThrottling,
+ });
+ }
+
+ /**
+ * Render filter Searchbox.
+ */
+ renderFilterBox(setRequestFilterText) {
+ return SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ keyShortcut: FILTER_KEY_SHORTCUT,
+ placeholder: SEARCH_PLACE_HOLDER,
+ type: "filter",
+ ref: "searchbox",
+ onChange: setRequestFilterText,
+ onFocusKeyboardShortcut: this.onSearchBoxFocusKeyboardShortcut,
+ onFocus: this.onSearchBoxFocus,
+ autocompleteProvider: this.autocompleteProvider,
+ learnMoreUrl: LEARN_MORE_URL,
+ learnMoreTitle: LEARN_MORE_TITLE,
+ });
+ }
+
+ renderSettingsMenuButton() {
+ const { toolboxDoc } = this.props;
+ return MenuButton(
+ {
+ menuId: "netmonitor-settings-menu-button",
+ toolboxDoc,
+ className: "devtools-button netmonitor-settings-menu-button",
+ title: L10N.getStr("netmonitor.settings.menuTooltip"),
+ },
+ // We pass the children in a function so we don't require the MenuItem and MenuList
+ // components until we need to display them (i.e. when the button is clicked).
+ () => this.renderSettingsMenuItems()
+ );
+ }
+
+ renderSettingsMenuItems() {
+ const {
+ actions,
+ connector,
+ displayedRequests,
+ openSplitConsole,
+ persistentLogsEnabled,
+ togglePersistentLogs,
+ } = this.props;
+
+ const menuItems = [
+ MenuItem({
+ key: "netmonitor-settings-persist-item",
+ className: "menu-item netmonitor-settings-persist-item",
+ type: "checkbox",
+ checked: persistentLogsEnabled,
+ label: L10N.getStr("netmonitor.toolbar.enablePersistentLogs.label"),
+ tooltip: L10N.getStr("netmonitor.toolbar.enablePersistentLogs.tooltip"),
+ onClick: () => togglePersistentLogs(),
+ }),
+ hr({ key: "netmonitor-settings-har-divider" }),
+ MenuItem({
+ key: "request-list-context-import-har",
+ className: "menu-item netmonitor-settings-import-har-item",
+ label: L10N.getStr("netmonitor.har.importHarDialogTitle"),
+ tooltip: L10N.getStr("netmonitor.settings.importHarTooltip"),
+ accesskey: L10N.getStr("netmonitor.context.importHar.accesskey"),
+ onClick: () => HarMenuUtils.openHarFile(actions, openSplitConsole),
+ }),
+ MenuItem({
+ key: "request-list-context-save-all-as-har",
+ className: "menu-item netmonitor-settings-save-har-item",
+ label: L10N.getStr("netmonitor.context.saveAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.saveAllAsHar.accesskey"),
+ tooltip: L10N.getStr("netmonitor.settings.saveHarTooltip"),
+ disabled: !displayedRequests.length,
+ onClick: () => HarMenuUtils.saveAllAsHar(displayedRequests, connector),
+ }),
+ MenuItem({
+ key: "request-list-context-copy-all-as-har",
+ className: "menu-item netmonitor-settings-copy-har-item",
+ label: L10N.getStr("netmonitor.context.copyAllAsHar"),
+ accesskey: L10N.getStr("netmonitor.context.copyAllAsHar.accesskey"),
+ tooltip: L10N.getStr("netmonitor.settings.copyHarTooltip"),
+ disabled: !displayedRequests.length,
+ onClick: () => HarMenuUtils.copyAllAsHar(displayedRequests, connector),
+ }),
+ ];
+
+ return MenuList({ id: "netmonitor-settings-menu-list" }, menuItems);
+ }
+
+ render() {
+ const {
+ toggleRecording,
+ clearRequests,
+ requestFilterTypes,
+ setRequestFilterText,
+ toggleBrowserCache,
+ browserCacheDisabled,
+ recording,
+ singleRow,
+ toggleSearchPanel,
+ } = this.props;
+
+ // Render the entire toolbar.
+ // dock at bottom or dock at side has different layout
+ return singleRow
+ ? span(
+ { id: "netmonitor-toolbar-container" },
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderClearButton(clearRequests),
+ this.renderSeparator(),
+ this.renderFilterBox(setRequestFilterText),
+ this.renderSeparator(),
+ this.renderToggleRecordingButton(recording, toggleRecording),
+ this.renderHTTPCustomRequestButton(),
+ this.renderSearchButton(toggleSearchPanel),
+ this.renderBlockingButton(toggleSearchPanel),
+ this.renderSeparator(),
+ this.renderFilterButtons(requestFilterTypes),
+ this.renderSeparator(),
+ this.renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache),
+ this.renderSeparator(),
+ this.renderThrottlingMenu(),
+ this.renderSeparator(),
+ this.renderSettingsMenuButton()
+ )
+ )
+ : span(
+ { id: "netmonitor-toolbar-container" },
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderClearButton(clearRequests),
+ this.renderSeparator(),
+ this.renderFilterBox(setRequestFilterText),
+ this.renderSeparator(),
+ this.renderToggleRecordingButton(recording, toggleRecording),
+ this.renderHTTPCustomRequestButton(),
+ this.renderSearchButton(toggleSearchPanel),
+ this.renderBlockingButton(toggleSearchPanel),
+ this.renderSeparator(),
+ this.renderCacheCheckbox(browserCacheDisabled, toggleBrowserCache),
+ this.renderSeparator(),
+ this.renderThrottlingMenu(),
+ this.renderSeparator(),
+ this.renderSettingsMenuButton()
+ ),
+ span(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ this.renderFilterButtons(requestFilterTypes)
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ browserCacheDisabled: state.ui.browserCacheDisabled,
+ displayedRequests: getDisplayedRequests(state),
+ hasBlockedRequests:
+ state.requestBlocking.blockingEnabled &&
+ state.requestBlocking.blockedUrls.some(({ enabled }) => enabled),
+ filteredRequests: getTypeFilteredRequests(state),
+ persistentLogsEnabled: state.ui.persistentLogsEnabled,
+ recording: getRecordingState(state),
+ requestFilterTypes: state.filters.requestFilterTypes,
+ networkThrottling: state.networkThrottling,
+ networkActionBarOpen: state.ui.networkActionOpen,
+ networkActionBarSelectedPanel: state.ui.selectedActionBarTabId || "",
+ selectedRequest: getSelectedRequest(state),
+ }),
+ dispatch => ({
+ clearRequests: () => dispatch(Actions.clearRequests()),
+ disableBrowserCache: disabled =>
+ dispatch(Actions.disableBrowserCache(disabled)),
+ enablePersistentLogs: (enabled, skipTelemetry) =>
+ dispatch(Actions.enablePersistentLogs(enabled, skipTelemetry)),
+ setRequestFilterText: text => dispatch(Actions.setRequestFilterText(text)),
+ toggleBrowserCache: () => dispatch(Actions.toggleBrowserCache()),
+ toggleRecording: () => dispatch(Actions.toggleRecording()),
+ togglePersistentLogs: () => dispatch(Actions.togglePersistentLogs()),
+ toggleRequestFilterType: type =>
+ dispatch(Actions.toggleRequestFilterType(type)),
+ onChangeNetworkThrottling: (enabled, profile) =>
+ dispatch(changeNetworkThrottling(enabled, profile)),
+ toggleHTTPCustomRequestPanel: () =>
+ dispatch(Actions.toggleHTTPCustomRequestPanel()),
+ toggleSearchPanel: () => dispatch(Actions.toggleSearchPanel()),
+ toggleRequestBlockingPanel: () =>
+ dispatch(Actions.toggleRequestBlockingPanel()),
+ })
+)(Toolbar);
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnData.js b/devtools/client/netmonitor/src/components/messages/ColumnData.js
new file mode 100644
index 0000000000..2c4b7c1b60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnData.js
@@ -0,0 +1,60 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ limitTooltipLength,
+} = require("resource://devtools/client/netmonitor/src/utils/tooltips.js");
+
+/**
+ * Renders the "Data" column of a message.
+ */
+class ColumnData extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ connector: PropTypes.object.isRequired,
+ };
+ }
+
+ render() {
+ const { type, payload } = this.props.item;
+ // type could be undefined for sse channel.
+ const typeLabel = type ? L10N.getStr(`netmonitor.ws.type.${type}`) : null;
+
+ // If payload is a LongStringActor object, we show the first 1000 characters
+ const displayedPayload = payload.initial ? payload.initial : payload;
+
+ const frameTypeImg = type
+ ? dom.img({
+ alt: typeLabel,
+ className: `message-list-type-icon message-list-type-icon-${type}`,
+ src: `chrome://devtools/content/netmonitor/src/assets/icons/arrow-up.svg`,
+ })
+ : null;
+
+ let title = limitTooltipLength(displayedPayload);
+ title = type ? typeLabel + " " + title : title;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-payload",
+ title,
+ },
+ frameTypeImg,
+ " " + displayedPayload
+ );
+ }
+}
+
+module.exports = ColumnData;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnEventName.js b/devtools/client/netmonitor/src/components/messages/ColumnEventName.js
new file mode 100644
index 0000000000..812de4d40c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnEventName.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "EventName" column of a message.
+ */
+class ColumnEventName extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.eventName !== nextProps.item.eventName;
+ }
+
+ render() {
+ const { eventName } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-eventName",
+ title: eventName,
+ },
+ eventName
+ );
+ }
+}
+
+module.exports = ColumnEventName;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js b/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js
new file mode 100644
index 0000000000..8f9a1d9e0b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnFinBit.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "FinBit" column of a message.
+ */
+class ColumnFinBit extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.finBit !== nextProps.item.finBit;
+ }
+
+ render() {
+ const { finBit } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-finBit",
+ title: finBit.toString(),
+ },
+ finBit.toString()
+ );
+ }
+}
+
+module.exports = ColumnFinBit;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js b/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js
new file mode 100644
index 0000000000..2c5a65313a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "LastEventId" column of a message.
+ */
+class ColumnLastEventId extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.lastEventId !== nextProps.item.lastEventId;
+ }
+
+ render() {
+ const { lastEventId } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-lastEventId",
+ title: lastEventId,
+ },
+ lastEventId
+ );
+ }
+}
+
+module.exports = ColumnLastEventId;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js b/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js
new file mode 100644
index 0000000000..20330ebc92
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "MaskBit" column of a message.
+ */
+class ColumnMaskBit extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.maskBit !== nextProps.item.maskBit;
+ }
+
+ render() {
+ const { maskBit } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-maskBit",
+ title: maskBit.toString(),
+ },
+ maskBit.toString()
+ );
+ }
+}
+
+module.exports = ColumnMaskBit;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js b/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js
new file mode 100644
index 0000000000..2fcdc85ed0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnOpCode.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "OpCode" column of a message.
+ */
+class ColumnOpCode extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.opCode !== nextProps.item.opCode;
+ }
+
+ render() {
+ const { opCode } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-opCode",
+ title: opCode,
+ },
+ opCode
+ );
+ }
+}
+
+module.exports = ColumnOpCode;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnRetry.js b/devtools/client/netmonitor/src/components/messages/ColumnRetry.js
new file mode 100644
index 0000000000..e1fb63d706
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnRetry.js
@@ -0,0 +1,40 @@
+/* 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");
+
+/**
+ * Renders the "Retry" column of a message.
+ */
+class ColumnRetry extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.retry !== nextProps.item.retry;
+ }
+
+ render() {
+ const { retry } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-retry",
+ title: retry,
+ },
+ retry
+ );
+ }
+}
+
+module.exports = ColumnRetry;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnSize.js b/devtools/client/netmonitor/src/components/messages/ColumnSize.js
new file mode 100644
index 0000000000..4f00e1a521
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnSize.js
@@ -0,0 +1,43 @@
+/* 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 {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+/**
+ * Renders the "Size" column of a message.
+ */
+class ColumnSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.payload !== nextProps.item.payload;
+ }
+
+ render() {
+ const { payload } = this.props.item;
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-size",
+ title: getFormattedSize(payload.length),
+ },
+ getFormattedSize(payload.length)
+ );
+ }
+}
+
+module.exports = ColumnSize;
diff --git a/devtools/client/netmonitor/src/components/messages/ColumnTime.js b/devtools/client/netmonitor/src/components/messages/ColumnTime.js
new file mode 100644
index 0000000000..594a6b705b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/ColumnTime.js
@@ -0,0 +1,56 @@
+/* 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");
+
+/**
+ * Renders the "Time" column of a message.
+ */
+class ColumnTime extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.item.type !== nextProps.item.type ||
+ this.props.item.timeStamp !== nextProps.item.timeStamp
+ );
+ }
+
+ /**
+ * Format a DOMHighResTimeStamp (in microseconds) as HH:mm:ss.SSS
+ * @param {number} highResTimeStamp
+ */
+ formatTime(highResTimeStamp) {
+ const date = new Date(highResTimeStamp / 1000);
+ const hh = date.getHours().toString().padStart(2, "0");
+ const mm = date.getMinutes().toString().padStart(2, "0");
+ const ss = date.getSeconds().toString().padStart(2, "0");
+ const mmm = date.getMilliseconds().toString().padStart(3, "0");
+ return `${hh}:${mm}:${ss}.${mmm}`;
+ }
+
+ render() {
+ const label = this.formatTime(this.props.item.timeStamp);
+
+ return dom.td(
+ {
+ className: "message-list-column message-list-time",
+ title: label,
+ },
+ label
+ );
+ }
+}
+
+module.exports = ColumnTime;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js b/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js
new file mode 100644
index 0000000000..b2cd2d346d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js
@@ -0,0 +1,122 @@
+/* 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 {
+ PureComponent,
+} = 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+// Menu
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+
+class MessageFilterMenu extends PureComponent {
+ static get propTypes() {
+ return {
+ messageFilterType: PropTypes.string.isRequired,
+ toggleMessageFilterType: PropTypes.func.isRequired,
+ // showControlFrames decides if control frames
+ // will be shown in messages panel
+ showControlFrames: PropTypes.bool.isRequired,
+ // toggleControlFrames toggles the value for showControlFrames
+ toggleControlFrames: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onShowFilterMenu = this.onShowFilterMenu.bind(this);
+ }
+
+ onShowFilterMenu(event) {
+ const {
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ } = this.props;
+
+ const menuItems = [
+ {
+ id: "message-list-context-filter-all",
+ label: L10N.getStr("netmonitor.ws.context.all"),
+ accesskey: L10N.getStr("netmonitor.ws.context.all.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "all",
+ click: () => {
+ toggleMessageFilterType("all");
+ },
+ },
+ {
+ id: "message-list-context-filter-sent",
+ label: L10N.getStr("netmonitor.ws.context.sent"),
+ accesskey: L10N.getStr("netmonitor.ws.context.sent.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "sent",
+ click: () => {
+ toggleMessageFilterType("sent");
+ },
+ },
+ {
+ id: "message-list-context-filter-received",
+ label: L10N.getStr("netmonitor.ws.context.received"),
+ accesskey: L10N.getStr("netmonitor.ws.context.received.accesskey"),
+ type: "checkbox",
+ checked: messageFilterType === "received",
+ click: () => {
+ toggleMessageFilterType("received");
+ },
+ },
+ {
+ type: "separator",
+ },
+ {
+ id: "message-list-context-filter-controlFrames",
+ label: L10N.getStr("netmonitor.ws.context.controlFrames"),
+ accesskey: L10N.getStr("netmonitor.ws.context.controlFrames.accesskey"),
+ type: "checkbox",
+ checked: showControlFrames,
+ click: () => {
+ toggleControlFrames();
+ },
+ },
+ ];
+
+ showMenu(menuItems, { button: event.target });
+ }
+
+ render() {
+ const { messageFilterType, showControlFrames } = this.props;
+ const messageFilterTypeTitle = L10N.getStr(
+ `netmonitor.ws.context.${messageFilterType}`
+ );
+ const title =
+ messageFilterTypeTitle +
+ (showControlFrames
+ ? " (" + L10N.getStr(`netmonitor.ws.context.controlFrames`) + ")"
+ : "");
+
+ return dom.button(
+ {
+ id: "frame-filter-menu",
+ className: "devtools-button devtools-dropdown-button",
+ title,
+ onClick: this.onShowFilterMenu,
+ },
+ dom.span({ className: "title" }, title)
+ );
+ }
+}
+
+module.exports = MessageFilterMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListContent.js b/devtools/client/netmonitor/src/components/messages/MessageListContent.js
new file mode 100644
index 0000000000..f4377911af
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListContent.js
@@ -0,0 +1,398 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ getDisplayedMessages,
+ isCurrentChannelClosed,
+ getClosedConnectionDetails,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { table, tbody, tr, td, div, input, label, hr, p } = dom;
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const MESSAGES_EMPTY_TEXT = L10N.getStr("messagesEmptyText");
+const TOGGLE_MESSAGES_TRUNCATION = L10N.getStr("toggleMessagesTruncation");
+const TOGGLE_MESSAGES_TRUNCATION_TITLE = L10N.getStr(
+ "toggleMessagesTruncation.title"
+);
+const CONNECTION_CLOSED_TEXT = L10N.getStr("netmonitor.ws.connection.closed");
+const {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+const {
+ getSelectedMessage,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const MessageListContextMenu = require("resource://devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js");
+loader.lazyGetter(this, "MessageListHeader", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListHeader.js")
+ );
+});
+loader.lazyGetter(this, "MessageListItem", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListItem.js")
+ );
+});
+
+const LEFT_MOUSE_BUTTON = 0;
+
+/**
+ * Renders the actual contents of the message list.
+ */
+class MessageListContent extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ startPanelContainer: PropTypes.object,
+ messages: PropTypes.array,
+ selectedMessage: PropTypes.object,
+ selectMessage: PropTypes.func.isRequired,
+ columns: PropTypes.object.isRequired,
+ isClosed: PropTypes.bool.isRequired,
+ closedConnectionDetails: PropTypes.object,
+ channelId: PropTypes.number,
+ onSelectMessageDelta: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.messagesLimit = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.displayed-messages.limit"
+ );
+ this.currentTruncatedNum = 0;
+ this.state = {
+ checked: false,
+ };
+ this.pinnedToBottom = false;
+ this.initIntersectionObserver = false;
+ this.intersectionObserver = null;
+ this.toggleTruncationCheckBox = this.toggleTruncationCheckBox.bind(this);
+ }
+
+ componentDidMount() {
+ const { startPanelContainer } = this.props;
+ const { scrollAnchor } = this.refs;
+
+ if (scrollAnchor) {
+ // Always scroll to anchor when MessageListContent component first mounts.
+ scrollAnchor.scrollIntoView();
+ }
+ this.setupScrollToBottom(startPanelContainer, scrollAnchor);
+ }
+
+ componentDidUpdate(prevProps) {
+ const { startPanelContainer, channelId } = this.props;
+ const { scrollAnchor } = this.refs;
+
+ // When messages are cleared, the previous scrollAnchor would be destroyed, so we need to reset this boolean.
+ if (!scrollAnchor) {
+ this.initIntersectionObserver = false;
+ }
+
+ // In addition to that, we need to reset currentTruncatedNum
+ if (prevProps.messages.length && this.props.messages.length === 0) {
+ this.currentTruncatedNum = 0;
+ }
+
+ // If a new connection is selected, scroll to anchor.
+ if (channelId !== prevProps.channelId && scrollAnchor) {
+ scrollAnchor.scrollIntoView();
+ }
+
+ // Do not autoscroll if the selection changed. This would cause
+ // the newly selected message to jump just after clicking in.
+ // (not user friendly)
+ //
+ // If the selection changed, we need to ensure that the newly
+ // selected message is properly scrolled into the visible area.
+ if (prevProps.selectedMessage === this.props.selectedMessage) {
+ this.setupScrollToBottom(startPanelContainer, scrollAnchor);
+ } else {
+ const head = document.querySelector("thead.message-list-headers-group");
+ const selectedRow = document.querySelector(
+ "tr.message-list-item.selected"
+ );
+
+ if (selectedRow) {
+ const rowRect = selectedRow.getBoundingClientRect();
+ const scrollableRect = startPanelContainer.getBoundingClientRect();
+ const headRect = head.getBoundingClientRect();
+
+ if (rowRect.top <= scrollableRect.top) {
+ selectedRow.scrollIntoView(true);
+
+ // We need to scroll a bit more to get the row out
+ // of the header. The header is sticky and overlaps
+ // part of the scrollable area.
+ startPanelContainer.scrollTop -= headRect.height;
+ } else if (rowRect.bottom > scrollableRect.bottom) {
+ selectedRow.scrollIntoView(false);
+ }
+ }
+ }
+ }
+
+ componentWillUnmount() {
+ // Reset observables and boolean values.
+ const { scrollAnchor } = this.refs;
+
+ if (this.intersectionObserver) {
+ if (scrollAnchor) {
+ this.intersectionObserver.unobserve(scrollAnchor);
+ }
+ this.initIntersectionObserver = false;
+ this.pinnedToBottom = false;
+ }
+ }
+
+ setupScrollToBottom(startPanelContainer, scrollAnchor) {
+ if (startPanelContainer && scrollAnchor) {
+ // Initialize intersection observer.
+ if (!this.initIntersectionObserver) {
+ this.intersectionObserver = new IntersectionObserver(
+ () => {
+ // When scrollAnchor first comes into view, this.pinnedToBottom is set to true.
+ // When the anchor goes out of view, this callback function triggers again and toggles this.pinnedToBottom.
+ // Subsequent scroll into/out of view will toggle this.pinnedToBottom.
+ this.pinnedToBottom = !this.pinnedToBottom;
+ },
+ {
+ root: startPanelContainer,
+ threshold: 0.1,
+ }
+ );
+ if (this.intersectionObserver) {
+ this.intersectionObserver.observe(scrollAnchor);
+ this.initIntersectionObserver = true;
+ }
+ }
+
+ if (this.pinnedToBottom) {
+ scrollAnchor.scrollIntoView();
+ }
+ }
+ }
+
+ toggleTruncationCheckBox() {
+ this.setState({
+ checked: !this.state.checked,
+ });
+ }
+
+ onMouseDown(evt, item) {
+ if (evt.button === LEFT_MOUSE_BUTTON) {
+ this.props.selectMessage(item);
+ }
+ }
+
+ onContextMenu(evt, item) {
+ evt.preventDefault();
+ const { connector } = this.props;
+ this.contextMenu = new MessageListContextMenu({
+ connector,
+ });
+ this.contextMenu.open(evt, item);
+ }
+
+ /**
+ * Handler for keyboard events. For arrow up/down, page up/down, home/end,
+ * move the selection up or down.
+ */
+ onKeyDown(evt) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ let delta;
+
+ switch (evt.key) {
+ case "ArrowUp":
+ delta = -1;
+ break;
+ case "ArrowDown":
+ delta = +1;
+ break;
+ case "PageUp":
+ delta = "PAGE_UP";
+ break;
+ case "PageDown":
+ delta = "PAGE_DOWN";
+ break;
+ case "Home":
+ delta = -Infinity;
+ break;
+ case "End":
+ delta = +Infinity;
+ break;
+ }
+
+ if (delta) {
+ this.props.onSelectMessageDelta(delta);
+ }
+ }
+
+ render() {
+ const {
+ messages,
+ selectedMessage,
+ connector,
+ columns,
+ isClosed,
+ closedConnectionDetails,
+ } = this.props;
+
+ if (messages.length === 0) {
+ return div(
+ { className: "empty-notice message-list-empty-notice" },
+ MESSAGES_EMPTY_TEXT
+ );
+ }
+
+ const visibleColumns = MESSAGE_HEADERS.filter(
+ header => columns[header.name]
+ ).map(col => col.name);
+
+ let displayedMessages;
+ let MESSAGES_TRUNCATED;
+ const shouldTruncate = messages.length > this.messagesLimit;
+ if (shouldTruncate) {
+ // If the checkbox is checked, we display all messages after the currentTruncatedNum limit.
+ // If the checkbox is unchecked, we display all messages after the messagesLimit.
+ this.currentTruncatedNum = this.state.checked
+ ? this.currentTruncatedNum
+ : messages.length - this.messagesLimit;
+ displayedMessages = messages.slice(this.currentTruncatedNum);
+
+ MESSAGES_TRUNCATED = PluralForm.get(
+ this.currentTruncatedNum,
+ L10N.getStr("netmonitor.ws.truncated-messages.warning")
+ ).replace("#1", this.currentTruncatedNum);
+ } else {
+ displayedMessages = messages;
+ }
+
+ let connectionClosedMsg = CONNECTION_CLOSED_TEXT;
+ if (
+ closedConnectionDetails &&
+ closedConnectionDetails.code !== undefined &&
+ closedConnectionDetails.reason !== undefined
+ ) {
+ connectionClosedMsg += `: ${closedConnectionDetails.code} ${closedConnectionDetails.reason}`;
+ }
+ return div(
+ {},
+ table(
+ { className: "message-list-table" },
+ MessageListHeader(),
+ tbody(
+ {
+ className: "message-list-body",
+ onKeyDown: this.onKeyDown,
+ },
+ tr(
+ {
+ tabIndex: 0,
+ },
+ td(
+ {
+ className: "truncated-messages-cell",
+ colSpan: visibleColumns.length,
+ },
+ shouldTruncate &&
+ div(
+ {
+ className: "truncated-messages-header",
+ },
+ div(
+ {
+ className: "truncated-messages-container",
+ },
+ div({
+ className: "truncated-messages-warning-icon",
+ }),
+ div(
+ {
+ className: "truncated-message",
+ title: MESSAGES_TRUNCATED,
+ },
+ MESSAGES_TRUNCATED
+ )
+ ),
+ label(
+ {
+ className: "truncated-messages-checkbox-label",
+ title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
+ },
+ input({
+ type: "checkbox",
+ className: "truncation-checkbox",
+ title: TOGGLE_MESSAGES_TRUNCATION_TITLE,
+ checked: this.state.checked,
+ onChange: this.toggleTruncationCheckBox,
+ }),
+ TOGGLE_MESSAGES_TRUNCATION
+ )
+ )
+ )
+ ),
+ displayedMessages.map((item, index) =>
+ MessageListItem({
+ key: "message-list-item-" + index,
+ item,
+ index,
+ isSelected: item === selectedMessage,
+ onMouseDown: evt => this.onMouseDown(evt, item),
+ onContextMenu: evt => this.onContextMenu(evt, item),
+ connector,
+ visibleColumns,
+ })
+ )
+ )
+ ),
+ isClosed &&
+ p(
+ {
+ className: "msg-connection-closed-message",
+ },
+ connectionClosedMsg
+ ),
+ hr({
+ ref: "scrollAnchor",
+ className: "message-list-scroll-anchor",
+ })
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ selectedMessage: getSelectedMessage(state),
+ messages: getDisplayedMessages(state),
+ columns: state.messages.columns,
+ isClosed: isCurrentChannelClosed(state),
+ closedConnectionDetails: getClosedConnectionDetails(state),
+ }),
+ dispatch => ({
+ selectMessage: item => dispatch(Actions.selectMessage(item)),
+ onSelectMessageDelta: delta => dispatch(Actions.selectMessageDelta(delta)),
+ })
+)(MessageListContent);
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js b/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js
new file mode 100644
index 0000000000..a3169ab12c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js
@@ -0,0 +1,62 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "copyString",
+ "resource://devtools/shared/platform/clipboard.js",
+ true
+);
+const {
+ getMessagePayload,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class MessageListContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ /**
+ * Handle the context menu opening.
+ */
+ open(event = {}, item) {
+ const menuItems = [
+ {
+ id: `message-list-context-copy-message`,
+ label: L10N.getStr("netmonitor.ws.context.copyFrame"),
+ accesskey: L10N.getStr("netmonitor.ws.context.copyFrame.accesskey"),
+ click: () => this.copyMessagePayload(item),
+ },
+ ];
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+
+ /**
+ * Copy the full payload from the selected message.
+ */
+ copyMessagePayload(item) {
+ getMessagePayload(item.payload, this.props.connector.getLongString).then(
+ payload => {
+ copyString(payload);
+ }
+ );
+ }
+}
+
+module.exports = MessageListContextMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListHeader.js b/devtools/client/netmonitor/src/components/messages/MessageListHeader.js
new file mode 100644
index 0000000000..b3c49ac0eb
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListHeader.js
@@ -0,0 +1,121 @@
+/* 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 {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+// Components
+const MessageListHeaderContextMenu = require("resource://devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js");
+
+/**
+ * Renders the message list header.
+ */
+class MessageListHeader extends Component {
+ static get propTypes() {
+ return {
+ columns: PropTypes.object.isRequired,
+ toggleColumn: PropTypes.func.isRequired,
+ resetColumns: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ const { resetColumns, toggleColumn, columns } = this.props;
+
+ if (!this.contextMenu) {
+ this.contextMenu = new MessageListHeaderContextMenu({
+ toggleColumn,
+ resetColumns,
+ });
+ }
+ this.contextMenu.open(evt, columns);
+ }
+
+ /**
+ * Helper method to get visibleColumns.
+ */
+ getVisibleColumns() {
+ const { columns } = this.props;
+ return MESSAGE_HEADERS.filter(header => columns[header.name]);
+ }
+
+ /**
+ * Render one column header from the table headers.
+ */
+ renderColumn({ name, width = "10%" }) {
+ const label = L10N.getStr(`netmonitor.ws.toolbar.${name}`);
+
+ return dom.th(
+ {
+ key: name,
+ id: `message-list-${name}-header-box`,
+ className: `message-list-column message-list-${name}`,
+ scope: "col",
+ style: { width },
+ },
+ dom.button(
+ {
+ id: `message-list-${name}-button`,
+ className: `message-list-header-button`,
+ title: label,
+ },
+ dom.div({ className: "button-text" }, label),
+ dom.div({ className: "button-icon" })
+ )
+ );
+ }
+
+ /**
+ * Render all columns in the table header.
+ */
+ renderColumns() {
+ const visibleColumns = this.getVisibleColumns();
+ return visibleColumns.map(header => this.renderColumn(header));
+ }
+
+ render() {
+ return dom.thead(
+ { className: "message-list-headers-group" },
+ dom.tr(
+ {
+ className: "message-list-headers",
+ onContextMenu: this.onContextMenu,
+ },
+ this.renderColumns()
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ columns: state.messages.columns,
+ }),
+ dispatch => ({
+ toggleColumn: column => dispatch(Actions.toggleMessageColumn(column)),
+ resetColumns: () => dispatch(Actions.resetMessageColumns()),
+ })
+)(MessageListHeader);
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js b/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js
new file mode 100644
index 0000000000..edf99bd5ac
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js
@@ -0,0 +1,61 @@
+/* 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 {
+ showMenu,
+} = require("resource://devtools/client/shared/components/menu/utils.js");
+const {
+ MESSAGE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+class MessageListHeaderContextMenu {
+ constructor(props) {
+ this.props = props;
+ }
+
+ /**
+ * Handle the context menu opening.
+ */
+ open(event = {}, columns) {
+ const visibleColumns = Object.values(columns).filter(state => state);
+ const onlyOneColumn = visibleColumns.length === 1;
+
+ const columnsToShow = Object.keys(columns);
+ const menuItems = MESSAGE_HEADERS.filter(({ name }) =>
+ columnsToShow.includes(name)
+ ).map(({ name: column }) => {
+ const shown = columns[column];
+ const label = L10N.getStr(`netmonitor.ws.toolbar.${column}`);
+ return {
+ id: `message-list-header-${column}-toggle`,
+ label,
+ type: "checkbox",
+ checked: shown,
+ click: () => this.props.toggleColumn(column),
+ // We don't want to allow hiding the last visible column
+ disabled: onlyOneColumn && shown,
+ };
+ });
+ menuItems.push(
+ { type: "separator" },
+ {
+ id: "message-list-header-reset-columns",
+ label: L10N.getStr("netmonitor.ws.toolbar.resetColumns"),
+ click: () => this.props.resetColumns(),
+ }
+ );
+
+ showMenu(menuItems, {
+ screenX: event.screenX,
+ screenY: event.screenY,
+ });
+ }
+}
+
+module.exports = MessageListHeaderContextMenu;
diff --git a/devtools/client/netmonitor/src/components/messages/MessageListItem.js b/devtools/client/netmonitor/src/components/messages/MessageListItem.js
new file mode 100644
index 0000000000..a5d837a31b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessageListItem.js
@@ -0,0 +1,127 @@
+/* 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,
+ createFactory,
+} = 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");
+
+loader.lazyGetter(this, "ColumnData", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnData.js")
+ );
+});
+loader.lazyGetter(this, "ColumnEventName", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnEventName.js")
+ );
+});
+loader.lazyGetter(this, "ColumnFinBit", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnFinBit.js")
+ );
+});
+loader.lazyGetter(this, "ColumnLastEventId", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js")
+ );
+});
+loader.lazyGetter(this, "ColumnMaskBit", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js")
+ );
+});
+loader.lazyGetter(this, "ColumnOpCode", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnOpCode.js")
+ );
+});
+loader.lazyGetter(this, "ColumnRetry", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnRetry.js")
+ );
+});
+loader.lazyGetter(this, "ColumnSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnSize.js")
+ );
+});
+loader.lazyGetter(this, "ColumnTime", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/ColumnTime.js")
+ );
+});
+
+const COLUMN_COMPONENT_MAP = {
+ data: ColumnData,
+ eventName: ColumnEventName,
+ finBit: ColumnFinBit,
+ lastEventId: ColumnLastEventId,
+ maskBit: ColumnMaskBit,
+ opCode: ColumnOpCode,
+ retry: ColumnRetry,
+ size: ColumnSize,
+ time: ColumnTime,
+};
+
+/**
+ * Renders one row in the list.
+ */
+class MessageListItem extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ index: PropTypes.number.isRequired,
+ isSelected: PropTypes.bool.isRequired,
+ onMouseDown: PropTypes.func.isRequired,
+ onContextMenu: PropTypes.func.isRequired,
+ connector: PropTypes.object.isRequired,
+ visibleColumns: PropTypes.array.isRequired,
+ };
+ }
+
+ render() {
+ const {
+ item,
+ index,
+ isSelected,
+ onMouseDown,
+ onContextMenu,
+ connector,
+ visibleColumns,
+ } = this.props;
+
+ const classList = [
+ "message-list-item",
+ index % 2 ? "odd" : "even",
+ item.type,
+ ];
+ if (isSelected) {
+ classList.push("selected");
+ }
+
+ return dom.tr(
+ {
+ className: classList.join(" "),
+ tabIndex: 0,
+ onMouseDown,
+ onContextMenu,
+ },
+ visibleColumns.map(name => {
+ const ColumnComponent = COLUMN_COMPONENT_MAP[name];
+ return ColumnComponent({
+ key: `message-list-column-${name}-${index}`,
+ connector,
+ item,
+ });
+ })
+ );
+ }
+}
+
+module.exports = MessageListItem;
diff --git a/devtools/client/netmonitor/src/components/messages/MessagePayload.js b/devtools/client/netmonitor/src/components/messages/MessagePayload.js
new file mode 100644
index 0000000000..b8d3f7ae33
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessagePayload.js
@@ -0,0 +1,403 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div, input, label, span, h2 } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getMessagePayload,
+ getResponseHeader,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const MESSAGE_DATA_LIMIT = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.messageDataLimit"
+);
+const MESSAGE_DATA_TRUNCATED = L10N.getStr("messageDataTruncated");
+const SocketIODecoder = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js");
+const {
+ JsonHubProtocol,
+ HandshakeProtocol,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js");
+const {
+ parseSockJS,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js");
+const {
+ parseStompJs,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js");
+const {
+ wampSerializers,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js");
+const {
+ getRequestByChannelId,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const RawData = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/RawData.js")
+);
+loader.lazyGetter(this, "PropertiesView", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+ );
+});
+
+const RAW_DATA = L10N.getStr("netmonitor.response.raw");
+
+/**
+ * Shows the full payload of a message.
+ * The payload is unwrapped from the LongStringActor object.
+ */
+class MessagePayload extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedMessage: PropTypes.object,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ payload: "",
+ isFormattedData: false,
+ formattedData: {},
+ formattedDataTitle: "",
+ rawDataDisplayed: false,
+ };
+
+ this.toggleRawData = this.toggleRawData.bind(this);
+ this.renderRawDataBtn = this.renderRawDataBtn.bind(this);
+ }
+
+ componentDidMount() {
+ this.updateMessagePayload();
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.selectedMessage !== prevProps.selectedMessage) {
+ this.updateMessagePayload();
+ }
+ }
+
+ updateMessagePayload() {
+ const { selectedMessage, connector } = this.props;
+
+ getMessagePayload(selectedMessage.payload, connector.getLongString).then(
+ async payload => {
+ const { formattedData, formattedDataTitle } = await this.parsePayload(
+ payload
+ );
+ this.setState({
+ payload,
+ isFormattedData: !!formattedData,
+ formattedData,
+ formattedDataTitle,
+ });
+ }
+ );
+ }
+
+ async parsePayload(payload) {
+ const { connector, selectedMessage, request } = this.props;
+
+ // Don't apply formatting to control frames
+ // Control frame check can be done using opCode as specified here:
+ // https://tools.ietf.org/html/rfc6455
+ const controlFrames = [0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf];
+ const isControlFrame = controlFrames.includes(selectedMessage.opCode);
+ if (isControlFrame) {
+ return {
+ formattedData: null,
+ formattedDataTitle: "",
+ };
+ }
+
+ // Make sure that request headers are fetched from the backend before
+ // looking for `Sec-WebSocket-Protocol` header.
+ const responseHeaders = await connector.requestData(
+ request.id,
+ "responseHeaders"
+ );
+
+ const wsProtocol = getResponseHeader(
+ { responseHeaders },
+ "Sec-WebSocket-Protocol"
+ );
+
+ const wampSerializer = wampSerializers[wsProtocol];
+ if (wampSerializer) {
+ const wampPayload = wampSerializer.deserializeMessage(payload);
+
+ return {
+ formattedData: wampPayload,
+ formattedDataTitle: wampSerializer.description,
+ };
+ }
+
+ // socket.io payload
+ const socketIOPayload = this.parseSocketIOPayload(payload);
+
+ if (socketIOPayload) {
+ return {
+ formattedData: socketIOPayload,
+ formattedDataTitle: "Socket.IO",
+ };
+ }
+ // sockjs payload
+ const sockJSPayload = parseSockJS(payload);
+ if (sockJSPayload) {
+ let formattedData = sockJSPayload.data;
+
+ if (sockJSPayload.type === "message") {
+ if (Array.isArray(formattedData)) {
+ formattedData = formattedData.map(
+ message => parseStompJs(message) || message
+ );
+ } else {
+ formattedData = parseStompJs(formattedData) || formattedData;
+ }
+ }
+
+ return {
+ formattedData,
+ formattedDataTitle: "SockJS",
+ };
+ }
+ // signalr payload
+ const signalRPayload = this.parseSignalR(payload);
+ if (signalRPayload) {
+ return {
+ formattedData: signalRPayload,
+ formattedDataTitle: "SignalR",
+ };
+ }
+ // STOMP
+ const stompPayload = parseStompJs(payload);
+ if (stompPayload) {
+ return {
+ formattedData: stompPayload,
+ formattedDataTitle: "STOMP",
+ };
+ }
+
+ // json payload
+ let { json } = parseJSON(payload);
+ if (json) {
+ const { data, identifier } = json;
+ // A json payload MAY be an "Action cable" if it
+ // contains either a `data` or an `identifier` property
+ // which are also json strings and would need to be parsed.
+ // See https://medium.com/codequest/actioncable-in-rails-api-f087b65c860d
+ if (
+ (data && typeof data == "string") ||
+ (identifier && typeof identifier == "string")
+ ) {
+ const actionCablePayload = this.parseActionCable(json);
+ return {
+ formattedData: actionCablePayload,
+ formattedDataTitle: "Action Cable",
+ };
+ }
+
+ if (Array.isArray(json)) {
+ json = json.map(message => parseStompJs(message) || message);
+ }
+
+ return {
+ formattedData: json,
+ formattedDataTitle: "JSON",
+ };
+ }
+ return {
+ formattedData: null,
+ formattedDataTitle: "",
+ };
+ }
+
+ parseSocketIOPayload(payload) {
+ let result;
+ // Try decoding socket.io frames
+ try {
+ const decoder = new SocketIODecoder();
+ decoder.on("decoded", decodedPacket => {
+ if (
+ decodedPacket &&
+ !decodedPacket.data.includes("parser error") &&
+ decodedPacket.type
+ ) {
+ result = decodedPacket;
+ }
+ });
+ decoder.add(payload);
+ return result;
+ } catch (err) {
+ // Ignore errors
+ }
+ return null;
+ }
+
+ parseSignalR(payload) {
+ // attempt to parse as HandshakeResponseMessage
+ let decoder;
+ try {
+ decoder = new HandshakeProtocol();
+ const [remainingData, responseMessage] =
+ decoder.parseHandshakeResponse(payload);
+
+ if (responseMessage) {
+ return {
+ handshakeResponse: responseMessage,
+ remainingData: this.parseSignalR(remainingData),
+ };
+ }
+ } catch (err) {
+ // ignore errors;
+ }
+
+ // attempt to parse as JsonHubProtocolMessage
+ try {
+ decoder = new JsonHubProtocol();
+ const msgs = decoder.parseMessages(payload, null);
+ if (msgs?.length) {
+ return msgs;
+ }
+ } catch (err) {
+ // ignore errors;
+ }
+
+ // MVP Signalr
+ if (payload.endsWith("\u001e")) {
+ const { json } = parseJSON(payload.slice(0, -1));
+ if (json) {
+ return json;
+ }
+ }
+
+ return null;
+ }
+
+ parseActionCable(payload) {
+ const identifier = payload.identifier && parseJSON(payload.identifier).json;
+ const data = payload.data && parseJSON(payload.data).json;
+
+ if (identifier) {
+ payload.identifier = identifier;
+ }
+ if (data) {
+ payload.data = data;
+ }
+ return payload;
+ }
+
+ toggleRawData() {
+ this.setState({
+ rawDataDisplayed: !this.state.rawDataDisplayed,
+ });
+ }
+
+ renderRawDataBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawDataBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_DATA),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderData(component, componentProps) {
+ return component(componentProps);
+ }
+
+ render() {
+ let component;
+ let componentProps;
+ let dataLabel;
+ let { payload, rawDataDisplayed } = this.state;
+ let isTruncated = false;
+ if (this.state.payload.length >= MESSAGE_DATA_LIMIT) {
+ payload = payload.substring(0, MESSAGE_DATA_LIMIT);
+ isTruncated = true;
+ }
+
+ if (
+ !isTruncated &&
+ this.state.isFormattedData &&
+ !this.state.rawDataDisplayed
+ ) {
+ component = PropertiesView;
+ componentProps = {
+ object: this.state.formattedData,
+ };
+ dataLabel = this.state.formattedDataTitle;
+ } else {
+ component = RawData;
+ componentProps = { payload };
+ dataLabel = L10N.getFormatStrWithNumbers(
+ "netmonitor.ws.rawData.header",
+ getFormattedSize(this.state.payload.length)
+ );
+ }
+
+ return div(
+ {
+ className: "message-payload",
+ },
+ isTruncated &&
+ div(
+ {
+ className: "truncated-data-message",
+ },
+ MESSAGE_DATA_TRUNCATED
+ ),
+ h2({ className: "data-header", role: "heading" }, [
+ span({ key: "data-label", className: "data-label" }, dataLabel),
+ !isTruncated &&
+ this.state.isFormattedData &&
+ this.renderRawDataBtn("data", rawDataDisplayed, this.toggleRawData),
+ ]),
+ this.renderData(component, componentProps)
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ request: getRequestByChannelId(state, state.messages.currentChannelId),
+}))(MessagePayload);
diff --git a/devtools/client/netmonitor/src/components/messages/MessagesView.js b/devtools/client/netmonitor/src/components/messages/MessagesView.js
new file mode 100644
index 0000000000..898e28289d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/MessagesView.js
@@ -0,0 +1,173 @@
+/* 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,
+ createRef,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ findDOMNode,
+} = require("resource://devtools/client/shared/vendor/react-dom.js");
+const {
+ getSelectedMessage,
+ isSelectedMessageVisible,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+const SplitBox = createFactory(
+ require("resource://devtools/client/shared/components/splitter/SplitBox.js")
+);
+const MessageListContent = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageListContent.js")
+);
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/Toolbar.js")
+);
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/StatusBar.js")
+);
+
+loader.lazyGetter(this, "MessagePayload", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessagePayload.js")
+ );
+});
+
+/**
+ * Renders a list of messages in table view.
+ * Full payload is separated using a SplitBox.
+ */
+class MessagesView extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ selectedMessage: PropTypes.object,
+ messageDetailsOpen: PropTypes.bool.isRequired,
+ openMessageDetailsTab: PropTypes.func.isRequired,
+ selectedMessageVisible: PropTypes.bool.isRequired,
+ channelId: PropTypes.number,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.searchboxRef = createRef();
+ this.clearFilterText = this.clearFilterText.bind(this);
+ this.handleContainerElement = this.handleContainerElement.bind(this);
+ this.state = {
+ startPanelContainer: null,
+ };
+ }
+
+ componentDidUpdate(prevProps) {
+ const { channelId, openMessageDetailsTab, selectedMessageVisible } =
+ this.props;
+
+ // If a new connection is selected, clear the filter text
+ if (channelId !== prevProps.channelId) {
+ this.clearFilterText();
+ }
+
+ if (!selectedMessageVisible) {
+ openMessageDetailsTab(false);
+ }
+ }
+
+ componentWillUnmount() {
+ const { openMessageDetailsTab } = this.props;
+ openMessageDetailsTab(false);
+
+ const { clientHeight } = findDOMNode(this.refs.endPanel) || {};
+
+ if (clientHeight) {
+ Services.prefs.setIntPref(
+ "devtools.netmonitor.msg.payload-preview-height",
+ clientHeight
+ );
+ }
+ }
+
+ /* Store the parent DOM element of the SplitBox startPanel's element.
+ We need this element for as an option for the IntersectionObserver */
+ handleContainerElement(element) {
+ if (!this.state.startPanelContainer) {
+ this.setState({
+ startPanelContainer: element,
+ });
+ }
+ }
+
+ // Reset the filter text
+ clearFilterText() {
+ if (this.searchboxRef) {
+ this.searchboxRef.current.onClearButtonClick();
+ }
+ }
+
+ render() {
+ const { messageDetailsOpen, connector, selectedMessage, channelId } =
+ this.props;
+
+ const { searchboxRef } = this;
+ const { startPanelContainer } = this.state;
+
+ const initialHeight = Services.prefs.getIntPref(
+ "devtools.netmonitor.msg.payload-preview-height"
+ );
+
+ return div(
+ { id: "messages-view", className: "monitor-panel" },
+ Toolbar({
+ searchboxRef,
+ }),
+ SplitBox({
+ className: "devtools-responsive-container",
+ initialHeight,
+ minSize: "50px",
+ maxSize: "80%",
+ splitterSize: messageDetailsOpen ? 1 : 0,
+ onSelectContainerElement: this.handleContainerElement,
+ startPanel: MessageListContent({
+ connector,
+ startPanelContainer,
+ channelId,
+ }),
+ endPanel:
+ messageDetailsOpen &&
+ MessagePayload({
+ ref: "endPanel",
+ connector,
+ selectedMessage,
+ }),
+ endPanelCollapsed: !messageDetailsOpen,
+ endPanelControl: true,
+ vert: false,
+ }),
+ StatusBar()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ channelId: state.messages.currentChannelId,
+ messageDetailsOpen: state.messages.messageDetailsOpen,
+ selectedMessage: getSelectedMessage(state),
+ selectedMessageVisible: isSelectedMessageVisible(state),
+ }),
+ dispatch => ({
+ openMessageDetailsTab: open => dispatch(Actions.openMessageDetails(open)),
+ })
+)(MessagesView);
diff --git a/devtools/client/netmonitor/src/components/messages/RawData.js b/devtools/client/netmonitor/src/components/messages/RawData.js
new file mode 100644
index 0000000000..e0b49759c9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/RawData.js
@@ -0,0 +1,34 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+/**
+ * Shows raw data of a message.
+ */
+class RawData extends Component {
+ static get propTypes() {
+ return {
+ payload: PropTypes.string.isRequired,
+ };
+ }
+
+ render() {
+ const { payload } = this.props;
+ return dom.textarea({
+ className: "message-rawData-payload",
+ rows: payload.split(/\n/g).length + 1,
+ value: payload,
+ readOnly: true,
+ });
+ }
+}
+
+module.exports = RawData;
diff --git a/devtools/client/netmonitor/src/components/messages/StatusBar.js b/devtools/client/netmonitor/src/components/messages/StatusBar.js
new file mode 100644
index 0000000000..61bfc75e31
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/StatusBar.js
@@ -0,0 +1,130 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ getDisplayedMessagesSummary,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getFormattedSize,
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const {
+ CHANNEL_TYPE,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div, footer } = dom;
+
+const MESSAGE_COUNT_EMPTY = L10N.getStr(
+ "networkMenu.ws.summary.framesCountEmpty"
+);
+const TOOLTIP_MESSAGE_COUNT = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesCount"
+);
+const TOOLTIP_MESSAGE_TOTAL_SIZE = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesTotalSize"
+);
+const TOOLTIP_MESSAGE_TOTAL_TIME = L10N.getStr(
+ "networkMenu.ws.summary.tooltip.framesTotalTime"
+);
+
+const UPDATED_MSG_SUMMARY_PROPS = ["count", "totalMs", "totalSize"];
+
+/**
+ * Displays the summary of message count, total size and total time since the first message.
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ channelType: PropTypes.string,
+ summary: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const { summary, channelType } = this.props;
+ return (
+ channelType !== nextProps.channelType ||
+ !propertiesEqual(UPDATED_MSG_SUMMARY_PROPS, summary, nextProps.summary)
+ );
+ }
+
+ render() {
+ const { summary, channelType } = this.props;
+ const { count, totalMs, sentSize, receivedSize, totalSize } = summary;
+
+ const countText =
+ count === 0
+ ? MESSAGE_COUNT_EMPTY
+ : PluralForm.get(
+ count,
+ L10N.getStr("networkMenu.ws.summary.framesCount2")
+ ).replace("#1", count);
+ const totalSizeText = getFormattedSize(totalSize);
+ const sentSizeText = getFormattedSize(sentSize);
+ const receivedText = getFormattedSize(receivedSize);
+ const totalMillisText = getFormattedTime(totalMs);
+
+ // channelType might be null in which case it's better to just show
+ // total size than showing all three sizes.
+ const summaryText =
+ channelType === CHANNEL_TYPE.WEB_SOCKET
+ ? L10N.getFormatStr(
+ "networkMenu.ws.summary.label.framesTranferredSize",
+ totalSizeText,
+ sentSizeText,
+ receivedText
+ )
+ : `${totalSizeText} total`;
+
+ return footer(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ div(
+ {
+ className: "status-bar-label message-network-summary-count",
+ title: TOOLTIP_MESSAGE_COUNT,
+ },
+ countText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label message-network-summary-total-size",
+ title: TOOLTIP_MESSAGE_TOTAL_SIZE,
+ },
+ summaryText
+ ),
+ count !== 0 &&
+ div(
+ {
+ className: "status-bar-label message-network-summary-total-millis",
+ title: TOOLTIP_MESSAGE_TOTAL_TIME,
+ },
+ totalMillisText
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ channelType: state.messages.currentChannelType,
+ summary: getDisplayedMessagesSummary(state),
+}))(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/messages/Toolbar.js b/devtools/client/netmonitor/src/components/messages/Toolbar.js
new file mode 100644
index 0000000000..7b71c9aa06
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/Toolbar.js
@@ -0,0 +1,152 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ CHANNEL_TYPE,
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const { button, span, div } = dom;
+
+// Components
+const MessageFilterMenu = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+// Localization
+const MSG_TOOLBAR_CLEAR = L10N.getStr("netmonitor.ws.toolbar.clear");
+const MSG_SEARCH_KEY_SHORTCUT = L10N.getStr(
+ "netmonitor.ws.toolbar.filterFreetext.key"
+);
+const MSG_SEARCH_PLACE_HOLDER = L10N.getStr(
+ "netmonitor.ws.toolbar.filterFreetext.label"
+);
+
+/**
+ * MessagesPanel toolbar component.
+ *
+ * Toolbar contains a set of useful tools that clear the list of
+ * existing messages as well as filter content.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ searchboxRef: PropTypes.object.isRequired,
+ toggleMessageFilterType: PropTypes.func.isRequired,
+ toggleControlFrames: PropTypes.func.isRequired,
+ clearMessages: PropTypes.func.isRequired,
+ setMessageFilterText: PropTypes.func.isRequired,
+ messageFilterType: PropTypes.string.isRequired,
+ showControlFrames: PropTypes.bool.isRequired,
+ channelType: PropTypes.string,
+ };
+ }
+
+ componentWillUnmount() {
+ const { setMessageFilterText } = this.props;
+ setMessageFilterText("");
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Render a clear button.
+ */
+ renderClearButton(clearMessages) {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon message-list-clear-button",
+ title: MSG_TOOLBAR_CLEAR,
+ onClick: () => {
+ clearMessages();
+ },
+ });
+ }
+
+ /**
+ * Render the message filter menu button.
+ */
+ renderMessageFilterMenu() {
+ const {
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ } = this.props;
+
+ return MessageFilterMenu({
+ messageFilterType,
+ toggleMessageFilterType,
+ showControlFrames,
+ toggleControlFrames,
+ });
+ }
+
+ /**
+ * Render filter Searchbox.
+ */
+ renderFilterBox(setMessageFilterText) {
+ return SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ keyShortcut: MSG_SEARCH_KEY_SHORTCUT,
+ placeholder: MSG_SEARCH_PLACE_HOLDER,
+ type: "filter",
+ ref: this.props.searchboxRef,
+ onChange: setMessageFilterText,
+ });
+ }
+
+ render() {
+ const { clearMessages, setMessageFilterText, channelType } = this.props;
+ const isWs = channelType === CHANNEL_TYPE.WEB_SOCKET;
+ return div(
+ {
+ id: "netmonitor-toolbar-container",
+ className: "devtools-toolbar devtools-input-toolbar",
+ },
+ this.renderClearButton(clearMessages),
+ isWs ? this.renderSeparator() : null,
+ isWs ? this.renderMessageFilterMenu() : null,
+ this.renderSeparator(),
+ this.renderFilterBox(setMessageFilterText)
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ messageFilterType: state.messages.messageFilterType,
+ showControlFrames: state.messages.showControlFrames,
+ channelType: state.messages.currentChannelType,
+ }),
+ dispatch => ({
+ clearMessages: () => dispatch(Actions.clearMessages()),
+ toggleMessageFilterType: filter =>
+ dispatch(Actions.toggleMessageFilterType(filter)),
+ toggleControlFrames: () => dispatch(Actions.toggleControlFrames()),
+ setMessageFilterText: text => dispatch(Actions.setMessageFilterText(text)),
+ })
+)(Toolbar);
diff --git a/devtools/client/netmonitor/src/components/messages/cbor.js b/devtools/client/netmonitor/src/components/messages/cbor.js
new file mode 100644
index 0000000000..8b8b249391
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/cbor.js
@@ -0,0 +1,270 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2016 Patrick Gansterer <paroga@paroga.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+"use strict";
+const POW_2_24 = 5.960464477539063e-8;
+const POW_2_32 = 4294967296;
+
+function decode(data, tagger, simpleValue) {
+ const dataView = new DataView(data);
+ let offset = 0;
+
+ if (typeof tagger !== "function") {
+ tagger = function (value) {
+ return value;
+ };
+ }
+ if (typeof simpleValue !== "function") {
+ simpleValue = function () {
+ return undefined;
+ };
+ }
+
+ function commitRead(length, value) {
+ offset += length;
+ return value;
+ }
+ function readArrayBuffer(length) {
+ return commitRead(length, new Uint8Array(data, offset, length));
+ }
+ function readFloat16() {
+ const tempArrayBuffer = new ArrayBuffer(4);
+ const tempDataView = new DataView(tempArrayBuffer);
+ const value = readUint16();
+
+ const sign = value & 0x8000;
+ let exponent = value & 0x7c00;
+ const fraction = value & 0x03ff;
+
+ if (exponent === 0x7c00) {
+ exponent = 0xff << 10;
+ } else if (exponent !== 0) {
+ exponent += (127 - 15) << 10;
+ } else if (fraction !== 0) {
+ return (sign ? -1 : 1) * fraction * POW_2_24;
+ }
+
+ tempDataView.setUint32(
+ 0,
+ (sign << 16) | (exponent << 13) | (fraction << 13)
+ );
+ return tempDataView.getFloat32(0);
+ }
+ function readFloat32() {
+ return commitRead(4, dataView.getFloat32(offset));
+ }
+ function readFloat64() {
+ return commitRead(8, dataView.getFloat64(offset));
+ }
+ function readUint8() {
+ return commitRead(1, dataView.getUint8(offset));
+ }
+ function readUint16() {
+ return commitRead(2, dataView.getUint16(offset));
+ }
+ function readUint32() {
+ return commitRead(4, dataView.getUint32(offset));
+ }
+ function readUint64() {
+ return readUint32() * POW_2_32 + readUint32();
+ }
+ function readBreak() {
+ if (dataView.getUint8(offset) !== 0xff) {
+ return false;
+ }
+ offset += 1;
+ return true;
+ }
+ function readLength(additionalInformation) {
+ if (additionalInformation < 24) {
+ return additionalInformation;
+ }
+ if (additionalInformation === 24) {
+ return readUint8();
+ }
+ if (additionalInformation === 25) {
+ return readUint16();
+ }
+ if (additionalInformation === 26) {
+ return readUint32();
+ }
+ if (additionalInformation === 27) {
+ return readUint64();
+ }
+ if (additionalInformation === 31) {
+ return -1;
+ }
+ throw new Error("Invalid length encoding");
+ }
+ function readIndefiniteStringLength(majorType) {
+ const initialByte = readUint8();
+ if (initialByte === 0xff) {
+ return -1;
+ }
+ const length = readLength(initialByte & 0x1f);
+ if (length < 0 || initialByte >> 5 !== majorType) {
+ throw new Error("Invalid indefinite length element");
+ }
+ return length;
+ }
+
+ function appendUtf16Data(utf16data, length) {
+ for (let i = 0; i < length; ++i) {
+ let value = readUint8();
+ if (value & 0x80) {
+ if (value < 0xe0) {
+ value = ((value & 0x1f) << 6) | (readUint8() & 0x3f);
+ length -= 1;
+ } else if (value < 0xf0) {
+ value =
+ ((value & 0x0f) << 12) |
+ ((readUint8() & 0x3f) << 6) |
+ (readUint8() & 0x3f);
+ length -= 2;
+ } else {
+ value =
+ ((value & 0x0f) << 18) |
+ ((readUint8() & 0x3f) << 12) |
+ ((readUint8() & 0x3f) << 6) |
+ (readUint8() & 0x3f);
+ length -= 3;
+ }
+ }
+
+ if (value < 0x10000) {
+ utf16data.push(value);
+ } else {
+ value -= 0x10000;
+ utf16data.push(0xd800 | (value >> 10));
+ utf16data.push(0xdc00 | (value & 0x3ff));
+ }
+ }
+ }
+
+ // eslint-disable-next-line complexity
+ function decodeItem() {
+ const initialByte = readUint8();
+ const majorType = initialByte >> 5;
+ const additionalInformation = initialByte & 0x1f;
+ let i;
+ let length;
+
+ if (majorType === 7) {
+ switch (additionalInformation) {
+ case 25:
+ return readFloat16();
+ case 26:
+ return readFloat32();
+ case 27:
+ return readFloat64();
+ }
+ }
+
+ length = readLength(additionalInformation);
+ if (length < 0 && (majorType < 2 || majorType > 6)) {
+ throw new Error("Invalid length");
+ }
+
+ switch (majorType) {
+ case 0:
+ return length;
+ case 1:
+ return -1 - length;
+ case 2:
+ if (length < 0) {
+ const elements = [];
+ let fullArrayLength = 0;
+ while ((length = readIndefiniteStringLength(majorType)) >= 0) {
+ fullArrayLength += length;
+ elements.push(readArrayBuffer(length));
+ }
+ const fullArray = new Uint8Array(fullArrayLength);
+ let fullArrayOffset = 0;
+ for (i = 0; i < elements.length; ++i) {
+ fullArray.set(elements[i], fullArrayOffset);
+ fullArrayOffset += elements[i].length;
+ }
+ return fullArray;
+ }
+ return readArrayBuffer(length);
+ case 3:
+ const utf16data = [];
+ if (length < 0) {
+ while ((length = readIndefiniteStringLength(majorType)) >= 0) {
+ appendUtf16Data(utf16data, length);
+ }
+ } else {
+ appendUtf16Data(utf16data, length);
+ }
+ return String.fromCharCode.apply(null, utf16data);
+ case 4:
+ let retArray;
+ if (length < 0) {
+ retArray = [];
+ while (!readBreak()) {
+ retArray.push(decodeItem());
+ }
+ } else {
+ retArray = new Array(length);
+ for (i = 0; i < length; ++i) {
+ retArray[i] = decodeItem();
+ }
+ }
+ return retArray;
+ case 5:
+ const retObject = {};
+ for (i = 0; i < length || (length < 0 && !readBreak()); ++i) {
+ const key = decodeItem();
+ retObject[key] = decodeItem();
+ }
+ return retObject;
+ case 6:
+ return tagger(decodeItem(), length);
+ case 7:
+ switch (length) {
+ case 20:
+ return false;
+ case 21:
+ return true;
+ case 22:
+ return null;
+ case 23:
+ return undefined;
+ default:
+ return simpleValue(length);
+ }
+ }
+
+ throw new Error("Invalid major byte");
+ }
+
+ const ret = decodeItem();
+ if (offset !== data.byteLength) {
+ throw new Error("Remaining bytes");
+ }
+
+ return ret;
+}
+
+module.exports = { decode };
diff --git a/devtools/client/netmonitor/src/components/messages/moz.build b/devtools/client/netmonitor/src/components/messages/moz.build
new file mode 100644
index 0000000000..b5b8751d30
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/moz.build
@@ -0,0 +1,32 @@
+# 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/.
+
+DIRS += [
+ "parsers",
+]
+
+DevToolsModules(
+ "cbor.js",
+ "ColumnData.js",
+ "ColumnEventName.js",
+ "ColumnFinBit.js",
+ "ColumnLastEventId.js",
+ "ColumnMaskBit.js",
+ "ColumnOpCode.js",
+ "ColumnRetry.js",
+ "ColumnSize.js",
+ "ColumnTime.js",
+ "MessageFilterMenu.js",
+ "MessageListContent.js",
+ "MessageListContextMenu.js",
+ "MessageListHeader.js",
+ "MessageListHeaderContextMenu.js",
+ "MessageListItem.js",
+ "MessagePayload.js",
+ "MessagesView.js",
+ "msgpack.js",
+ "RawData.js",
+ "StatusBar.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/msgpack.js b/devtools/client/netmonitor/src/components/messages/msgpack.js
new file mode 100644
index 0000000000..e54e2707e9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/msgpack.js
@@ -0,0 +1,365 @@
+// Copyright © 2019, Yves Goergen, https://unclassified.software/source/msgpack-js
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+// associated documentation files (the “Software”), to deal in the Software without restriction,
+// including without limitation the rights to use, copy, modify, merge, publish, distribute,
+// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all copies or
+// substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"use strict";
+
+// Deserializes a MessagePack byte array to a value.
+//
+// array: The MessagePack byte array to deserialize. This must be an Array or Uint8Array containing bytes, not a string.
+function deserialize(array) {
+ const pow32 = 0x100000000; // 2^32
+ let pos = 0;
+ if (array instanceof ArrayBuffer) {
+ array = new Uint8Array(array);
+ }
+ if (typeof array !== "object" || typeof array.length === "undefined") {
+ throw new Error(
+ "Invalid argument type: Expected a byte array (Array or Uint8Array) to deserialize."
+ );
+ }
+ if (!array.length) {
+ throw new Error(
+ "Invalid argument: The byte array to deserialize is empty."
+ );
+ }
+ if (!(array instanceof Uint8Array)) {
+ array = new Uint8Array(array);
+ }
+ const data = read();
+ if (pos < array.length) {
+ // Junk data at the end
+ }
+ return data;
+
+ // eslint-disable-next-line complexity
+ function read() {
+ const byte = array[pos++];
+ if (byte >= 0x00 && byte <= 0x7f) {
+ return byte;
+ } // positive fixint
+ if (byte >= 0x80 && byte <= 0x8f) {
+ return readMap(byte - 0x80);
+ } // fixmap
+ if (byte >= 0x90 && byte <= 0x9f) {
+ return readArray(byte - 0x90);
+ } // fixarray
+ if (byte >= 0xa0 && byte <= 0xbf) {
+ return readStr(byte - 0xa0);
+ } // fixstr
+ if (byte === 0xc0) {
+ return null;
+ } // nil
+ if (byte === 0xc1) {
+ throw new Error("Invalid byte code 0xc1 found.");
+ } // never used
+ if (byte === 0xc2) {
+ return false;
+ } // false
+ if (byte === 0xc3) {
+ return true;
+ } // true
+ if (byte === 0xc4) {
+ return readBin(-1, 1);
+ } // bin 8
+ if (byte === 0xc5) {
+ return readBin(-1, 2);
+ } // bin 16
+ if (byte === 0xc6) {
+ return readBin(-1, 4);
+ } // bin 32
+ if (byte === 0xc7) {
+ return readExt(-1, 1);
+ } // ext 8
+ if (byte === 0xc8) {
+ return readExt(-1, 2);
+ } // ext 16
+ if (byte === 0xc9) {
+ return readExt(-1, 4);
+ } // ext 32
+ if (byte === 0xca) {
+ return readFloat(4);
+ } // float 32
+ if (byte === 0xcb) {
+ return readFloat(8);
+ } // float 64
+ if (byte === 0xcc) {
+ return readUInt(1);
+ } // uint 8
+ if (byte === 0xcd) {
+ return readUInt(2);
+ } // uint 16
+ if (byte === 0xce) {
+ return readUInt(4);
+ } // uint 32
+ if (byte === 0xcf) {
+ return readUInt(8);
+ } // uint 64
+ if (byte === 0xd0) {
+ return readInt(1);
+ } // int 8
+ if (byte === 0xd1) {
+ return readInt(2);
+ } // int 16
+ if (byte === 0xd2) {
+ return readInt(4);
+ } // int 32
+ if (byte === 0xd3) {
+ return readInt(8);
+ } // int 64
+ if (byte === 0xd4) {
+ return readExt(1);
+ } // fixext 1
+ if (byte === 0xd5) {
+ return readExt(2);
+ } // fixext 2
+ if (byte === 0xd6) {
+ return readExt(4);
+ } // fixext 4
+ if (byte === 0xd7) {
+ return readExt(8);
+ } // fixext 8
+ if (byte === 0xd8) {
+ return readExt(16);
+ } // fixext 16
+ if (byte === 0xd9) {
+ return readStr(-1, 1);
+ } // str 8
+ if (byte === 0xda) {
+ return readStr(-1, 2);
+ } // str 16
+ if (byte === 0xdb) {
+ return readStr(-1, 4);
+ } // str 32
+ if (byte === 0xdc) {
+ return readArray(-1, 2);
+ } // array 16
+ if (byte === 0xdd) {
+ return readArray(-1, 4);
+ } // array 32
+ if (byte === 0xde) {
+ return readMap(-1, 2);
+ } // map 16
+ if (byte === 0xdf) {
+ return readMap(-1, 4);
+ } // map 32
+ if (byte >= 0xe0 && byte <= 0xff) {
+ return byte - 256;
+ } // negative fixint
+ console.debug("msgpack array:", array);
+ throw new Error(
+ "Invalid byte value '" +
+ byte +
+ "' at index " +
+ (pos - 1) +
+ " in the MessagePack binary data (length " +
+ array.length +
+ "): Expecting a range of 0 to 255. This is not a byte array."
+ );
+ }
+
+ function readInt(size) {
+ let value = 0;
+ let first = true;
+ while (size-- > 0) {
+ if (first) {
+ const byte = array[pos++];
+ value += byte & 0x7f;
+ if (byte & 0x80) {
+ value -= 0x80; // Treat most-significant bit as -2^i instead of 2^i
+ }
+ first = false;
+ } else {
+ value *= 256;
+ value += array[pos++];
+ }
+ }
+ return value;
+ }
+
+ function readUInt(size) {
+ let value = 0;
+ while (size-- > 0) {
+ value *= 256;
+ value += array[pos++];
+ }
+ return value;
+ }
+
+ function readFloat(size) {
+ const view = new DataView(array.buffer, pos, size);
+ pos += size;
+ if (size === 4) {
+ return view.getFloat32(0, false);
+ }
+ if (size === 8) {
+ return view.getFloat64(0, false);
+ }
+ throw new Error("Invalid size for readFloat.");
+ }
+
+ function readBin(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = array.subarray(pos, pos + size);
+ pos += size;
+ return readData;
+ }
+
+ function readMap(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = {};
+ while (size-- > 0) {
+ const key = read();
+ readData[key] = read();
+ }
+ return readData;
+ }
+
+ function readArray(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const readData = [];
+ while (size-- > 0) {
+ readData.push(read());
+ }
+ return readData;
+ }
+
+ function readStr(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const start = pos;
+ pos += size;
+ return decodeUtf8(array, start, size);
+ }
+
+ function readExt(size, lengthSize) {
+ if (size < 0) {
+ size = readUInt(lengthSize);
+ }
+ const type = readUInt(1);
+ const readData = readBin(size);
+ switch (type) {
+ case 255:
+ return readExtDate(readData);
+ }
+ return { type, data: readData };
+ }
+
+ function readExtDate(givenData) {
+ if (givenData.length === 4) {
+ const sec =
+ ((givenData[0] << 24) >>> 0) +
+ ((givenData[1] << 16) >>> 0) +
+ ((givenData[2] << 8) >>> 0) +
+ givenData[3];
+ return new Date(sec * 1000);
+ }
+ if (givenData.length === 8) {
+ const ns =
+ ((givenData[0] << 22) >>> 0) +
+ ((givenData[1] << 14) >>> 0) +
+ ((givenData[2] << 6) >>> 0) +
+ (givenData[3] >>> 2);
+ const sec =
+ (givenData[3] & 0x3) * pow32 +
+ ((givenData[4] << 24) >>> 0) +
+ ((givenData[5] << 16) >>> 0) +
+ ((givenData[6] << 8) >>> 0) +
+ givenData[7];
+ return new Date(sec * 1000 + ns / 1000000);
+ }
+ if (givenData.length === 12) {
+ const ns =
+ ((givenData[0] << 24) >>> 0) +
+ ((givenData[1] << 16) >>> 0) +
+ ((givenData[2] << 8) >>> 0) +
+ givenData[3];
+ pos -= 8;
+ const sec = readInt(8);
+ return new Date(sec * 1000 + ns / 1000000);
+ }
+ throw new Error("Invalid givenData length for a date value.");
+ }
+}
+
+// Decodes a string from UTF-8 bytes.
+function decodeUtf8(bytes, start, length) {
+ // Based on: https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330
+ let i = start,
+ str = "";
+ length += start;
+ while (i < length) {
+ let c = bytes[i++];
+ if (c > 127) {
+ if (c > 191 && c < 224) {
+ if (i >= length) {
+ throw new Error("UTF-8 decode: incomplete 2-byte sequence");
+ }
+ c = ((c & 31) << 6) | (bytes[i++] & 63);
+ } else if (c > 223 && c < 240) {
+ if (i + 1 >= length) {
+ throw new Error("UTF-8 decode: incomplete 3-byte sequence");
+ }
+ c = ((c & 15) << 12) | ((bytes[i++] & 63) << 6) | (bytes[i++] & 63);
+ } else if (c > 239 && c < 248) {
+ if (i + 2 >= length) {
+ throw new Error("UTF-8 decode: incomplete 4-byte sequence");
+ }
+ c =
+ ((c & 7) << 18) |
+ ((bytes[i++] & 63) << 12) |
+ ((bytes[i++] & 63) << 6) |
+ (bytes[i++] & 63);
+ } else {
+ throw new Error(
+ "UTF-8 decode: unknown multibyte start 0x" +
+ c.toString(16) +
+ " at index " +
+ (i - 1)
+ );
+ }
+ }
+ if (c <= 0xffff) {
+ str += String.fromCharCode(c);
+ } else if (c <= 0x10ffff) {
+ c -= 0x10000;
+ str += String.fromCharCode((c >> 10) | 0xd800);
+ str += String.fromCharCode((c & 0x3ff) | 0xdc00);
+ } else {
+ throw new Error(
+ "UTF-8 decode: code point 0x" + c.toString(16) + " exceeds UTF-16 reach"
+ );
+ }
+ }
+ return str;
+}
+
+// The exported functions
+const msgpack = {
+ deserialize,
+
+ // Compatibility with other libraries
+ decode: deserialize,
+};
+
+module.exports = msgpack;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
new file mode 100644
index 0000000000..6b1947e4a1
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/moz.build
@@ -0,0 +1,11 @@
+# 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/.
+
+DIRS += [
+ "socket-io",
+ "sockjs",
+ "stomp",
+ "signalr",
+ "wamp",
+]
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
new file mode 100644
index 0000000000..c1c64d6717
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js
@@ -0,0 +1,82 @@
+/*
+ * A helper class for working with SignalR handshakes.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+const Utils = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js");
+/** @private */
+class HandshakeProtocol {
+ // Handshake request is always JSON
+ writeHandshakeRequest(handshakeRequest) {
+ return TextMessageFormat.TextMessageFormat.write(
+ JSON.stringify(handshakeRequest)
+ );
+ }
+ parseHandshakeResponse(data) {
+ let messageData;
+ let remainingData;
+ if (
+ Utils.isArrayBuffer(data) ||
+ // eslint-disable-next-line no-undef
+ (typeof Buffer !== "undefined" && data instanceof Buffer)
+ ) {
+ // Format is binary but still need to read JSON text from handshake response
+ const binaryData = new Uint8Array(data);
+ const separatorIndex = binaryData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparatorCode
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = String.fromCharCode.apply(
+ null,
+ binaryData.slice(0, responseLength)
+ );
+ remainingData =
+ binaryData.byteLength > responseLength
+ ? binaryData.slice(responseLength).buffer
+ : null;
+ } else {
+ const textData = data;
+ const separatorIndex = textData.indexOf(
+ TextMessageFormat.TextMessageFormat.RecordSeparator
+ );
+ if (separatorIndex === -1) {
+ throw new Error("Message is incomplete.");
+ }
+ // content before separator is handshake response
+ // optional content after is additional messages
+ const responseLength = separatorIndex + 1;
+ messageData = textData.substring(0, responseLength);
+ remainingData =
+ textData.length > responseLength
+ ? textData.substring(responseLength)
+ : null;
+ }
+ // At this point we should have just the single handshake message
+ const messages = TextMessageFormat.TextMessageFormat.parse(messageData);
+ const response = JSON.parse(messages[0]);
+ if (response.type) {
+ throw new Error("Expected a handshake response from the server.");
+ }
+ const responseMessage = response;
+ // multiple messages could have arrived with handshake
+ // return additional data to be parsed as usual, or null if all parsed
+ return [remainingData, responseMessage];
+ }
+}
+exports.HandshakeProtocol = HandshakeProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
new file mode 100644
index 0000000000..fec2cdbff4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js
@@ -0,0 +1,33 @@
+/*
+ * A protocol abstraction for communicating with SignalR hubs.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+/** Defines the type of a Hub Message. */
+var MessageType;
+(function (_MessageType) {
+ /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
+ MessageType[(MessageType.Invocation = 1)] = "Invocation";
+ /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
+ MessageType[(MessageType.StreamItem = 2)] = "StreamItem";
+ /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
+ MessageType[(MessageType.Completion = 3)] = "Completion";
+ /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
+ MessageType[(MessageType.StreamInvocation = 4)] = "StreamInvocation";
+ /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
+ MessageType[(MessageType.CancelInvocation = 5)] = "CancelInvocation";
+ /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
+ MessageType[(MessageType.Ping = 6)] = "Ping";
+ /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
+ MessageType[(MessageType.Close = 7)] = "Close";
+})((MessageType = exports.MessageType || (exports.MessageType = {})));
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
new file mode 100644
index 0000000000..c3648e940f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js
@@ -0,0 +1,120 @@
+/*
+ * Implements the SignalR Hub Protocol.
+ *
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+const IHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js");
+const TextMessageFormat = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js");
+/** Implements the JSON Hub Protocol. */
+class JsonHubProtocol {
+ /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
+ *
+ * @param {string} input A string containing the serialized representation.
+ */
+ parseMessages(input) {
+ // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
+ if (typeof input !== "string") {
+ throw new Error(
+ "Invalid input for JSON hub protocol. Expected a string."
+ );
+ }
+ if (!input) {
+ return [];
+ }
+ // Parse the messages
+ const messages = TextMessageFormat.TextMessageFormat.parse(input);
+ const hubMessages = [];
+ for (const message of messages) {
+ const parsedMessage = JSON.parse(message);
+ if (typeof parsedMessage.type !== "number") {
+ throw new Error("Invalid payload.");
+ }
+ switch (parsedMessage.type) {
+ case IHubProtocol.MessageType.Invocation:
+ this.isInvocationMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.StreamItem:
+ this.isStreamItemMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Completion:
+ this.isCompletionMessage(parsedMessage);
+ break;
+ case IHubProtocol.MessageType.Ping:
+ // Single value, no need to validate
+ break;
+ case IHubProtocol.MessageType.Close:
+ // All optional values, no need to validate
+ break;
+ default:
+ // Future protocol changes can add message types, new kinds of messages
+ // will show up without having to update Firefox.
+ break;
+ }
+ // Map numeric message type to their textual name if it exists
+ parsedMessage.type =
+ IHubProtocol.MessageType[parsedMessage.type] || parsedMessage.type;
+ hubMessages.push(parsedMessage);
+ }
+ return hubMessages;
+ }
+ /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
+ *
+ * @param {HubMessage} message The message to write.
+ * @returns {string} A string containing the serialized representation of the message.
+ */
+ writeMessage(message) {
+ return TextMessageFormat.TextMessageFormat.write(JSON.stringify(message));
+ }
+ isInvocationMessage(message) {
+ this.assertNotEmptyString(
+ message.target,
+ "Invalid payload for Invocation message."
+ );
+ if (message.invocationId !== undefined) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Invocation message."
+ );
+ }
+ }
+ isStreamItemMessage(message) {
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for StreamItem message."
+ );
+ if (message.item === undefined) {
+ throw new Error("Invalid payload for StreamItem message.");
+ }
+ }
+ isCompletionMessage(message) {
+ if (message.result && message.error) {
+ throw new Error("Invalid payload for Completion message.");
+ }
+ if (!message.result && message.error) {
+ this.assertNotEmptyString(
+ message.error,
+ "Invalid payload for Completion message."
+ );
+ }
+ this.assertNotEmptyString(
+ message.invocationId,
+ "Invalid payload for Completion message."
+ );
+ }
+ assertNotEmptyString(value, errorMessage) {
+ if (typeof value !== "string" || value === "") {
+ throw new Error(errorMessage);
+ }
+ }
+}
+exports.JsonHubProtocol = JsonHubProtocol;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
new file mode 100644
index 0000000000..a9ec58ee36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Not exported from index
+/** @private */
+class TextMessageFormat {
+ static write(output) {
+ return `${output}${TextMessageFormat.RecordSeparator}`;
+ }
+ static parse(input) {
+ if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
+ throw new Error("Message is incomplete.");
+ }
+ const messages = input.split(TextMessageFormat.RecordSeparator);
+ messages.pop();
+ return messages;
+ }
+}
+exports.TextMessageFormat = TextMessageFormat;
+TextMessageFormat.RecordSeparatorCode = 0x1e;
+TextMessageFormat.RecordSeparator = String.fromCharCode(
+ TextMessageFormat.RecordSeparatorCode
+);
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
new file mode 100644
index 0000000000..77b00daf45
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) .NET Foundation. All rights reserved.
+ *
+ * This source code is licensed under the Apache License, Version 2.0,
+ * found in the LICENSE.txt file in the root directory of the library
+ * source tree.
+ *
+ * https://github.com/aspnet/AspNetCore
+ */
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// Also in signalr-protocol-msgpack/Utils.ts
+/** @private */
+function isArrayBuffer(val) {
+ return (
+ val &&
+ typeof ArrayBuffer !== "undefined" &&
+ (val instanceof ArrayBuffer ||
+ // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
+ (val.constructor && val.constructor.name === "ArrayBuffer"))
+ );
+}
+exports.isArrayBuffer = isArrayBuffer;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
new file mode 100644
index 0000000000..927b0a0922
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js
@@ -0,0 +1,13 @@
+/* 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 JsonHubProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js");
+const HandshakeProtocol = require("resource://devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js");
+
+module.exports = {
+ JsonHubProtocol: JsonHubProtocol.JsonHubProtocol,
+ HandshakeProtocol: HandshakeProtocol.HandshakeProtocol,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
new file mode 100644
index 0000000000..48329513f2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build
@@ -0,0 +1,12 @@
+# 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/.
+
+DevToolsModules(
+ "HandshakeProtocol.js",
+ "IHubProtocol.js",
+ "index.js",
+ "JSONHubProtocol.js",
+ "TextMessageFormat.js",
+ "Utils.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
new file mode 100644
index 0000000000..340791199f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js
@@ -0,0 +1,48 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+"use strict";
+
+/**
+ * Reconstructs a binary packet from its placeholder packet and buffers
+ *
+ * @param {Object} packet - event packet with placeholders
+ * @param {Array} buffers - binary buffers to put in placeholder positions
+ * @return {Object} reconstructed packet
+ * @api public
+ */
+
+exports.reconstructPacket = function (packet, buffers) {
+ packet.data = _reconstructPacket(packet.data, buffers);
+ packet.attachments = undefined; // no longer useful
+ return packet;
+};
+
+function _reconstructPacket(data, buffers) {
+ if (!data) {
+ return data;
+ }
+
+ if (data && data._placeholder) {
+ return buffers[data.num]; // appropriate buffer (should be natural order anyway)
+ } else if (Array.isArray(data)) {
+ for (let i = 0; i < data.length; i++) {
+ data[i] = _reconstructPacket(data[i], buffers);
+ }
+ } else if (typeof data === "object") {
+ for (const key in data) {
+ data[key] = _reconstructPacket(data[key], buffers);
+ }
+ }
+
+ return data;
+}
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
new file mode 100644
index 0000000000..5874778f75
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js
@@ -0,0 +1,84 @@
+/*
+ * Event emitter component.
+ *
+ * Copyright (c) 2014 Component contributors <dev@component.io>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/component/emitter
+ */
+
+"use strict";
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) {
+ return mixin(obj);
+ }
+}
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (const key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on = function (event, fn) {
+ this._callbacks = this._callbacks || {};
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function (event) {
+ this._callbacks = this._callbacks || {};
+
+ const args = new Array(arguments.length - 1);
+ let callbacks = this._callbacks["$" + event];
+
+ for (let i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (let i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+module.exports = Emitter;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
new file mode 100644
index 0000000000..9d631d014b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js
@@ -0,0 +1,292 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-unused-vars */
+
+"use strict";
+
+const Emitter = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js");
+const binary = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js");
+const isBuf = require("resource://devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js");
+
+/**
+ * Packet types
+ */
+
+const TYPES = [
+ "CONNECT",
+ "DISCONNECT",
+ "EVENT",
+ "ACK",
+ "ERROR",
+ "BINARY_EVENT",
+ "BINARY_ACK",
+];
+
+/**
+ * Packet type `connect`
+ */
+
+const CONNECT = 0;
+
+/**
+ * Packet type `disconnect`
+ */
+
+const DISCONNECT = 1;
+
+/**
+ * Packet type `event`
+ */
+
+const EVENT = 2;
+
+/**
+ * Packet type `ack`
+ */
+
+const ACK = 3;
+
+/**
+ * Packet type `error`
+ */
+
+const ERROR = 4;
+
+/**
+ * Packet type 'binary event'
+ */
+const BINARY_EVENT = 5;
+
+/**
+ * Packet type `binary ack`. For acks with binary arguments
+ */
+
+const BINARY_ACK = 6;
+
+/**
+ * A socket.io Decoder instance
+ *
+ * @return {Object} decoder
+ * @api public
+ */
+
+function Decoder() {
+ this.reconstructor = null;
+}
+
+/**
+ * Mix in `Emitter` with Decoder.
+ */
+
+Emitter(Decoder.prototype);
+
+/**
+ * A manager of a binary event's 'buffer sequence'. Should
+ * be constructed whenever a packet of type BINARY_EVENT is
+ * decoded.
+ *
+ * @param {Object} packet
+ * @return {BinaryReconstructor} initialized reconstructor
+ * @api private
+ */
+
+function BinaryReconstructor(packet) {
+ this.reconPack = packet;
+ this.buffers = [];
+}
+
+/**
+ * Method to be called when binary data received from connection
+ * after a BINARY_EVENT packet.
+ *
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
+ * @return {null | Object} returns null if more binary data is expected or
+ * a reconstructed packet object if all buffers have been received.
+ * @api private
+ */
+
+BinaryReconstructor.prototype.takeBinaryData = function (binData) {
+ this.buffers.push(binData);
+ if (this.buffers.length === this.reconPack.attachments) {
+ // done with buffer list
+ const packet = binary.reconstructPacket(this.reconPack, this.buffers);
+ this.finishedReconstruction();
+ return packet;
+ }
+ return null;
+};
+
+/**
+ * Cleans up binary packet reconstruction variables.
+ *
+ * @api private
+ */
+
+BinaryReconstructor.prototype.finishedReconstruction = function () {
+ this.reconPack = null;
+ this.buffers = [];
+};
+
+/**
+ * Decodes an encoded packet string into packet JSON.
+ *
+ * @param {String} obj - encoded packet
+ * @return {Object} packet
+ * @api public
+ */
+
+Decoder.prototype.add = function (obj) {
+ let packet;
+ if (typeof obj === "string") {
+ packet = decodeString(obj);
+ if (BINARY_EVENT === packet.type || BINARY_ACK === packet.type) {
+ // binary packet's json
+ this.reconstructor = new BinaryReconstructor(packet);
+
+ // no attachments, labeled binary but no binary data to follow
+ if (this.reconstructor.reconPack.attachments === 0) {
+ this.emit("decoded", packet);
+ }
+ } else {
+ // non-binary full packet
+ this.emit("decoded", packet);
+ }
+ } else if (isBuf(obj) || obj.base64) {
+ // raw binary data
+ if (!this.reconstructor) {
+ throw new Error("got binary data when not reconstructing a packet");
+ } else {
+ packet = this.reconstructor.takeBinaryData(obj);
+ if (packet) {
+ // received final buffer
+ this.reconstructor = null;
+ this.emit("decoded", packet);
+ }
+ }
+ } else {
+ throw new Error("Unknown type: " + obj);
+ }
+};
+
+/**
+ * Decode a packet String (JSON data)
+ *
+ * @param {String} str
+ * @return {Object} packet
+ * @api private
+ */
+// eslint-disable-next-line complexity
+function decodeString(str) {
+ let i = 0;
+ // look up type
+ const p = {
+ type: Number(str.charAt(0)),
+ };
+
+ if (TYPES[p.type] == null) {
+ return error("unknown packet type " + p.type);
+ }
+
+ // look up attachments if type binary
+ if (BINARY_EVENT === p.type || BINARY_ACK === p.type) {
+ let buf = "";
+ while (str.charAt(++i) !== "-") {
+ buf += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
+ throw new Error("Illegal attachments");
+ }
+ p.attachments = Number(buf);
+ }
+
+ // look up namespace (if any)
+ if (str.charAt(i + 1) === "/") {
+ p.nsp = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c === ",") {
+ break;
+ }
+ p.nsp += c;
+ if (i === str.length) {
+ break;
+ }
+ }
+ } else {
+ p.nsp = "/";
+ }
+
+ // look up id
+ const next = str.charAt(i + 1);
+ if (next !== "" && Number(next) == next) {
+ p.id = "";
+ while (++i) {
+ const c = str.charAt(i);
+ if (c == null || Number(c) != c) {
+ --i;
+ break;
+ }
+ p.id += str.charAt(i);
+ if (i === str.length) {
+ break;
+ }
+ }
+ p.id = Number(p.id);
+ }
+
+ // look up json data
+ if (str.charAt(++i)) {
+ const payload = tryParse(str.substr(i));
+ const isPayloadValid =
+ payload !== false && (p.type === ERROR || Array.isArray(payload));
+ if (isPayloadValid) {
+ p.data = payload;
+ } else {
+ return error("invalid payload");
+ }
+ }
+
+ return p;
+}
+
+function tryParse(str) {
+ try {
+ return JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+}
+
+/**
+ * Deallocates a parser's resources
+ *
+ * @api public
+ */
+
+Decoder.prototype.destroy = function () {
+ if (this.reconstructor) {
+ this.reconstructor.finishedReconstruction();
+ }
+};
+
+function error(msg) {
+ return {
+ type: ERROR,
+ data: "parser error: " + msg,
+ };
+}
+
+module.exports = Decoder;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
new file mode 100644
index 0000000000..cdbad14abc
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js
@@ -0,0 +1,40 @@
+/*
+ * A socket.io encoder and decoder written in JavaScript complying with version 4
+ * of socket.io-protocol. Used by socket.io and socket.io-client.
+ *
+ * Copyright (c) 2014 Guillermo Rauch <guillermo@learnboost.com>
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/socketio/socket.io-parser
+ */
+
+/* eslint-disable no-undef */
+
+"use strict";
+
+var withNativeBuffer =
+ typeof Buffer === "function" && typeof Buffer.isBuffer === "function";
+var withNativeArrayBuffer = typeof ArrayBuffer === "function";
+
+var isView = function (obj) {
+ return typeof ArrayBuffer.isView === "function"
+ ? ArrayBuffer.isView(obj)
+ : obj.buffer instanceof ArrayBuffer;
+};
+
+/**
+ * Returns true if obj is a buffer or an arraybuffer.
+ *
+ * @api private
+ */
+
+function isBuf(obj) {
+ return (
+ (withNativeBuffer && Buffer.isBuffer(obj)) ||
+ (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)))
+ );
+}
+
+module.exports = isBuf;
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
new file mode 100644
index 0000000000..d38ca19dd6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build
@@ -0,0 +1,10 @@
+# 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/.
+
+DevToolsModules(
+ "binary.js",
+ "component-emitter.js",
+ "index.js",
+ "is-buffer.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
new file mode 100644
index 0000000000..b688b84b36
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js
@@ -0,0 +1,56 @@
+/*
+ * SockJS is a browser JavaScript library that provides a WebSocket-like object.
+ * SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency,
+ * full duplex, cross-domain communication channel between the browser and the web server.
+ *
+ * Copyright (c) 2011-2018 The sockjs-client Authors.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of the library source tree.
+ *
+ * https://github.com/sockjs/sockjs-client
+ */
+
+"use strict";
+
+function parseSockJS(msg) {
+ const type = msg.slice(0, 1);
+ const content = msg.slice(1);
+
+ // first check for messages that don't need a payload
+ switch (type) {
+ case "o":
+ return { type: "open" };
+ case "h":
+ return { type: "heartbeat" };
+ }
+
+ let payload;
+ if (content) {
+ try {
+ payload = JSON.parse(content);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ if (typeof payload === "undefined") {
+ return null;
+ }
+
+ switch (type) {
+ case "a":
+ return { type: "message", data: payload };
+ case "m":
+ return { type: "message", data: payload };
+ case "c":
+ const [code, message] = payload;
+ return { type: "close", code, message };
+ default:
+ return null;
+ }
+}
+
+module.exports = {
+ parseSockJS,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
new file mode 100644
index 0000000000..e1ca52aa96
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build
@@ -0,0 +1,7 @@
+# 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/.
+
+DevToolsModules(
+ "index.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
new file mode 100644
index 0000000000..a55d5bff7a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/byte.ts
+ */
+
+"use strict";
+
+const BYTE = {
+ // LINEFEED byte (octet 10)
+ LF: "\x0A",
+ // NULL byte (octet 0)
+ NULL: "\x00",
+};
+
+module.exports = { BYTE };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
new file mode 100644
index 0000000000..679b1140b4
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/frame.ts
+ */
+
+"use strict";
+
+const {
+ BYTE,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js");
+
+/**
+ * Frame class represents a STOMP frame.
+ *
+ * @internal
+ */
+class FrameImpl {
+ /**
+ * Frame constructor. `command`, `headers` and `body` are available as properties.
+ *
+ * @internal
+ */
+ constructor(params) {
+ const {
+ command,
+ headers,
+ body,
+ binaryBody,
+ escapeHeaderValues,
+ skipContentLengthHeader,
+ } = params;
+ this.command = command;
+ this.headers = Object.assign({}, headers || {});
+ if (binaryBody) {
+ this._binaryBody = binaryBody;
+ this.isBinaryBody = true;
+ } else {
+ this._body = body || "";
+ this.isBinaryBody = false;
+ }
+ this.escapeHeaderValues = escapeHeaderValues || false;
+ this.skipContentLengthHeader = skipContentLengthHeader || false;
+ }
+ /**
+ * body of the frame
+ */
+ get body() {
+ if (!this._body && this.isBinaryBody) {
+ this._body = new TextDecoder().decode(this._binaryBody);
+ }
+ return this._body;
+ }
+ /**
+ * body as Uint8Array
+ */
+ get binaryBody() {
+ if (!this._binaryBody && !this.isBinaryBody) {
+ this._binaryBody = new TextEncoder().encode(this._body);
+ }
+ return this._binaryBody;
+ }
+ /**
+ * deserialize a STOMP Frame from raw data.
+ *
+ * @internal
+ */
+ static fromRawFrame(rawFrame, escapeHeaderValues) {
+ const headers = {};
+ const trim = str => str.replace(/^\s+|\s+$/g, "");
+ // In case of repeated headers, as per standards, first value need to be used
+ for (const header of rawFrame.headers.reverse()) {
+ const key = trim(header[0]);
+ let value = trim(header[1]);
+ if (
+ escapeHeaderValues &&
+ rawFrame.command !== "CONNECT" &&
+ rawFrame.command !== "CONNECTED"
+ ) {
+ value = FrameImpl.hdrValueUnEscape(value);
+ }
+ headers[key] = value;
+ }
+ return new FrameImpl({
+ command: rawFrame.command,
+ headers,
+ binaryBody: rawFrame.binaryBody,
+ escapeHeaderValues,
+ });
+ }
+ /**
+ * @internal
+ */
+ toString() {
+ return this.serializeCmdAndHeaders();
+ }
+ /**
+ * serialize this Frame in a format suitable to be passed to WebSocket.
+ * If the body is string the output will be string.
+ * If the body is binary (i.e. of type Unit8Array) it will be serialized to ArrayBuffer.
+ *
+ * @internal
+ */
+ serialize() {
+ const cmdAndHeaders = this.serializeCmdAndHeaders();
+ if (this.isBinaryBody) {
+ return FrameImpl.toUnit8Array(cmdAndHeaders, this._binaryBody).buffer;
+ }
+ return cmdAndHeaders + this._body + BYTE.NULL;
+ }
+ serializeCmdAndHeaders() {
+ const lines = [this.command];
+ if (this.skipContentLengthHeader) {
+ delete this.headers["content-length"];
+ }
+ for (const name of Object.keys(this.headers || {})) {
+ const value = this.headers[name];
+ if (
+ this.escapeHeaderValues &&
+ this.command !== "CONNECT" &&
+ this.command !== "CONNECTED"
+ ) {
+ lines.push(`${name}:${FrameImpl.hdrValueEscape(`${value}`)}`);
+ } else {
+ lines.push(`${name}:${value}`);
+ }
+ }
+ if (
+ this.isBinaryBody ||
+ (!this.isBodyEmpty() && !this.skipContentLengthHeader)
+ ) {
+ lines.push(`content-length:${this.bodyLength()}`);
+ }
+ return lines.join(BYTE.LF) + BYTE.LF + BYTE.LF;
+ }
+ isBodyEmpty() {
+ return this.bodyLength() === 0;
+ }
+ bodyLength() {
+ const binaryBody = this.binaryBody;
+ return binaryBody ? binaryBody.length : 0;
+ }
+ /**
+ * Compute the size of a UTF-8 string by counting its number of bytes
+ * (and not the number of characters composing the string)
+ */
+ static sizeOfUTF8(s) {
+ return s ? new TextEncoder().encode(s).length : 0;
+ }
+ static toUnit8Array(cmdAndHeaders, binaryBody) {
+ const uint8CmdAndHeaders = new TextEncoder().encode(cmdAndHeaders);
+ const nullTerminator = new Uint8Array([0]);
+ const uint8Frame = new Uint8Array(
+ uint8CmdAndHeaders.length + binaryBody.length + nullTerminator.length
+ );
+ uint8Frame.set(uint8CmdAndHeaders);
+ uint8Frame.set(binaryBody, uint8CmdAndHeaders.length);
+ uint8Frame.set(
+ nullTerminator,
+ uint8CmdAndHeaders.length + binaryBody.length
+ );
+ return uint8Frame;
+ }
+ /**
+ * Serialize a STOMP frame as per STOMP standards, suitable to be sent to the STOMP broker.
+ *
+ * @internal
+ */
+ static marshall(params) {
+ const frame = new FrameImpl(params);
+ return frame.serialize();
+ }
+ /**
+ * Escape header values
+ */
+ static hdrValueEscape(str) {
+ return str
+ .replace(/\\/g, "\\\\")
+ .replace(/\r/g, "\\r")
+ .replace(/\n/g, "\\n")
+ .replace(/:/g, "\\c");
+ }
+ /**
+ * UnEscape header values
+ */
+ static hdrValueUnEscape(str) {
+ return str
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\c/g, ":")
+ .replace(/\\\\/g, "\\");
+ }
+}
+
+module.exports = { Frame: FrameImpl };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
new file mode 100644
index 0000000000..d5d441c543
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js
@@ -0,0 +1,40 @@
+/* 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 frameModule = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js");
+const {
+ Parser,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js");
+const {
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { Frame } = frameModule;
+
+function parseStompJs(message) {
+ let output;
+
+ function onFrame(rawFrame) {
+ const frame = Frame.fromRawFrame(rawFrame);
+ const { error, json } = parseJSON(frame.body);
+
+ output = {
+ command: frame.command,
+ headers: frame.headers,
+ body: error ? frame.body : json,
+ };
+ }
+ const onIncomingPing = () => {};
+ const parser = new Parser(onFrame, onIncomingPing);
+
+ parser.parseChunk(message);
+
+ return output;
+}
+
+module.exports = {
+ parseStompJs,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
new file mode 100644
index 0000000000..420c7479db
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build
@@ -0,0 +1,10 @@
+# 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/.
+
+DevToolsModules(
+ "byte.js",
+ "frame.js",
+ "index.js",
+ "parser.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
new file mode 100644
index 0000000000..a7116627d3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2018 Deepak Kumar
+ *
+ * MIT License
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * https://github.com/stomp-js/stompjs
+ * https://github.com/stomp-js/stompjs/blob/develop/src/parser.ts
+ */
+
+"use strict";
+
+/**
+ * @internal
+ */
+const NULL = 0;
+/**
+ * @internal
+ */
+const LF = 10;
+/**
+ * @internal
+ */
+const CR = 13;
+/**
+ * @internal
+ */
+const COLON = 58;
+/**
+ * This is an evented, rec descent parser.
+ * A stream of Octets can be passed and whenever it recognizes
+ * a complete Frame or an incoming ping it will invoke the registered callbacks.
+ *
+ * All incoming Octets are fed into _onByte function.
+ * Depending on current state the _onByte function keeps changing.
+ * Depending on the state it keeps accumulating into _token and _results.
+ * State is indicated by current value of _onByte, all states are named as _collect.
+ *
+ * STOMP standards https://stomp.github.io/stomp-specification-1.2.html
+ * imply that all lengths are considered in bytes (instead of string lengths).
+ * So, before actual parsing, if the incoming data is String it is converted to Octets.
+ * This allows faithful implementation of the protocol and allows NULL Octets to be present in the body.
+ *
+ * There is no peek function on the incoming data.
+ * When a state change occurs based on an Octet without consuming the Octet,
+ * the Octet, after state change, is fed again (_reinjectByte).
+ * This became possible as the state change can be determined by inspecting just one Octet.
+ *
+ * There are two modes to collect the body, if content-length header is there then it by counting Octets
+ * otherwise it is determined by NULL terminator.
+ *
+ * Following the standards, the command and headers are converted to Strings
+ * and the body is returned as Octets.
+ * Headers are returned as an array and not as Hash - to allow multiple occurrence of an header.
+ *
+ * This parser does not use Regular Expressions as that can only operate on Strings.
+ *
+ * It handles if multiple STOMP frames are given as one chunk, a frame is split into multiple chunks, or
+ * any combination there of. The parser remembers its state (any partial frame) and continues when a new chunk
+ * is pushed.
+ *
+ * Typically the higher level function will convert headers to Hash, handle unescaping of header values
+ * (which is protocol version specific), and convert body to text.
+ *
+ * Check the parser.spec.js to understand cases that this parser is supposed to handle.
+ *
+ * Part of `@stomp/stompjs`.
+ *
+ * @internal
+ */
+class Parser {
+ constructor(onFrame, onIncomingPing) {
+ this.onFrame = onFrame;
+ this.onIncomingPing = onIncomingPing;
+ this._encoder = new TextEncoder();
+ this._decoder = new TextDecoder();
+ this._token = [];
+ this._initState();
+ }
+ parseChunk(segment, appendMissingNULLonIncoming = false) {
+ let chunk;
+ if (segment instanceof ArrayBuffer) {
+ chunk = new Uint8Array(segment);
+ } else {
+ chunk = this._encoder.encode(segment);
+ }
+ // See https://github.com/stomp-js/stompjs/issues/89
+ // Remove when underlying issue is fixed.
+ //
+ // Send a NULL byte, if the last byte of a Text frame was not NULL.F
+ if (appendMissingNULLonIncoming && chunk[chunk.length - 1] !== 0) {
+ const chunkWithNull = new Uint8Array(chunk.length + 1);
+ chunkWithNull.set(chunk, 0);
+ chunkWithNull[chunk.length] = 0;
+ chunk = chunkWithNull;
+ }
+ // tslint:disable-next-line:prefer-for-of
+ for (let i = 0; i < chunk.length; i++) {
+ const byte = chunk[i];
+ this._onByte(byte);
+ }
+ }
+ // The following implements a simple Rec Descent Parser.
+ // The grammar is simple and just one byte tells what should be the next state
+ _collectFrame(byte) {
+ if (byte === NULL) {
+ // Ignore
+ return;
+ }
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ // Incoming Ping
+ this.onIncomingPing();
+ return;
+ }
+ this._onByte = this._collectCommand;
+ this._reinjectByte(byte);
+ }
+ _collectCommand(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.command = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaders(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._setupCollectBody();
+ return;
+ }
+ this._onByte = this._collectHeaderKey;
+ this._reinjectByte(byte);
+ }
+ _reinjectByte(byte) {
+ this._onByte(byte);
+ }
+ _collectHeaderKey(byte) {
+ if (byte === COLON) {
+ this._headerKey = this._consumeTokenAsUTF8();
+ this._onByte = this._collectHeaderValue;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectHeaderValue(byte) {
+ if (byte === CR) {
+ // Ignore CR
+ return;
+ }
+ if (byte === LF) {
+ this._results.headers.push([this._headerKey, this._consumeTokenAsUTF8()]);
+ this._headerKey = undefined;
+ this._onByte = this._collectHeaders;
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _setupCollectBody() {
+ const contentLengthHeader = this._results.headers.filter(header => {
+ return header[0] === "content-length";
+ })[0];
+ if (contentLengthHeader) {
+ this._bodyBytesRemaining = parseInt(contentLengthHeader[1], 10);
+ this._onByte = this._collectBodyFixedSize;
+ } else {
+ this._onByte = this._collectBodyNullTerminated;
+ }
+ }
+ _collectBodyNullTerminated(byte) {
+ if (byte === NULL) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _collectBodyFixedSize(byte) {
+ // It is post decrement, so that we discard the trailing NULL octet
+ if (this._bodyBytesRemaining-- === 0) {
+ this._retrievedBody();
+ return;
+ }
+ this._consumeByte(byte);
+ }
+ _retrievedBody() {
+ this._results.binaryBody = this._consumeTokenAsRaw();
+ this.onFrame(this._results);
+ this._initState();
+ }
+ // Rec Descent Parser helpers
+ _consumeByte(byte) {
+ this._token.push(byte);
+ }
+ _consumeTokenAsUTF8() {
+ return this._decoder.decode(this._consumeTokenAsRaw());
+ }
+ _consumeTokenAsRaw() {
+ const rawResult = new Uint8Array(this._token);
+ this._token = [];
+ return rawResult;
+ }
+ _initState() {
+ this._results = {
+ command: undefined,
+ headers: [],
+ binaryBody: undefined,
+ };
+ this._token = [];
+ this._headerKey = undefined;
+ this._onByte = this._collectFrame;
+ }
+}
+
+module.exports = { Parser };
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
new file mode 100644
index 0000000000..de73a7986c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js
@@ -0,0 +1,274 @@
+/* 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";
+
+// An implementation for WAMP messages parsing https://wamp-proto.org/
+var WampMessageType;
+(function (wampMessageTypeEnum) {
+ wampMessageTypeEnum[(wampMessageTypeEnum.Hello = 1)] = "Hello";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Welcome = 2)] = "Welcome";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Abort = 3)] = "Abort";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Challenge = 4)] = "Challenge";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Authenticate = 5)] = "Authenticate";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Goodbye = 6)] = "Goodbye";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Error = 8)] = "Error";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Publish = 16)] = "Publish";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Published = 17)] = "Published";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribe = 32)] = "Subscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Subscribed = 33)] = "Subscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribe = 34)] = "Unsubscribe";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unsubscribed = 35)] = "Unsubscribed";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Event = 36)] = "Event";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Call = 48)] = "Call";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Cancel = 49)] = "Cancel";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Result = 50)] = "Result";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Register = 64)] = "Register";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Registered = 65)] = "Registered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregister = 66)] = "Unregister";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Unregistered = 67)] = "Unregistered";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Invocation = 68)] = "Invocation";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Interrupt = 69)] = "Interrupt";
+ wampMessageTypeEnum[(wampMessageTypeEnum.Yield = 70)] = "Yield";
+})(WampMessageType || (WampMessageType = {}));
+
+// The WAMP protocol consists of many messages, disable complexity for one time
+// eslint-disable-next-line complexity
+function parseWampArray(messageArray) {
+ const [messageType, ...args] = messageArray;
+ switch (messageType) {
+ case WampMessageType.Hello:
+ return new HelloMessage(args);
+ case WampMessageType.Welcome:
+ return new WelcomeMessage(args);
+ case WampMessageType.Abort:
+ return new AbortMessage(args);
+ case WampMessageType.Challenge:
+ return new ChallengeMessage(args);
+ case WampMessageType.Authenticate:
+ return new AuthenticateMessage(args);
+ case WampMessageType.Goodbye:
+ return new GoodbyeMessage(args);
+ case WampMessageType.Error:
+ return new ErrorMessage(args);
+ case WampMessageType.Publish:
+ return new PublishMessage(args);
+ case WampMessageType.Published:
+ return new PublishedMessage(args);
+ case WampMessageType.Subscribe:
+ return new SubscribeMessage(args);
+ case WampMessageType.Subscribed:
+ return new SubscribedMessage(args);
+ case WampMessageType.Unsubscribe:
+ return new UnsubscribeMessage(args);
+ case WampMessageType.Unsubscribed:
+ return new UnsubscribedMessage(args);
+ case WampMessageType.Event:
+ return new EventMessage(args);
+ case WampMessageType.Call:
+ return new CallMessage(args);
+ case WampMessageType.Cancel:
+ return new CancelMessage(args);
+ case WampMessageType.Result:
+ return new ResultMessage(args);
+ case WampMessageType.Register:
+ return new RegisterMessage(args);
+ case WampMessageType.Registered:
+ return new RegisteredMessage(args);
+ case WampMessageType.Unregister:
+ return new UnregisterMessage(args);
+ case WampMessageType.Unregistered:
+ return new UnregisteredMessage(args);
+ case WampMessageType.Invocation:
+ return new InvocationMessage(args);
+ case WampMessageType.Interrupt:
+ return new InterruptMessage(args);
+ case WampMessageType.Yield:
+ return new YieldMessage(args);
+ default:
+ return null;
+ }
+}
+class WampMessage {
+ constructor(code) {
+ this.messageCode = code;
+ this.messageName = WampMessageType[code].toUpperCase();
+ }
+}
+class HelloMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Hello);
+ [this.realm, this.details] = messageArgs;
+ }
+}
+class WelcomeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Welcome);
+ [this.session, this.details] = messageArgs;
+ }
+}
+class AbortMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Abort);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ChallengeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Challenge);
+ [this.authMethod, this.extra] = messageArgs;
+ }
+}
+class AuthenticateMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Authenticate);
+ [this.signature, this.extra] = messageArgs;
+ }
+}
+class GoodbyeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Goodbye);
+ [this.details, this.reason] = messageArgs;
+ }
+}
+class ErrorMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Error);
+ [
+ this.type,
+ this.request,
+ this.details,
+ this.error,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class PublishMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Publish);
+ [this.request, this.options, this.topic, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class PublishedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Published);
+ [this.request, this.publication] = messageArgs;
+ }
+}
+class SubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribe);
+ [this.request, this.options, this.topic] = messageArgs;
+ }
+}
+class SubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Subscribed);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribeMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribe);
+ [this.request, this.subscription] = messageArgs;
+ }
+}
+class UnsubscribedMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unsubscribed);
+ [this.request] = messageArgs;
+ }
+}
+class EventMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Event);
+ [
+ this.subscription,
+ this.publication,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CallMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Call);
+ [
+ this.request,
+ this.options,
+ this.procedure,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class CancelMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Cancel);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class ResultMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Result);
+ [this.request, this.details, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+class RegisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Register);
+ [this.request, this.options, this.procedure] = messageArgs;
+ }
+}
+class RegisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Registered);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisterMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregister);
+ [this.request, this.registration] = messageArgs;
+ }
+}
+class UnregisteredMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Unregistered);
+ [this.request] = messageArgs;
+ }
+}
+class InvocationMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Invocation);
+ [
+ this.request,
+ this.registration,
+ this.details,
+ this.arguments,
+ this.argumentsKw,
+ ] = messageArgs;
+ }
+}
+class InterruptMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Interrupt);
+ [this.request, this.options] = messageArgs;
+ }
+}
+class YieldMessage extends WampMessage {
+ constructor(messageArgs) {
+ super(WampMessageType.Yield);
+ [this.request, this.options, this.arguments, this.argumentsKw] =
+ messageArgs;
+ }
+}
+
+module.exports = {
+ parseWampArray,
+};
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
new file mode 100644
index 0000000000..b6b7c91036
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build
@@ -0,0 +1,8 @@
+# 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/.
+
+DevToolsModules(
+ "arrayParser.js",
+ "serializers.js",
+)
diff --git a/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
new file mode 100644
index 0000000000..c2139d320c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js
@@ -0,0 +1,73 @@
+/* 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 {
+ parseWampArray,
+} = require("resource://devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js");
+const msgpack = require("resource://devtools/client/netmonitor/src/components/messages/msgpack.js");
+const cbor = require("resource://devtools/client/netmonitor/src/components/messages/cbor.js");
+
+class WampSerializer {
+ deserializeMessage(payload) {
+ const array = this.deserializeToArray(payload);
+ const result = parseWampArray(array);
+ return result;
+ }
+
+ stringToBinary(str) {
+ const result = new Uint8Array(str.length);
+ for (let i = 0; i < str.length; i++) {
+ result[i] = str[i].charCodeAt(0);
+ }
+ return result;
+ }
+}
+
+class JsonSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.json";
+ this.description = "WAMP JSON";
+ }
+ deserializeToArray(payload) {
+ return JSON.parse(payload);
+ }
+}
+
+class MessagePackSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.msgpack";
+ this.description = "WAMP MessagePack";
+ }
+ deserializeToArray(payload) {
+ const binary = this.stringToBinary(payload);
+ return msgpack.deserialize(binary);
+ }
+}
+
+class CBORSerializer extends WampSerializer {
+ constructor() {
+ super(...arguments);
+ this.subProtocol = "wamp.2.cbor";
+ this.description = "WAMP CBOR";
+ }
+ deserializeToArray(payload) {
+ const binaryBuffer = this.stringToBinary(payload).buffer;
+ return cbor.decode(binaryBuffer);
+ }
+}
+
+const serializers = {};
+for (var serializer of [
+ new JsonSerializer(),
+ new MessagePackSerializer(),
+ new CBORSerializer(),
+]) {
+ serializers[serializer.subProtocol] = serializer;
+}
+
+module.exports = { wampSerializers: serializers };
diff --git a/devtools/client/netmonitor/src/components/moz.build b/devtools/client/netmonitor/src/components/moz.build
new file mode 100644
index 0000000000..98d821338f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/moz.build
@@ -0,0 +1,28 @@
+# 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/.
+
+DIRS += [
+ "messages",
+ "new-request",
+ "previews",
+ "request-blocking",
+ "request-details",
+ "request-list",
+ "search",
+]
+
+DevToolsModules(
+ "App.js",
+ "CustomRequestPanel.js",
+ "DropHarHandler.js",
+ "MonitorPanel.js",
+ "NetworkActionBar.js",
+ "SecurityState.js",
+ "SourceEditor.js",
+ "StatisticsPanel.js",
+ "StatusBar.js",
+ "StatusCode.js",
+ "TabboxPanel.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js b/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js
new file mode 100644
index 0000000000..826f0317ba
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js
@@ -0,0 +1,511 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const asyncStorage = require("resource://devtools/shared/async-storage.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getClickedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getUrlQuery,
+ parseQueryString,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const InputMap = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/new-request/InputMap.js")
+);
+const { button, div, footer, label, textarea, select, option } = dom;
+
+const CUSTOM_HEADERS = L10N.getStr("netmonitor.custom.newRequestHeaders");
+const CUSTOM_NEW_REQUEST_URL_LABEL = L10N.getStr(
+ "netmonitor.custom.newRequestUrlLabel"
+);
+const CUSTOM_POSTDATA = L10N.getStr("netmonitor.custom.postBody");
+const CUSTOM_POSTDATA_PLACEHOLDER = L10N.getStr(
+ "netmonitor.custom.postBody.placeholder"
+);
+const CUSTOM_QUERY = L10N.getStr("netmonitor.custom.urlParameters");
+const CUSTOM_SEND = L10N.getStr("netmonitor.custom.send");
+const CUSTOM_CLEAR = L10N.getStr("netmonitor.custom.clear");
+
+const FIREFOX_DEFAULT_HEADERS = [
+ "Accept-Charset",
+ "Accept-Encoding",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Connection",
+ "Content-Length",
+ "Cookie",
+ "Cookie2",
+ "Date",
+ "DNT",
+ "Expect",
+ "Feature-Policy",
+ "Host",
+ "Keep-Alive",
+ "Origin",
+ "Proxy-",
+ "Sec-",
+ "Referer",
+ "TE",
+ "Trailer",
+ "Transfer-Encoding",
+ "Upgrade",
+ "Via",
+];
+// This does not include the CONNECT method as it is restricted and special.
+// See https://bugzilla.mozilla.org/show_bug.cgi?id=1769572#c2 for details
+const HTTP_METHODS = [
+ "GET",
+ "HEAD",
+ "POST",
+ "DELETE",
+ "PUT",
+ "OPTIONS",
+ "TRACE",
+ "PATCH",
+];
+
+/*
+ * HTTP Custom request panel component
+ * A network request panel which enables creating and sending new requests
+ * or selecting, editing and re-sending current requests.
+ */
+class HTTPCustomRequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object,
+ sendCustomRequest: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ method: HTTP_METHODS[0],
+ url: "",
+ urlQueryParams: [],
+ headers: [],
+ postBody: "",
+ // Flag to know the data from either the request or the async storage has
+ // been loaded in componentDidMount
+ _isStateDataReady: false,
+ };
+
+ this.handleInputChange = this.handleInputChange.bind(this);
+ this.handleChangeURL = this.handleChangeURL.bind(this);
+ this.updateInputMapItem = this.updateInputMapItem.bind(this);
+ this.addInputMapItem = this.addInputMapItem.bind(this);
+ this.deleteInputMapItem = this.deleteInputMapItem.bind(this);
+ this.checkInputMapItem = this.checkInputMapItem.bind(this);
+ this.handleClear = this.handleClear.bind(this);
+ this.createQueryParamsListFromURL =
+ this.createQueryParamsListFromURL.bind(this);
+ this.onUpdateQueryParams = this.onUpdateQueryParams.bind(this);
+ }
+
+ async componentDidMount() {
+ let { connector, request } = this.props;
+ const persistedCustomRequest = await asyncStorage.getItem(
+ "devtools.netmonitor.customRequest"
+ );
+ request = request || persistedCustomRequest;
+
+ if (!request) {
+ this.setState({ _isStateDataReady: true });
+ return;
+ }
+
+ // We need this part because in the asyncStorage we are saving the request in one format
+ // and from the edit and resend it comes in a different form with different properties,
+ // so we need this to nomalize the request.
+ if (request.requestHeaders) {
+ request.headers = request.requestHeaders.headers;
+ }
+
+ if (request.requestPostData?.postData?.text) {
+ request.postBody = request.requestPostData.postData.text;
+ }
+
+ const headers = request.headers
+ .map(({ name, value }) => {
+ return {
+ name,
+ value,
+ checked: true,
+ disabled: FIREFOX_DEFAULT_HEADERS.some(i => name.startsWith(i)),
+ };
+ })
+ .sort((a, b) => {
+ if (a.disabled && !b.disabled) {
+ return -1;
+ }
+ if (!a.disabled && b.disabled) {
+ return 1;
+ }
+ return 0;
+ });
+
+ if (request.requestPostDataAvailable && !request.postBody) {
+ const requestData = await connector.requestData(
+ request.id,
+ "requestPostData"
+ );
+ request.postBody = requestData.postData.text;
+ }
+
+ this.setState({
+ method: request.method,
+ url: request.url,
+ urlQueryParams: this.createQueryParamsListFromURL(request.url),
+ headers,
+ postBody: request.postBody,
+ _isStateDataReady: true,
+ });
+ }
+
+ componentDidUpdate(prevProps, prevState) {
+ // This is when the query params change in the url params input map
+ if (
+ prevState.urlQueryParams !== this.state.urlQueryParams &&
+ prevState.url === this.state.url
+ ) {
+ this.onUpdateQueryParams();
+ }
+ }
+
+ componentWillUnmount() {
+ asyncStorage.setItem("devtools.netmonitor.customRequest", this.state);
+ }
+
+ handleChangeURL(event) {
+ const { value } = event.target;
+
+ this.setState({
+ url: value,
+ urlQueryParams: this.createQueryParamsListFromURL(value),
+ });
+ }
+
+ handleInputChange(event) {
+ const { name, value } = event.target;
+ const newState = {
+ [name]: value,
+ };
+
+ // If the message body changes lets make sure we
+ // keep the content-length up to date.
+ if (name == "postBody") {
+ newState.headers = this.state.headers.map(header => {
+ if (header.name == "Content-Length") {
+ header.value = value.length;
+ }
+ return header;
+ });
+ }
+
+ this.setState(newState);
+ }
+
+ updateInputMapItem(stateName, event) {
+ const { name, value } = event.target;
+ const [prop, index] = name.split("-");
+ const updatedList = [...this.state[stateName]];
+ updatedList[Number(index)][prop] = value;
+
+ this.setState({
+ [stateName]: updatedList,
+ });
+ }
+
+ addInputMapItem(stateName, name, value) {
+ this.setState({
+ [stateName]: [
+ ...this.state[stateName],
+ { name, value, checked: true, disabled: false },
+ ],
+ });
+ }
+
+ deleteInputMapItem(stateName, index) {
+ this.setState({
+ [stateName]: this.state[stateName].filter((_, i) => i !== index),
+ });
+ }
+
+ checkInputMapItem(stateName, index, checked) {
+ this.setState({
+ [stateName]: this.state[stateName].map((item, i) => {
+ if (index === i) {
+ return {
+ ...item,
+ checked,
+ };
+ }
+ return item;
+ }),
+ });
+ }
+
+ onUpdateQueryParams() {
+ const { urlQueryParams, url } = this.state;
+ let queryString = "";
+ for (const { name, value, checked } of urlQueryParams) {
+ if (checked) {
+ queryString += `${encodeURIComponent(name)}=${encodeURIComponent(
+ value
+ )}&`;
+ }
+ }
+
+ let finalURL = url.split("?")[0];
+
+ if (queryString.length) {
+ finalURL += `?${queryString.substring(0, queryString.length - 1)}`;
+ }
+ this.setState({
+ url: finalURL,
+ });
+ }
+
+ createQueryParamsListFromURL(url = "") {
+ const parsedQuery = parseQueryString(getUrlQuery(url) || url.split("?")[1]);
+ const queryArray = parsedQuery || [];
+ return queryArray.map(({ name, value }) => {
+ return {
+ checked: true,
+ name,
+ value,
+ };
+ });
+ }
+
+ handleClear() {
+ this.setState({
+ method: HTTP_METHODS[0],
+ url: "",
+ urlQueryParams: [],
+ headers: [],
+ postBody: "",
+ });
+ }
+
+ render() {
+ return div(
+ { className: "http-custom-request-panel" },
+ div(
+ { className: "http-custom-request-panel-content" },
+ div(
+ {
+ className: "tabpanel-summary-container http-custom-method-and-url",
+ id: "http-custom-method-and-url",
+ },
+ select(
+ {
+ className: "http-custom-method-value",
+ id: "http-custom-method-value",
+ name: "method",
+ onChange: this.handleInputChange,
+ onBlur: this.handleInputChange,
+ value: this.state.method,
+ },
+
+ HTTP_METHODS.map(item =>
+ option(
+ {
+ value: item,
+ key: item,
+ },
+ item
+ )
+ )
+ ),
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": this.state.url,
+ title: this.state.url,
+ },
+ textarea({
+ className: "http-custom-url-value",
+ id: "http-custom-url-value",
+ name: "url",
+ placeholder: CUSTOM_NEW_REQUEST_URL_LABEL,
+ onChange: event => {
+ this.handleChangeURL(event);
+ },
+ onBlur: this.handleTextareaChange,
+ value: this.state.url,
+ rows: 1,
+ })
+ )
+ ),
+ div(
+ {
+ className: "tabpanel-summary-container http-custom-section",
+ id: "http-custom-query",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "http-custom-query-value",
+ },
+ CUSTOM_QUERY
+ ),
+ // This is the input map for the Url Parameters Component
+ InputMap({
+ list: this.state.urlQueryParams,
+ onUpdate: event => {
+ this.updateInputMapItem(
+ "urlQueryParams",
+ event,
+ this.onUpdateQueryParams
+ );
+ },
+ onAdd: (name, value) =>
+ this.addInputMapItem(
+ "urlQueryParams",
+ name,
+ value,
+ this.onUpdateQueryParams
+ ),
+ onDelete: index =>
+ this.deleteInputMapItem(
+ "urlQueryParams",
+ index,
+ this.onUpdateQueryParams
+ ),
+ onChecked: (index, checked) => {
+ this.checkInputMapItem(
+ "urlQueryParams",
+ index,
+ checked,
+ this.onUpdateQueryParams
+ );
+ },
+ })
+ ),
+ div(
+ {
+ id: "http-custom-headers",
+ className: "tabpanel-summary-container http-custom-section",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "custom-headers-value",
+ },
+ CUSTOM_HEADERS
+ ),
+ // This is the input map for the Headers Component
+ InputMap({
+ ref: this.headersListRef,
+ list: this.state.headers,
+ onUpdate: event => {
+ this.updateInputMapItem("headers", event);
+ },
+ onAdd: (name, value) =>
+ this.addInputMapItem("headers", name, value),
+ onDelete: index => this.deleteInputMapItem("headers", index),
+ onChecked: (index, checked) => {
+ this.checkInputMapItem("headers", index, checked);
+ },
+ })
+ ),
+ div(
+ {
+ id: "http-custom-postdata",
+ className: "tabpanel-summary-container http-custom-section",
+ },
+ label(
+ {
+ className: "http-custom-request-label",
+ htmlFor: "http-custom-postdata-value",
+ },
+ CUSTOM_POSTDATA
+ ),
+ textarea({
+ className: "tabpanel-summary-input",
+ id: "http-custom-postdata-value",
+ name: "postBody",
+ placeholder: CUSTOM_POSTDATA_PLACEHOLDER,
+ onChange: this.handleInputChange,
+ rows: 6,
+ value: this.state.postBody,
+ wrap: "off",
+ })
+ )
+ ),
+ footer(
+ { className: "http-custom-request-button-container" },
+ button(
+ {
+ className: "devtools-button",
+ id: "http-custom-request-clear-button",
+ onClick: this.handleClear,
+ },
+ CUSTOM_CLEAR
+ ),
+ button(
+ {
+ className: "devtools-button",
+ id: "http-custom-request-send-button",
+ disabled:
+ !this.state._isStateDataReady ||
+ !this.state.url ||
+ !this.state.method,
+ onClick: () => {
+ const newRequest = {
+ method: this.state.method,
+ url: this.state.url,
+ cause: this.props.request?.cause,
+ urlQueryParams: this.state.urlQueryParams.map(
+ ({ checked, ...params }) => params
+ ),
+ requestHeaders: {
+ headers: this.state.headers
+ .filter(({ checked }) => checked)
+ .map(({ checked, ...headersValues }) => headersValues),
+ },
+ };
+
+ if (this.state.postBody) {
+ newRequest.requestPostData = {
+ postData: {
+ text: this.state.postBody,
+ },
+ };
+ }
+ this.props.sendCustomRequest(newRequest);
+ },
+ },
+ CUSTOM_SEND
+ )
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({ request: getClickedRequest(state) }),
+ (dispatch, props) => ({
+ sendCustomRequest: request =>
+ dispatch(Actions.sendHTTPCustomRequest(request)),
+ })
+)(HTTPCustomRequestPanel);
diff --git a/devtools/client/netmonitor/src/components/new-request/InputMap.js b/devtools/client/netmonitor/src/components/new-request/InputMap.js
new file mode 100644
index 0000000000..6e9eff2845
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/InputMap.js
@@ -0,0 +1,211 @@
+/* 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,
+ createRef,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div, input, textarea, button } = dom;
+
+const CUSTOM_NEW_REQUEST_INPUT_NAME = L10N.getStr(
+ "netmonitor.custom.placeholder.name"
+);
+
+const CUSTOM_NEW_REQUEST_INPUT_VALUE = L10N.getStr(
+ "netmonitor.custom.placeholder.value"
+);
+
+const REMOVE_ITEM = L10N.getStr("netmonitor.custom.removeItem");
+
+/**
+ * Editable name and value list component with optional form to add new items
+ **/
+class InputMap extends Component {
+ static get propTypes() {
+ return {
+ list: PropTypes.arrayOf(
+ PropTypes.shape({
+ name: PropTypes.string.isRequired,
+ value: PropTypes.string.isRequired,
+ disabled: PropTypes.bool,
+ })
+ ).isRequired,
+ onUpdate: PropTypes.func,
+ onAdd: PropTypes.func,
+ onDelete: PropTypes.func,
+ onChange: PropTypes.func,
+ onChecked: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.listRef = createRef();
+
+ this.state = {
+ name: "",
+ value: "",
+ };
+ }
+
+ render() {
+ const { list, onUpdate, onAdd, onDelete, onChecked } = this.props;
+ const { name, value } = this.state;
+
+ // Adds a new item with name and value when the user starts typing on the form
+ const onKeyDown = event => {
+ const { target } = event;
+ onAdd(name, value);
+ this.setState({ name: "", value: "" }, () => {
+ // Get next to last child on the list,
+ // because that was the item that was just added and
+ // we need to focous on it, so the user can keep editing it.
+ const targetParentNode =
+ this.listRef.current.childNodes?.[
+ this.listRef.current.childElementCount - 2
+ ];
+ targetParentNode?.querySelector(`.${target.className}`).focus();
+ });
+ };
+
+ return div(
+ {
+ ref: this.listRef,
+ className: "http-custom-input-and-map-form",
+ },
+ list.map((item, index) => {
+ return div(
+ {
+ className: "tabpanel-summary-container http-custom-input",
+ id: `http-custom-${item.name.toLowerCase()}`,
+ key: index,
+ },
+ input({
+ className: "tabpanel-summary-input-checkbox",
+ name: `checked-${index}`,
+ type: "checkbox",
+ onChange: event => {
+ onChecked(index, event.target.checked);
+ },
+ checked: item.checked,
+ disabled: !!item.disabled,
+ wrap: "off",
+ }),
+ div(
+ { className: "tabpanel-summary-input-name" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": item.name,
+ title: item.name,
+ },
+ textarea({
+ className: "http-custom-input-name",
+ name: `name-${index}`,
+ value: item.name,
+ disabled: !!item.disabled,
+ onChange: event => {
+ onUpdate(event);
+ },
+ rows: 1,
+ })
+ )
+ ),
+ div(
+ { className: "tabpanel-summary-input-value" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": item.value,
+ title: item.value,
+ },
+ textarea({
+ className: "http-custom-input-value",
+ name: `value-${index}`,
+ placeholder: "value",
+ disabled: !!item.disabled,
+ onChange: event => {
+ onUpdate(event);
+ },
+ value: item.value,
+ rows: 1,
+ })
+ )
+ ),
+ !item.disabled &&
+ onDelete &&
+ button({
+ className: "http-custom-delete-button",
+ title: REMOVE_ITEM,
+ "aria-label": REMOVE_ITEM,
+ onClick: () => onDelete(index),
+ })
+ );
+ }),
+ onAdd &&
+ div(
+ {
+ className: "map-add-new-inputs",
+ },
+ input({
+ className: "tabpanel-summary-input-checkbox",
+ onChange: () => {},
+ checked: true,
+ type: "checkbox",
+ }),
+ div(
+ { className: "tabpanel-summary-input-name" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": name,
+ title: value,
+ },
+ textarea({
+ className: "http-custom-input-name",
+ type: "text",
+ ref: "addInputName",
+ checked: true,
+ value: name,
+ rows: 1,
+ placeholder: CUSTOM_NEW_REQUEST_INPUT_NAME,
+ onChange: e => this.setState({ name: e.target.value }),
+ onKeyDown,
+ })
+ )
+ ),
+ div(
+ { className: "tabpanel-summary-input-value" },
+ div(
+ {
+ className: "auto-growing-textarea",
+ "data-replicated-value": value,
+ title: value,
+ },
+ textarea({
+ className: "http-custom-input-value",
+ type: "text",
+ ref: "addInputValue",
+ value,
+ onChange: e => this.setState({ value: e.target.value }),
+ rows: 1,
+ placeholder: CUSTOM_NEW_REQUEST_INPUT_VALUE,
+ onKeyDown,
+ })
+ )
+ )
+ )
+ );
+ }
+}
+
+module.exports = InputMap;
diff --git a/devtools/client/netmonitor/src/components/new-request/moz.build b/devtools/client/netmonitor/src/components/new-request/moz.build
new file mode 100644
index 0000000000..7e47799a22
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/new-request/moz.build
@@ -0,0 +1,8 @@
+# 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/.
+
+DevToolsModules(
+ "HTTPCustomRequestPanel.js",
+ "InputMap.js",
+)
diff --git a/devtools/client/netmonitor/src/components/previews/FontPreview.js b/devtools/client/netmonitor/src/components/previews/FontPreview.js
new file mode 100644
index 0000000000..2692fdefa0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/FontPreview.js
@@ -0,0 +1,135 @@
+/* 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 {
+ gDevTools,
+} = require("resource://devtools/client/framework/devtools.js");
+const {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+const {
+ div,
+ img,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const { getColor } = require("resource://devtools/client/shared/theme.js");
+
+const FONT_NAME = L10N.getStr("netmonitor.response.name");
+const FONT_MIME_TYPE = L10N.getStr("netmonitor.response.mime");
+const FONT_PREVIEW_FAILED = L10N.getStr(
+ "netmonitor.response.fontPreviewFailed"
+);
+
+const FONT_PREVIEW_TEXT =
+ "ABCDEFGHIJKLM\nNOPQRSTUVWXYZ\nabcdefghijklm\nnopqrstuvwxyz\n0123456789";
+
+class FontPreview extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ mimeType: PropTypes.string,
+ url: PropTypes.string,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ name: "",
+ dataURL: "",
+ };
+
+ this.onThemeChanged = this.onThemeChanged.bind(this);
+ }
+
+ componentDidMount() {
+ this.getPreview();
+
+ // Listen for theme changes as the color of the preview depends on the theme
+ gDevTools.on("theme-switched", this.onThemeChanged);
+ }
+
+ componentDidUpdate(prevProps) {
+ const { url } = this.props;
+ if (prevProps.url !== url) {
+ this.getPreview();
+ }
+ }
+
+ componentWillUnmount() {
+ gDevTools.off("theme-switched", this.onThemeChanged);
+ }
+
+ /**
+ * Handler for the "theme-switched" event.
+ */
+ onThemeChanged(frame) {
+ if (frame === window) {
+ this.getPreview();
+ }
+ }
+
+ /**
+ * Generate the font preview and receives information about the font.
+ */
+ async getPreview() {
+ const { connector } = this.props;
+
+ const toolbox = connector.getToolbox();
+ const inspectorFront = await toolbox.target.getFront("inspector");
+ const { pageStyle } = inspectorFront;
+ const pageFontFaces = await pageStyle.getAllUsedFontFaces({
+ includePreviews: true,
+ includeVariations: false,
+ previewText: FONT_PREVIEW_TEXT,
+ previewFillStyle: getColor("body-color"),
+ });
+
+ const fontFace = pageFontFaces.find(
+ pageFontFace => pageFontFace.URI === this.props.url
+ );
+
+ this.setState({
+ name: fontFace?.name ?? "",
+ dataURL: (await fontFace?.preview.data.string()) ?? "",
+ });
+ }
+
+ render() {
+ const { mimeType } = this.props;
+ const { name, dataURL } = this.state;
+
+ if (dataURL === "") {
+ return div({ className: "empty-notice" }, FONT_PREVIEW_FAILED);
+ }
+
+ return div(
+ { className: "panel-container response-font-box devtools-monospace" },
+ img({
+ className: "response-font",
+ src: dataURL,
+ alt: "",
+ }),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, FONT_NAME),
+ div({ className: "tabpanel-summary-value" }, name)
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, FONT_MIME_TYPE),
+ div({ className: "tabpanel-summary-value" }, mimeType)
+ )
+ );
+ }
+}
+
+module.exports = FontPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/HtmlPreview.js b/devtools/client/netmonitor/src/components/previews/HtmlPreview.js
new file mode 100644
index 0000000000..ab8c24fac0
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/HtmlPreview.js
@@ -0,0 +1,75 @@
+/* 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");
+
+/*
+ * Response preview component
+ * Display HTML content within a sandbox enabled iframe
+ */
+class HTMLPreview extends Component {
+ static get propTypes() {
+ return {
+ responseContent: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { container } = this.refs;
+ const iframe = container.ownerDocument.createXULElement("iframe");
+ this.iframe = iframe;
+ iframe.setAttribute("type", "content");
+ iframe.setAttribute("remote", "true");
+
+ // For some reason, when we try to select some text,
+ // a drag of the whole page is initiated.
+ // Workaround this by canceling any start of drag.
+ iframe.addEventListener("dragstart", e => e.preventDefault(), {
+ capture: true,
+ });
+
+ // Bug 1800916 allow interaction with the preview page until
+ // we find a way to prevent navigation without preventing copy paste from it.
+ //
+ // iframe.addEventListener("mousedown", e => e.preventDefault(), {
+ // capture: true,
+ // });
+ container.appendChild(iframe);
+
+ // browsingContext attribute is only available after the iframe
+ // is attached to the DOM Tree.
+ iframe.browsingContext.allowJavascript = false;
+
+ this.#updatePreview();
+ }
+
+ componentDidUpdate() {
+ this.#updatePreview();
+ }
+
+ componentWillUnmount() {
+ this.iframe.remove();
+ }
+
+ #updatePreview() {
+ const { responseContent } = this.props;
+ const htmlBody = responseContent ? responseContent.content.text : "";
+ this.iframe.setAttribute(
+ "src",
+ "data:text/html;charset=UTF-8," + encodeURIComponent(htmlBody)
+ );
+ }
+
+ render() {
+ return dom.div({ className: "html-preview", ref: "container" });
+ }
+}
+
+module.exports = HTMLPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/ImagePreview.js b/devtools/client/netmonitor/src/components/previews/ImagePreview.js
new file mode 100644
index 0000000000..003a7ec38e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/ImagePreview.js
@@ -0,0 +1,91 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+
+const {
+ div,
+ img,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const {
+ formDataURI,
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const RESPONSE_IMG_NAME = L10N.getStr("netmonitor.response.name");
+const RESPONSE_IMG_DIMENSIONS = L10N.getStr("netmonitor.response.dimensions");
+const RESPONSE_IMG_MIMETYPE = L10N.getStr("netmonitor.response.mime");
+
+class ImagePreview extends Component {
+ static get propTypes() {
+ return {
+ mimeType: PropTypes.string,
+ encoding: PropTypes.string,
+ text: PropTypes.string,
+ url: PropTypes.string,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ dimensions: {
+ width: 0,
+ height: 0,
+ },
+ };
+
+ this.updateDimensions = this.updateDimensions.bind(this);
+ }
+
+ updateDimensions({ target }) {
+ this.setState({
+ dimensions: {
+ width: target.naturalWidth,
+ height: target.naturalHeight,
+ },
+ });
+ }
+
+ render() {
+ const { mimeType, encoding, text, url } = this.props;
+ const { width, height } = this.state.dimensions;
+
+ return div(
+ { className: "panel-container response-image-box devtools-monospace" },
+ img({
+ className: "response-image",
+ src: formDataURI(mimeType, encoding, text),
+ onLoad: this.updateDimensions,
+ }),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_NAME),
+ div({ className: "tabpanel-summary-value" }, getUrlBaseName(url))
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_DIMENSIONS),
+ div({ className: "tabpanel-summary-value" }, `${width} × ${height}`)
+ ),
+ div(
+ { className: "response-summary" },
+ div({ className: "tabpanel-summary-label" }, RESPONSE_IMG_MIMETYPE),
+ div({ className: "tabpanel-summary-value" }, mimeType)
+ )
+ );
+ }
+}
+
+module.exports = ImagePreview;
diff --git a/devtools/client/netmonitor/src/components/previews/SourcePreview.js b/devtools/client/netmonitor/src/components/previews/SourcePreview.js
new file mode 100644
index 0000000000..7e9d011bad
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/SourcePreview.js
@@ -0,0 +1,178 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+const { div } = dom;
+/**
+ * CodeMirror editor as a React component
+ */
+class SourcePreview extends Component {
+ static get propTypes() {
+ return {
+ // Source editor syntax highlight mode, which is a mime type defined in CodeMirror
+ mode: PropTypes.string,
+ // Source editor content
+ text: PropTypes.string,
+ // Search result text to select
+ targetSearchResult: PropTypes.object,
+ // Reset target search result that has been used for navigation in this panel.
+ // This is done to avoid second navigation the next time.
+ resetTargetSearchResult: PropTypes.func,
+ };
+ }
+
+ componentDidMount() {
+ const { mode, text } = this.props;
+ this.loadEditor(mode, text);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.mode !== this.props.mode ||
+ nextProps.text !== this.props.text ||
+ nextProps.targetSearchResult !== this.props.targetSearchResult
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ const { mode, targetSearchResult, text } = this.props;
+
+ if (prevProps.text !== text) {
+ // When updating from editor to editor
+ this.updateEditor(mode, text);
+ } else if (prevProps.targetSearchResult !== targetSearchResult) {
+ this.findSearchResult();
+ }
+ }
+
+ componentWillUnmount() {
+ this.unloadEditor();
+ }
+
+ loadEditor(mode, text) {
+ this.editor = new Editor({
+ lineNumbers: true,
+ lineWrapping: false,
+ mode: null, // Disable auto syntax detection, but then we set mode asynchronously
+ readOnly: true,
+ theme: "mozilla",
+ value: text,
+ });
+
+ // Delay to CodeMirror initialization content to prevent UI freezing
+ this.editorTimeout = setTimeout(() => {
+ this.editorTimeout = null;
+ this.editor.appendToLocalElement(this.refs.editorElement);
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.findSearchResult();
+ });
+ });
+ }
+
+ updateEditor(mode, text) {
+ // Reset the existed 'mode' attribute in order to make setText() process faster
+ // to prevent drawing unnecessary syntax highlight.
+ if (this?.editor?.hasCodeMirror) {
+ this.editor.setMode(null);
+ this.editor.setText(text);
+ }
+
+ if (this.editorSetModeTimeout) {
+ clearTimeout(this.editorSetModeTimeout);
+ }
+
+ // CodeMirror's setMode() (syntax highlight) is the performance bottleneck when
+ // processing large content, so we enable it asynchronously within the setTimeout
+ // to avoid UI blocking. (rendering source code -> drawing syntax highlight)
+ this.editorSetModeTimeout = setTimeout(() => {
+ this.editorSetModeTimeout = null;
+ this.editor.setMode(mode);
+ this.findSearchResult();
+ });
+ }
+
+ unloadEditor() {
+ clearTimeout(this.editorTimeout);
+ clearTimeout(this.editorSetModeTimeout);
+ if (this.editor) {
+ this.editor.destroy();
+ this.editor = null;
+ }
+ }
+
+ findSearchResult() {
+ const { targetSearchResult, resetTargetSearchResult } = this.props;
+
+ if (targetSearchResult?.line) {
+ const { line } = targetSearchResult;
+ // scroll the editor to center the line
+ // with the target search result
+ if (this.editor) {
+ this.editor.setCursor({ line: line - 1 }, "center");
+ }
+ }
+
+ resetTargetSearchResult();
+ }
+
+ // Scroll to specified line if the user clicks on search results.
+ scrollToLine(element) {
+ const { targetSearchResult, resetTargetSearchResult } = this.props;
+
+ // The following code is responsible for scrolling given line
+ // to visible view-port.
+ // It gets the <div> child element representing the target
+ // line (by index) and uses `scrollIntoView` API to make sure
+ // it's visible to the user.
+ if (element && targetSearchResult && targetSearchResult.line) {
+ const child = element.children[targetSearchResult.line - 1];
+ if (child) {
+ const range = document.createRange();
+ range.selectNode(child);
+ document.getSelection().addRange(range);
+ child.scrollIntoView({ block: "center" });
+ }
+ resetTargetSearchResult();
+ }
+ }
+
+ renderEditor() {
+ return div(
+ { className: "editor-row-container" },
+ div({
+ ref: "editorElement",
+ className: "source-editor-mount devtools-monospace",
+ })
+ );
+ }
+
+ render() {
+ return div(
+ { key: "EDITOR_CONFIG", className: "editor-row-container" },
+ this.renderEditor()
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(SourcePreview);
diff --git a/devtools/client/netmonitor/src/components/previews/UrlPreview.js b/devtools/client/netmonitor/src/components/previews/UrlPreview.js
new file mode 100644
index 0000000000..c20762912f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/UrlPreview.js
@@ -0,0 +1,290 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ parseQueryString,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const TreeRow = createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+);
+
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+
+const { div, span, tr, td } = dom;
+
+/**
+ * Url Preview Component
+ * This component is used to render urls. Its show both compact and destructured views
+ * of the url. Its takes a url and the http method as properties.
+ *
+ * Example Url:
+ * https://foo.com/bla?x=123&y=456&z=789&a=foo&a=bar
+ *
+ * Structure:
+ * {
+ * GET : {
+ * "scheme" : "https",
+ * "host" : "foo.com",
+ * "filename" : "bla",
+ * "query" : {
+ * "x": "123",
+ * "y": "456",
+ * "z": "789",
+ * "a": {
+ * "0": foo,
+ * "1": bar
+ * }
+ * },
+ * "remote" : {
+ * "address" : "127.0.0.1:8080"
+ * }
+ * }
+ * }
+ */
+class UrlPreview extends Component {
+ static get propTypes() {
+ return {
+ url: PropTypes.string,
+ method: PropTypes.string,
+ address: PropTypes.string,
+ shouldExpandPreview: PropTypes.bool,
+ onTogglePreview: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.parseUrl = this.parseUrl.bind(this);
+ this.renderValue = this.renderValue.bind(this);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.url !== this.props.url ||
+ nextProps.method !== this.props.method ||
+ nextProps.address !== this.props.address
+ );
+ }
+
+ renderRow(props) {
+ const {
+ member: { name, level },
+ } = props;
+ if ((name == "query" || name == "remote") && level == 1) {
+ return tr(
+ { key: name, className: "treeRow stringRow" },
+ td(
+ { colSpan: 2, className: "splitter" },
+ div({ className: "horizontal-splitter" })
+ )
+ );
+ }
+
+ const customProps = { ...props };
+ customProps.member.selected = false;
+ return TreeRow(customProps);
+ }
+
+ renderValue(props) {
+ const {
+ member: { level, open },
+ value,
+ } = props;
+ if (level == 0) {
+ if (open) {
+ return "";
+ }
+ const { scheme, host, filename, query } = value;
+ const queryParamNames = query ? Object.keys(query) : [];
+ // render collapsed url
+ return div(
+ { key: "url", className: "url" },
+ span({ key: "url-scheme", className: "url-scheme" }, `${scheme}://`),
+ span({ key: "url-host", className: "url-host" }, `${host}`),
+ span({ key: "url-filename", className: "url-filename" }, `${filename}`),
+ !!queryParamNames.length &&
+ span({ key: "url-ques", className: "url-chars" }, "?"),
+
+ queryParamNames.map((name, index) => {
+ if (Array.isArray(query[name])) {
+ return query[name].map((item, queryIndex) => {
+ return span(
+ {
+ key: `url-params-${name}${queryIndex}`,
+ className: "url-params",
+ },
+ span(
+ {
+ key: `url-params${name}${queryIndex}-name`,
+ className: "url-params-name",
+ },
+ `${name}`
+ ),
+ span(
+ {
+ key: `url-chars-${name}${queryIndex}-equals`,
+ className: "url-chars",
+ },
+ "="
+ ),
+ span(
+ {
+ key: `url-params-${name}${queryIndex}-value`,
+ className: "url-params-value",
+ },
+ `${item}`
+ ),
+ (query[name].length - 1 !== queryIndex ||
+ queryParamNames.length - 1 !== index) &&
+ span({ key: "url-amp", className: "url-chars" }, "&")
+ );
+ });
+ }
+
+ return span(
+ { key: `url-params-${name}`, className: "url-params" },
+ span(
+ { key: "url-params-name", className: "url-params-name" },
+ `${name}`
+ ),
+ span({ key: "url-chars-equals", className: "url-chars" }, "="),
+ span(
+ { key: "url-params-value", className: "url-params-value" },
+ `${query[name]}`
+ ),
+ queryParamNames.length - 1 !== index &&
+ span({ key: "url-amp", className: "url-chars" }, "&")
+ );
+ })
+ );
+ }
+ if (typeof value !== "string") {
+ // the query node would be an object
+ if (level == 0) {
+ return "";
+ }
+ // for arrays (multival)
+ return "[...]";
+ }
+
+ return value;
+ }
+
+ parseUrl(url) {
+ const { method, address } = this.props;
+ const { host, protocol, pathname, search } = new URL(url);
+
+ const urlObject = {
+ [method]: {
+ scheme: protocol.replace(":", ""),
+ host,
+ filename: pathname,
+ },
+ };
+
+ const expandedNodes = new Set();
+
+ // check and add query parameters
+ if (search.length) {
+ const params = parseQueryString(search);
+ // make sure the query node is always expanded
+ expandedNodes.add(`/${method}/query`);
+ urlObject[method].query = params.reduce((map, obj) => {
+ const value = map[obj.name];
+ if (value || value === "") {
+ if (typeof value !== "object") {
+ expandedNodes.add(`/${method}/query/${obj.name}`);
+ map[obj.name] = [value];
+ }
+ map[obj.name].push(obj.value);
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, Object.create(null));
+ }
+
+ if (address) {
+ // makes sure the remote adress section is expanded
+ expandedNodes.add(`/${method}/remote`);
+ urlObject[method].remote = {
+ [L10N.getStr("netmonitor.headers.address")]: address,
+ };
+ }
+
+ return {
+ urlObject,
+ expandedNodes,
+ };
+ }
+
+ render() {
+ const {
+ url,
+ method,
+ shouldExpandPreview = false,
+ onTogglePreview,
+ } = this.props;
+
+ const { urlObject, expandedNodes } = this.parseUrl(url);
+
+ if (shouldExpandPreview) {
+ expandedNodes.add(`/${method}`);
+ }
+
+ return div(
+ { className: "url-preview" },
+ PropertiesView({
+ object: urlObject,
+ useQuotes: true,
+ defaultSelectFirstNode: false,
+ mode: MODE.TINY,
+ expandedNodes,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ enableInput: false,
+ onClickRow: (path, evt, member) => {
+ // Only track when the root is toggled
+ // as all the others are always expanded by
+ // default.
+ if (path == `/${method}`) {
+ onTogglePreview(!member.open);
+ }
+ },
+ contextMenuFormatters: {
+ copyFormatter: (member, baseCopyFormatter) => {
+ const { value, level, hasChildren } = member;
+ if (hasChildren && level == 0) {
+ const { scheme, filename, host, query } = value;
+ return `${scheme}://${host}${filename}${
+ query ? "?" + new URLSearchParams(query).toString() : ""
+ }`;
+ }
+ return baseCopyFormatter(member);
+ },
+ },
+ })
+ );
+ }
+}
+
+module.exports = UrlPreview;
diff --git a/devtools/client/netmonitor/src/components/previews/moz.build b/devtools/client/netmonitor/src/components/previews/moz.build
new file mode 100644
index 0000000000..0252ec3246
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/previews/moz.build
@@ -0,0 +1,11 @@
+# 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/.
+
+DevToolsModules(
+ "FontPreview.js",
+ "HtmlPreview.js",
+ "ImagePreview.js",
+ "SourcePreview.js",
+ "UrlPreview.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js b/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js
new file mode 100644
index 0000000000..4d209e788d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js
@@ -0,0 +1,350 @@
+/* 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 {
+ button,
+ div,
+ form,
+ input,
+ label,
+ li,
+ span,
+ ul,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const RequestBlockingContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js");
+
+const ENABLE_BLOCKING_LABEL = L10N.getStr(
+ "netmonitor.actionbar.enableBlocking"
+);
+const ADD_URL_PLACEHOLDER = L10N.getStr(
+ "netmonitor.actionbar.blockSearchPlaceholder"
+);
+const REQUEST_BLOCKING_USAGE_NOTICE = L10N.getStr(
+ "netmonitor.actionbar.requestBlockingUsageNotice"
+);
+const REQUEST_BLOCKING_ADD_NOTICE = L10N.getStr(
+ "netmonitor.actionbar.requestBlockingAddNotice"
+);
+const REMOVE_URL_TOOLTIP = L10N.getStr("netmonitor.actionbar.removeBlockedUrl");
+
+class RequestBlockingPanel extends Component {
+ static get propTypes() {
+ return {
+ blockedUrls: PropTypes.array.isRequired,
+ addBlockedUrl: PropTypes.func.isRequired,
+ isDisplaying: PropTypes.bool.isRequired,
+ removeBlockedUrl: PropTypes.func.isRequired,
+ toggleBlockingEnabled: PropTypes.func.isRequired,
+ toggleBlockedUrl: PropTypes.func.isRequired,
+ updateBlockedUrl: PropTypes.func.isRequired,
+ removeAllBlockedUrls: PropTypes.func.isRequired,
+ disableAllBlockedUrls: PropTypes.func.isRequired,
+ enableAllBlockedUrls: PropTypes.func.isRequired,
+ blockingEnabled: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ editingUrl: null,
+ };
+ }
+
+ componentDidMount() {
+ this.refs.addInput.focus();
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.state.editingUrl) {
+ this.refs.editInput.focus();
+ this.refs.editInput.select();
+ } else if (this.props.isDisplaying && !prevProps.isDisplaying) {
+ this.refs.addInput.focus();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.scrollToBottomTimeout) {
+ clearTimeout(this.scrollToBottomTimeout);
+ }
+ }
+
+ scrollToBottom() {
+ if (this.scrollToBottomTimeout) {
+ clearTimeout(this.scrollToBottomTimeout);
+ }
+ this.scrollToBottomTimeout = setTimeout(() => {
+ const { contents } = this.refs;
+ if (contents.scrollHeight > contents.offsetHeight) {
+ contents.scrollTo({ top: contents.scrollHeight });
+ }
+ }, 40);
+ }
+
+ renderEnableBar() {
+ return div(
+ { className: "request-blocking-enable-bar" },
+ div(
+ { className: "request-blocking-enable-form" },
+ label(
+ { className: "devtools-checkbox-label" },
+ input({
+ type: "checkbox",
+ className: "devtools-checkbox",
+ checked: this.props.blockingEnabled,
+ ref: "enabledCheckbox",
+ onChange: () =>
+ this.props.toggleBlockingEnabled(
+ this.refs.enabledCheckbox.checked
+ ),
+ }),
+ span({ className: "request-blocking-label" }, ENABLE_BLOCKING_LABEL)
+ )
+ )
+ );
+ }
+
+ renderItemContent({ url, enabled }) {
+ const { toggleBlockedUrl, removeBlockedUrl } = this.props;
+
+ return li(
+ { key: url },
+ label(
+ {
+ className: "devtools-checkbox-label",
+ onDoubleClick: () => this.setState({ editingUrl: url }),
+ },
+ input({
+ type: "checkbox",
+ className: "devtools-checkbox",
+ checked: enabled,
+ onChange: () => toggleBlockedUrl(url),
+ }),
+ span(
+ {
+ className: "request-blocking-label request-blocking-editable-label",
+ title: url,
+ },
+ url
+ )
+ ),
+ button({
+ className: "request-blocking-remove-button",
+ title: REMOVE_URL_TOOLTIP,
+ "aria-label": REMOVE_URL_TOOLTIP,
+ onClick: () => removeBlockedUrl(url),
+ })
+ );
+ }
+
+ renderEditForm(url) {
+ const { updateBlockedUrl, removeBlockedUrl } = this.props;
+ return li(
+ { key: url, className: "request-blocking-edit-item" },
+ form(
+ {
+ onSubmit: e => {
+ const { editInput } = this.refs;
+ const newValue = editInput.value;
+ e.preventDefault();
+
+ if (url != newValue) {
+ if (editInput.value.trim() === "") {
+ removeBlockedUrl(url, newValue);
+ } else {
+ updateBlockedUrl(url, newValue);
+ }
+ }
+ this.setState({ editingUrl: null });
+ },
+ },
+ input({
+ type: "text",
+ defaultValue: url,
+ ref: "editInput",
+ className: "devtools-searchinput",
+ placeholder: ADD_URL_PLACEHOLDER,
+ onBlur: () => this.setState({ editingUrl: null }),
+ onKeyDown: e => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ e.preventDefault();
+ this.setState({ editingUrl: null });
+ }
+ },
+ }),
+
+ input({ type: "submit", style: { display: "none" } })
+ )
+ );
+ }
+
+ renderBlockedList() {
+ const {
+ blockedUrls,
+ blockingEnabled,
+ removeAllBlockedUrls,
+ disableAllBlockedUrls,
+ enableAllBlockedUrls,
+ } = this.props;
+
+ if (blockedUrls.length === 0) {
+ return null;
+ }
+
+ const listItems = blockedUrls.map(item =>
+ this.state.editingUrl === item.url
+ ? this.renderEditForm(item.url)
+ : this.renderItemContent(item)
+ );
+
+ return div(
+ {
+ className: "request-blocking-contents",
+ ref: "contents",
+ onContextMenu: event => {
+ if (!this.contextMenu) {
+ this.contextMenu = new RequestBlockingContextMenu({
+ removeAllBlockedUrls,
+ disableAllBlockedUrls,
+ enableAllBlockedUrls,
+ });
+ }
+
+ const contextMenuOptions = {
+ disableDisableAllBlockedUrls: blockedUrls.every(
+ ({ enabled }) => enabled === false
+ ),
+ disableEnableAllBlockedUrls: blockedUrls.every(
+ ({ enabled }) => enabled === true
+ ),
+ };
+
+ this.contextMenu.open(event, contextMenuOptions);
+ },
+ },
+ ul(
+ {
+ className: `request-blocking-list ${
+ blockingEnabled ? "" : "disabled"
+ }`,
+ },
+ ...listItems
+ )
+ );
+ }
+
+ renderAddForm() {
+ const { addBlockedUrl } = this.props;
+ return div(
+ { className: "request-blocking-footer" },
+ form(
+ {
+ className: "request-blocking-add-form",
+ onSubmit: e => {
+ const { addInput } = this.refs;
+ e.preventDefault();
+ addBlockedUrl(addInput.value);
+ addInput.value = "";
+ addInput.focus();
+ this.scrollToBottom();
+ },
+ },
+ input({
+ type: "text",
+ ref: "addInput",
+ className: "devtools-searchinput",
+ placeholder: ADD_URL_PLACEHOLDER,
+ onKeyDown: e => {
+ if (e.key === "Escape") {
+ e.stopPropagation();
+ e.preventDefault();
+
+ const { addInput } = this.refs;
+ addInput.value = "";
+ addInput.focus();
+ }
+ },
+ }),
+ input({ type: "submit", style: { display: "none" } })
+ )
+ );
+ }
+
+ renderEmptyListNotice() {
+ return div(
+ { className: "request-blocking-list-empty-notice" },
+ div(
+ { className: "request-blocking-notice-element" },
+ REQUEST_BLOCKING_USAGE_NOTICE
+ ),
+ div(
+ { className: "request-blocking-notice-element" },
+ REQUEST_BLOCKING_ADD_NOTICE
+ )
+ );
+ }
+
+ render() {
+ const { blockedUrls, addBlockedUrl } = this.props;
+
+ return div(
+ {
+ className: "request-blocking-panel",
+ onDragOver: e => {
+ e.preventDefault();
+ },
+ onDrop: e => {
+ e.preventDefault();
+ const url = e.dataTransfer.getData("text/plain");
+ addBlockedUrl(url);
+ this.scrollToBottom();
+ },
+ },
+ this.renderEnableBar(),
+ this.renderBlockedList(),
+ this.renderAddForm(),
+ !blockedUrls.length && this.renderEmptyListNotice()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ blockedUrls: state.requestBlocking.blockedUrls,
+ blockingEnabled: state.requestBlocking.blockingEnabled,
+ isDisplaying: state.ui.selectedActionBarTabId === PANELS.BLOCKING,
+ }),
+ dispatch => ({
+ toggleBlockingEnabled: checked =>
+ dispatch(Actions.toggleBlockingEnabled(checked)),
+ addBlockedUrl: url => dispatch(Actions.addBlockedUrl(url)),
+ removeBlockedUrl: url => dispatch(Actions.removeBlockedUrl(url)),
+ toggleBlockedUrl: url => dispatch(Actions.toggleBlockedUrl(url)),
+ removeAllBlockedUrls: () => dispatch(Actions.removeAllBlockedUrls()),
+ enableAllBlockedUrls: () => dispatch(Actions.enableAllBlockedUrls()),
+ disableAllBlockedUrls: () => dispatch(Actions.disableAllBlockedUrls()),
+ updateBlockedUrl: (oldUrl, newUrl) =>
+ dispatch(Actions.updateBlockedUrl(oldUrl, newUrl)),
+ })
+)(RequestBlockingPanel);
diff --git a/devtools/client/netmonitor/src/components/request-blocking/moz.build b/devtools/client/netmonitor/src/components/request-blocking/moz.build
new file mode 100644
index 0000000000..7ce0f7ecc6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-blocking/moz.build
@@ -0,0 +1,7 @@
+# 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/.
+
+DevToolsModules(
+ "RequestBlockingPanel.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-details/CachePanel.js b/devtools/client/netmonitor/src/components/request-details/CachePanel.js
new file mode 100644
index 0000000000..5f3db6c501
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/CachePanel.js
@@ -0,0 +1,144 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+
+const { div, input } = dom;
+
+const CACHE = L10N.getStr("netmonitor.cache.cache");
+const DATA_SIZE = L10N.getStr("netmonitor.cache.dataSize");
+const EXPIRES = L10N.getStr("netmonitor.cache.expires");
+const FETCH_COUNT = L10N.getStr("netmonitor.cache.fetchCount");
+const LAST_FETCHED = L10N.getStr("netmonitor.cache.lastFetched");
+const LAST_MODIFIED = L10N.getStr("netmonitor.cache.lastModified");
+const DEVICE = L10N.getStr("netmonitor.cache.device");
+const NOT_AVAILABLE = L10N.getStr("netmonitor.cache.notAvailable");
+const EMPTY = L10N.getStr("netmonitor.cache.empty");
+
+/**
+ * Cache panel component
+ * This tab lists full details of any cache information of the response.
+ */
+class CachePanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["responseCache"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["responseCache"]);
+ }
+
+ renderSummary(label, value) {
+ return div(
+ { className: "tabpanel-summary-container cache-summary" },
+ div(
+ {
+ className: "tabpanel-summary-label cache-summary-label",
+ },
+ label + ":"
+ ),
+ input({
+ className: "tabpanel-summary-value textbox-input devtools-monospace",
+ readOnly: true,
+ value,
+ })
+ );
+ }
+
+ getProperties(responseCache) {
+ let responseCacheObj;
+ let cacheObj;
+ try {
+ responseCacheObj = Object.assign({}, responseCache);
+ responseCacheObj = responseCacheObj.cache;
+ } catch (e) {
+ return null;
+ }
+ try {
+ cacheObj = Object.assign({}, responseCacheObj);
+ } catch (e) {
+ return null;
+ }
+ return cacheObj;
+ }
+
+ getDate(timestamp) {
+ if (!timestamp) {
+ return null;
+ }
+ const d = new Date(parseInt(timestamp, 10) * 1000);
+ return d.toLocaleDateString() + " " + d.toLocaleTimeString();
+ }
+
+ render() {
+ const { request } = this.props;
+ const { responseCache } = request;
+
+ let object;
+ const cache = this.getProperties(responseCache);
+
+ if (
+ cache.lastFetched ||
+ cache.fetchCount ||
+ cache.storageDataSize ||
+ cache.lastModified ||
+ cache.expirationTime ||
+ cache.deviceID
+ ) {
+ object = {
+ [CACHE]: {
+ [LAST_FETCHED]: this.getDate(cache.lastFetched) || NOT_AVAILABLE,
+ [FETCH_COUNT]: cache.fetchCount || NOT_AVAILABLE,
+ [DATA_SIZE]: cache.storageDataSize || NOT_AVAILABLE,
+ [LAST_MODIFIED]: this.getDate(cache.lastModified) || NOT_AVAILABLE,
+ [EXPIRES]: this.getDate(cache.expirationTime) || NOT_AVAILABLE,
+ [DEVICE]: cache.deviceID || NOT_AVAILABLE,
+ },
+ };
+ } else {
+ return div({ className: "empty-notice" }, EMPTY);
+ }
+
+ return div(
+ { className: "panel-container security-panel" },
+ PropertiesView({
+ object,
+ enableFilter: false,
+ expandedNodes: TreeViewClass.getExpandedNodes(object),
+ })
+ );
+ }
+}
+
+module.exports = CachePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js b/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js
new file mode 100644
index 0000000000..466c0379cd
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/CookiesPanel.js
@@ -0,0 +1,225 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ sortObjectKeys,
+} = require("resource://devtools/client/netmonitor/src/utils/sort-utils.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Component
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+const Accordion = createFactory(
+ require("resource://devtools/client/shared/components/Accordion.js")
+);
+
+loader.lazyGetter(this, "TreeRow", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+ );
+});
+
+const { div } = dom;
+
+const COOKIES_EMPTY_TEXT = L10N.getStr("cookiesEmptyText");
+const COOKIES_FILTER_TEXT = L10N.getStr("cookiesFilterText");
+const REQUEST_COOKIES = L10N.getStr("requestCookies");
+const RESPONSE_COOKIES = L10N.getStr("responseCookies");
+
+/*
+ * Cookies panel component
+ * This tab lists full details of any cookies sent with the request or response
+ */
+class CookiesPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ filterText: "",
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestCookies",
+ "responseCookies",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestCookies",
+ "responseCookies",
+ ]);
+ }
+
+ /**
+ * Mapping array to dict for TreeView usage.
+ * Since TreeView only support Object(dict) format.
+ *
+ * @param {Object[]} arr - key-value pair array like cookies or params
+ * @returns {Object}
+ */
+ getProperties(arr, title) {
+ const cookies = arr.reduce((map, obj) => {
+ // Generally cookies object contains only name and value properties and can
+ // be rendered as name: value pair.
+ // When there are more properties in cookies object such as extra or path,
+ // We will pass the object to display these extra information
+ if (Object.keys(obj).length > 2) {
+ map[obj.name] = Object.assign({}, obj);
+ delete map[obj.name].name;
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, Object.create(null));
+
+ // To have different roots for Request and Response cookies
+ return { [title]: cookies };
+ }
+
+ /**
+ * Custom rendering method passed to PropertiesView. It's
+ * responsible to filter out level 0 node in the tree
+ *
+ * @param {Object} props
+ */
+ renderRow(props) {
+ const { level } = props.member;
+
+ if (level === 0) {
+ return null;
+ }
+
+ return TreeRow(props);
+ }
+
+ /**
+ * Get the selected cookies path
+ * @param {Object} searchResult
+ * @returns {string}
+ */
+ getTargetCookiePath(searchResult) {
+ if (!searchResult) {
+ return null;
+ }
+
+ switch (searchResult.type) {
+ case "requestCookies": {
+ return `/${REQUEST_COOKIES}/${searchResult.label}`;
+ }
+ case "responseCookies":
+ return `/${RESPONSE_COOKIES}/${searchResult.label}`;
+ }
+
+ return null;
+ }
+
+ render() {
+ let {
+ request: {
+ requestCookies = { cookies: [] },
+ responseCookies = { cookies: [] },
+ },
+ targetSearchResult,
+ } = this.props;
+
+ const { filterText } = this.state;
+
+ requestCookies = requestCookies.cookies || requestCookies;
+ responseCookies = responseCookies.cookies || responseCookies;
+
+ if (!requestCookies.length && !responseCookies.length) {
+ return div({ className: "empty-notice" }, COOKIES_EMPTY_TEXT);
+ }
+
+ const items = [];
+
+ if (responseCookies.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: sortObjectKeys(
+ this.getProperties(responseCookies, RESPONSE_COOKIES)
+ ),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ selectPath: this.getTargetCookiePath,
+ renderRow: this.renderRow,
+ },
+ header: RESPONSE_COOKIES,
+ id: "responseCookies",
+ opened: true,
+ });
+ }
+
+ if (requestCookies.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: sortObjectKeys(
+ this.getProperties(requestCookies, REQUEST_COOKIES)
+ ),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ selectPath: this.getTargetCookiePath,
+ renderRow: this.renderRow,
+ },
+ header: REQUEST_COOKIES,
+ id: "requestCookies",
+ opened: true,
+ });
+ }
+
+ return div(
+ { className: "panel-container cookies-panel-container" },
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: COOKIES_FILTER_TEXT,
+ })
+ ),
+ Accordion({ items })
+ );
+ }
+}
+
+module.exports = CookiesPanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js b/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js
new file mode 100644
index 0000000000..80b9aed27d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/HeadersPanel.js
@@ -0,0 +1,850 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ getFormattedIPAndPort,
+ getFormattedSize,
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getHeadersURL,
+ getTrackingProtectionURL,
+ getHTTPStatusCodeURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+ writeHeaderText,
+ getRequestHeadersRawText,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ HeadersProvider,
+ HeaderList,
+} = require("resource://devtools/client/netmonitor/src/utils/headers-provider.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+const Accordion = createFactory(
+ require("resource://devtools/client/shared/components/Accordion.js")
+);
+const UrlPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/UrlPreview.js")
+);
+const HeadersPanelContextMenu = require("resource://devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js");
+const StatusCode = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusCode.js")
+);
+
+loader.lazyGetter(this, "MDNLink", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+ );
+});
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+loader.lazyGetter(this, "TreeRow", function () {
+ return createFactory(
+ require("resource://devtools/client/shared/components/tree/TreeRow.js")
+ );
+});
+loader.lazyRequireGetter(
+ this,
+ "showMenu",
+ "resource://devtools/client/shared/components/menu/utils.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "openContentLink",
+ "resource://devtools/client/shared/link.js",
+ true
+);
+
+const { div, input, label, span, textarea, tr, td, button } = dom;
+
+const RESEND = L10N.getStr("netmonitor.context.resend.label");
+const EDIT_AND_RESEND = L10N.getStr("netmonitor.summary.editAndResend");
+const RAW_HEADERS = L10N.getStr("netmonitor.headers.raw");
+const HEADERS_EMPTY_TEXT = L10N.getStr("headersEmptyText");
+const HEADERS_FILTER_TEXT = L10N.getStr("headersFilterText");
+const REQUEST_HEADERS = L10N.getStr("requestHeaders");
+const REQUEST_HEADERS_FROM_UPLOAD = L10N.getStr("requestHeadersFromUpload");
+const RESPONSE_HEADERS = L10N.getStr("responseHeaders");
+const HEADERS_STATUS = L10N.getStr("netmonitor.headers.status");
+const HEADERS_VERSION = L10N.getStr("netmonitor.headers.version");
+const HEADERS_TRANSFERRED = L10N.getStr("netmonitor.toolbar.transferred");
+const SUMMARY_STATUS_LEARN_MORE = L10N.getStr("netmonitor.summary.learnMore");
+const SUMMARY_ETP_LEARN_MORE = L10N.getStr(
+ "netmonitor.enhancedTrackingProtection.learnMore"
+);
+const HEADERS_REFERRER = L10N.getStr("netmonitor.headers.referrerPolicy");
+const HEADERS_CONTENT_BLOCKING = L10N.getStr(
+ "netmonitor.headers.contentBlocking"
+);
+const HEADERS_ETP = L10N.getStr(
+ "netmonitor.trackingResource.enhancedTrackingProtection"
+);
+const HEADERS_PRIORITY = L10N.getStr("netmonitor.headers.requestPriority");
+
+/**
+ * Headers panel component
+ * Lists basic information about the request
+ *
+ * In http/2 all response headers are in small case.
+ * See: https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/request_details/index.html#response-headers
+ * RFC: https://tools.ietf.org/html/rfc7540#section-8.1.2
+ */
+class HeadersPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ cloneSelectedRequest: PropTypes.func.isRequired,
+ member: PropTypes.object,
+ request: PropTypes.object.isRequired,
+ renderValue: PropTypes.func,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+ openRequestBlockingAndAddUrl: PropTypes.func.isRequired,
+ openHTTPCustomRequestTab: PropTypes.func.isRequired,
+ cloneRequest: PropTypes.func,
+ sendCustomRequest: PropTypes.func,
+ shouldExpandPreview: PropTypes.bool,
+ setHeadersUrlPreviewExpanded: PropTypes.func,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ rawRequestHeadersOpened: false,
+ rawResponseHeadersOpened: false,
+ rawUploadHeadersOpened: false,
+ lastToggledRawHeader: "",
+ filterText: null,
+ };
+
+ this.getProperties = this.getProperties.bind(this);
+ this.getTargetHeaderPath = this.getTargetHeaderPath.bind(this);
+ this.toggleRawResponseHeaders = this.toggleRawResponseHeaders.bind(this);
+ this.toggleRawRequestHeaders = this.toggleRawRequestHeaders.bind(this);
+ this.toggleRawUploadHeaders = this.toggleRawUploadHeaders.bind(this);
+ this.renderSummary = this.renderSummary.bind(this);
+ this.renderRow = this.renderRow.bind(this);
+ this.renderValue = this.renderValue.bind(this);
+ this.renderRawHeadersBtn = this.renderRawHeadersBtn.bind(this);
+ this.onShowResendMenu = this.onShowResendMenu.bind(this);
+ this.onShowHeadersContextMenu = this.onShowHeadersContextMenu.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestHeaders",
+ "responseHeaders",
+ "requestPostData",
+ ]);
+ }
+
+ getHeadersTitle(headers, title) {
+ let result = "";
+ let preHeaderText = "";
+ const {
+ responseHeaders,
+ requestHeaders,
+ httpVersion,
+ status,
+ statusText,
+ method,
+ urlDetails,
+ } = this.props.request;
+ if (headers?.headers.length) {
+ if (!headers.headersSize) {
+ if (title == RESPONSE_HEADERS) {
+ preHeaderText = `${httpVersion} ${status} ${statusText}`;
+ result = `${title} (${getFormattedSize(
+ writeHeaderText(responseHeaders.headers, preHeaderText).length,
+ 3
+ )})`;
+ } else {
+ const hostHeader = requestHeaders.headers.find(
+ ele => ele.name === "Host"
+ );
+ if (hostHeader) {
+ preHeaderText = `${method} ${
+ urlDetails.url.split(hostHeader.value)[1]
+ } ${httpVersion}`;
+ }
+ result = `${title} (${getFormattedSize(
+ writeHeaderText(requestHeaders.headers, preHeaderText).length,
+ 3
+ )})`;
+ }
+ } else {
+ result = `${title} (${getFormattedSize(headers.headersSize, 3)})`;
+ }
+ }
+
+ return result;
+ }
+
+ getProperties(headers, title) {
+ let propertiesResult;
+
+ if (headers?.headers.length) {
+ const headerKey = this.getHeadersTitle(headers, title);
+ propertiesResult = {
+ [headerKey]: new HeaderList(headers.headers),
+ };
+ if (
+ (title === RESPONSE_HEADERS && this.state.rawResponseHeadersOpened) ||
+ (title === REQUEST_HEADERS && this.state.rawRequestHeadersOpened) ||
+ (title === REQUEST_HEADERS_FROM_UPLOAD &&
+ this.state.rawUploadHeadersOpened)
+ ) {
+ propertiesResult = {
+ [headerKey]: { RAW_HEADERS_ID: headers.rawHeaders },
+ };
+ }
+ }
+ return propertiesResult;
+ }
+
+ toggleRawResponseHeaders() {
+ this.setState({
+ rawResponseHeadersOpened: !this.state.rawResponseHeadersOpened,
+ lastToggledRawHeader: "response",
+ });
+ }
+
+ toggleRawRequestHeaders() {
+ this.setState({
+ rawRequestHeadersOpened: !this.state.rawRequestHeadersOpened,
+ lastToggledRawHeader: "request",
+ });
+ }
+
+ toggleRawUploadHeaders() {
+ this.setState({
+ rawUploadHeadersOpened: !this.state.rawUploadHeadersOpened,
+ lastToggledRawHeader: "upload",
+ });
+ }
+
+ /**
+ * Helper method to identify what kind of raw header this is.
+ * Information is in the path variable
+ */
+ getRawHeaderType(path) {
+ if (path.includes(RESPONSE_HEADERS)) {
+ return "RESPONSE";
+ }
+ if (path.includes(REQUEST_HEADERS_FROM_UPLOAD)) {
+ return "UPLOAD";
+ }
+ return "REQUEST";
+ }
+
+ /**
+ * Renders the top part of the headers detail panel - Summary.
+ */
+ renderSummary(summaryLabel, value) {
+ return div(
+ {
+ key: summaryLabel,
+ className: "tabpanel-summary-container headers-summary",
+ },
+ span(
+ { className: "tabpanel-summary-label headers-summary-label" },
+ summaryLabel
+ ),
+ span({ className: "tabpanel-summary-value" }, value)
+ );
+ }
+
+ /**
+ * Get path for target header if it's set. It's used to select
+ * the header automatically within the tree of headers.
+ * Note that the target header is set by the Search panel.
+ */
+ getTargetHeaderPath(searchResult) {
+ if (!searchResult) {
+ return null;
+ }
+ if (
+ searchResult.type !== "requestHeaders" &&
+ searchResult.type !== "responseHeaders" &&
+ searchResult.type !== "requestHeadersFromUploadStream"
+ ) {
+ return null;
+ }
+ const {
+ request: {
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ },
+ } = this.props;
+ // Using `HeaderList` ensures that we'll get the same
+ // header index as it's used in the tree.
+ const getPath = (headers, title) => {
+ return (
+ "/" +
+ this.getHeadersTitle(headers, title) +
+ "/" +
+ new HeaderList(headers.headers).headers.findIndex(
+ header => header.name == searchResult.label
+ )
+ );
+ };
+ // Calculate target header path according to the header type.
+ switch (searchResult.type) {
+ case "requestHeaders":
+ return getPath(requestHeaders, REQUEST_HEADERS);
+ case "responseHeaders":
+ return getPath(responseHeaders, RESPONSE_HEADERS);
+ case "requestHeadersFromUploadStream":
+ return getPath(uploadHeaders, REQUEST_HEADERS_FROM_UPLOAD);
+ }
+ return null;
+ }
+
+ /**
+ * Custom rendering method passed to PropertiesView. It's responsible
+ * for rendering <textarea> element with raw headers data.
+ */
+ renderRow(props) {
+ const { level, path } = props.member;
+
+ const {
+ request: {
+ method,
+ httpVersion,
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ status,
+ statusText,
+ urlDetails,
+ },
+ } = this.props;
+
+ let value;
+ let preHeaderText = "";
+ if (path.includes("RAW_HEADERS_ID")) {
+ const rawHeaderType = this.getRawHeaderType(path);
+ switch (rawHeaderType) {
+ case "REQUEST":
+ value = getRequestHeadersRawText(
+ method,
+ httpVersion,
+ requestHeaders,
+ urlDetails
+ );
+ break;
+ case "RESPONSE":
+ preHeaderText = `${httpVersion} ${status} ${statusText}`;
+ value = writeHeaderText(
+ responseHeaders.headers,
+ preHeaderText
+ ).trim();
+ break;
+ case "UPLOAD":
+ value = writeHeaderText(uploadHeaders.headers, preHeaderText).trim();
+ break;
+ }
+
+ let rows;
+ if (value) {
+ const match = value.match(/\n/g);
+ rows = match !== null ? match.length : 0;
+ // Need to add 1 for the horizontal scrollbar
+ // not to cover the last row of raw data
+ rows = rows + 1;
+ }
+
+ return tr(
+ {
+ key: path,
+ role: "treeitem",
+ className: "raw-headers-container",
+ onClick: event => {
+ event.stopPropagation();
+ },
+ },
+ td(
+ {
+ colSpan: 2,
+ },
+ textarea({
+ className: "raw-headers",
+ rows,
+ value,
+ readOnly: true,
+ })
+ )
+ );
+ }
+
+ if (level !== 1) {
+ return null;
+ }
+
+ return TreeRow(props);
+ }
+
+ renderRawHeadersBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawHeadersBtn`,
+ className: "raw-headers-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "headers-summary-label" }, RAW_HEADERS),
+ span(
+ { className: "raw-headers-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderValue(props) {
+ const { member, value } = props;
+
+ if (typeof value !== "string") {
+ return null;
+ }
+
+ const headerDocURL = getHeadersURL(member.name);
+
+ return div(
+ { className: "treeValueCellDivider" },
+ Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text everytime
+ member: Object.assign({}, member, { open: false }),
+ mode: MODE.TINY,
+ noGrip: true,
+ openLink: openContentLink,
+ })
+ ),
+ headerDocURL ? MDNLink({ url: headerDocURL }) : null
+ );
+ }
+
+ getShouldOpen(rawHeader, filterText, targetSearchResult) {
+ return (item, opened) => {
+ // If closed, open panel for these reasons
+ // 1.The raw header is switched on or off
+ // 2.The filter text is set
+ // 3.The search text is set
+ if (
+ (!opened && this.state.lastToggledRawHeader === rawHeader) ||
+ (!opened && filterText) ||
+ (!opened && targetSearchResult)
+ ) {
+ return true;
+ }
+ return !!opened;
+ };
+ }
+
+ onShowResendMenu(event) {
+ const {
+ request: { id },
+ cloneSelectedRequest,
+ cloneRequest,
+ sendCustomRequest,
+ } = this.props;
+ const menuItems = [
+ {
+ label: RESEND,
+ type: "button",
+ click: () => {
+ cloneRequest(id);
+ sendCustomRequest();
+ },
+ },
+ {
+ label: EDIT_AND_RESEND,
+ type: "button",
+ click: evt => {
+ cloneSelectedRequest(evt);
+ },
+ },
+ ];
+
+ showMenu(menuItems, { button: event.target });
+ }
+
+ onShowHeadersContextMenu(event) {
+ if (!this.contextMenu) {
+ this.contextMenu = new HeadersPanelContextMenu();
+ }
+ this.contextMenu.open(event, window.getSelection());
+ }
+
+ render() {
+ const {
+ targetSearchResult,
+ request: {
+ fromCache,
+ fromServiceWorker,
+ httpVersion,
+ method,
+ remoteAddress,
+ remotePort,
+ requestHeaders,
+ requestHeadersFromUploadStream: uploadHeaders,
+ responseHeaders,
+ status,
+ statusText,
+ urlDetails,
+ referrerPolicy,
+ priority,
+ isThirdPartyTrackingResource,
+ contentSize,
+ transferredSize,
+ },
+ openRequestBlockingAndAddUrl,
+ openHTTPCustomRequestTab,
+ shouldExpandPreview,
+ setHeadersUrlPreviewExpanded,
+ } = this.props;
+ const {
+ rawResponseHeadersOpened,
+ rawRequestHeadersOpened,
+ rawUploadHeadersOpened,
+ filterText,
+ } = this.state;
+
+ if (
+ (!requestHeaders || !requestHeaders.headers.length) &&
+ (!uploadHeaders || !uploadHeaders.headers.length) &&
+ (!responseHeaders || !responseHeaders.headers.length)
+ ) {
+ return div({ className: "empty-notice" }, HEADERS_EMPTY_TEXT);
+ }
+
+ const items = [];
+
+ if (responseHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(responseHeaders, RESPONSE_HEADERS),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(responseHeaders, RESPONSE_HEADERS),
+ buttons: this.renderRawHeadersBtn(
+ "response",
+ rawResponseHeadersOpened,
+ this.toggleRawResponseHeaders
+ ),
+ id: "responseHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "response",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ if (requestHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(requestHeaders, REQUEST_HEADERS),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(requestHeaders, REQUEST_HEADERS),
+ buttons: this.renderRawHeadersBtn(
+ "request",
+ rawRequestHeadersOpened,
+ this.toggleRawRequestHeaders
+ ),
+ id: "requestHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "request",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ if (uploadHeaders?.headers.length) {
+ items.push({
+ component: PropertiesView,
+ componentProps: {
+ object: this.getProperties(
+ uploadHeaders,
+ REQUEST_HEADERS_FROM_UPLOAD
+ ),
+ filterText,
+ targetSearchResult,
+ renderRow: this.renderRow,
+ renderValue: this.renderValue,
+ provider: HeadersProvider,
+ selectPath: this.getTargetHeaderPath,
+ defaultSelectFirstNode: false,
+ enableInput: false,
+ useQuotes: false,
+ },
+ header: this.getHeadersTitle(
+ uploadHeaders,
+ REQUEST_HEADERS_FROM_UPLOAD
+ ),
+ buttons: this.renderRawHeadersBtn(
+ "upload",
+ rawUploadHeadersOpened,
+ this.toggleRawUploadHeaders
+ ),
+ id: "uploadHeaders",
+ opened: true,
+ shouldOpen: this.getShouldOpen(
+ "upload",
+ filterText,
+ targetSearchResult
+ ),
+ });
+ }
+
+ const sizeText = L10N.getFormatStrWithNumbers(
+ "netmonitor.headers.sizeDetails",
+ getFormattedSize(transferredSize),
+ getFormattedSize(contentSize)
+ );
+
+ const summarySize = this.renderSummary(HEADERS_TRANSFERRED, sizeText);
+
+ let summaryStatus;
+ if (status) {
+ summaryStatus = div(
+ {
+ key: "headers-summary",
+ className: "tabpanel-summary-container headers-summary",
+ },
+ span(
+ {
+ className: "tabpanel-summary-label headers-summary-label",
+ },
+ HEADERS_STATUS
+ ),
+ span(
+ {
+ className: "tabpanel-summary-value status",
+ "data-code": status,
+ },
+ StatusCode({
+ item: { fromCache, fromServiceWorker, status, statusText },
+ }),
+ statusText,
+ MDNLink({
+ url: getHTTPStatusCodeURL(status),
+ title: SUMMARY_STATUS_LEARN_MORE,
+ })
+ )
+ );
+ }
+
+ let trackingProtectionStatus;
+ let trackingProtectionDetails = "";
+ if (isThirdPartyTrackingResource) {
+ const trackingProtectionDocURL = getTrackingProtectionURL();
+
+ trackingProtectionStatus = this.renderSummary(
+ HEADERS_CONTENT_BLOCKING,
+ div(null, span({ className: "tracking-resource" }), HEADERS_ETP)
+ );
+ trackingProtectionDetails = this.renderSummary(
+ "",
+ div(
+ {
+ key: "tracking-protection",
+ className: "tracking-protection",
+ },
+ L10N.getStr("netmonitor.trackingResource.tooltip"),
+ trackingProtectionDocURL
+ ? MDNLink({
+ url: trackingProtectionDocURL,
+ title: SUMMARY_ETP_LEARN_MORE,
+ })
+ : span({ className: "headers-summary learn-more-link" })
+ )
+ );
+ }
+
+ const summaryVersion = httpVersion
+ ? this.renderSummary(HEADERS_VERSION, httpVersion)
+ : null;
+
+ const summaryReferrerPolicy = referrerPolicy
+ ? this.renderSummary(HEADERS_REFERRER, referrerPolicy)
+ : null;
+
+ const summaryPriority = priority
+ ? this.renderSummary(HEADERS_PRIORITY, getRequestPriorityAsText(priority))
+ : null;
+
+ const summaryItems = [
+ summaryStatus,
+ summaryVersion,
+ summarySize,
+ summaryReferrerPolicy,
+ summaryPriority,
+ trackingProtectionStatus,
+ trackingProtectionDetails,
+ ].filter(summaryItem => summaryItem !== null);
+
+ const newEditAndResendPref = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "headers-panel-container" },
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: HEADERS_FILTER_TEXT,
+ }),
+ span({ className: "devtools-separator" }),
+ button(
+ {
+ id: "block-button",
+ className: "devtools-button",
+ title: L10N.getStr("netmonitor.context.blockURL"),
+ onClick: () => openRequestBlockingAndAddUrl(urlDetails.url),
+ },
+ L10N.getStr("netmonitor.headers.toolbar.block")
+ ),
+ span({ className: "devtools-separator" }),
+ button(
+ {
+ id: "edit-resend-button",
+ className: !newEditAndResendPref
+ ? "devtools-button devtools-dropdown-button"
+ : "devtools-button",
+ title: RESEND,
+ onClick: !newEditAndResendPref
+ ? this.onShowResendMenu
+ : () => {
+ openHTTPCustomRequestTab();
+ },
+ },
+ span({ className: "title" }, RESEND)
+ )
+ ),
+ div(
+ { className: "panel-container" },
+ div(
+ { className: "headers-overview" },
+ UrlPreview({
+ url: urlDetails.url,
+ method,
+ address: remoteAddress
+ ? getFormattedIPAndPort(remoteAddress, remotePort)
+ : null,
+ shouldExpandPreview,
+ onTogglePreview: expanded => setHeadersUrlPreviewExpanded(expanded),
+ }),
+ div(
+ {
+ className: "summary",
+ onContextMenu: this.onShowHeadersContextMenu,
+ },
+ summaryItems
+ )
+ ),
+ Accordion({ items })
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ shouldExpandPreview: state.ui.shouldExpandHeadersUrlPreview,
+ }),
+ (dispatch, props) => ({
+ setHeadersUrlPreviewExpanded: expanded =>
+ dispatch(Actions.setHeadersUrlPreviewExpanded(expanded)),
+ openRequestBlockingAndAddUrl: url =>
+ dispatch(Actions.openRequestBlockingAndAddUrl(url)),
+ openHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(true)),
+ cloneRequest: id => dispatch(Actions.cloneRequest(id)),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ })
+)(HeadersPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js b/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js
new file mode 100644
index 0000000000..8092eedc87
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js
@@ -0,0 +1,106 @@
+/* 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 {
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ getSelectedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+// Components
+loader.lazyGetter(this, "CustomRequestPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/CustomRequestPanel.js")
+ );
+});
+loader.lazyGetter(this, "TabboxPanel", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/TabboxPanel.js")
+ );
+});
+
+const { div } = dom;
+
+/**
+ * Network details panel component
+ */
+function NetworkDetailsBar({
+ connector,
+ activeTabId,
+ cloneSelectedRequest,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ openNetworkDetails,
+ openLink,
+ targetSearchResult,
+}) {
+ if (!request) {
+ return null;
+ }
+
+ const newEditAndResendPref = Services.prefs.getBoolPref(
+ "devtools.netmonitor.features.newEditAndResend"
+ );
+
+ return div(
+ { className: "network-details-bar" },
+ request.isCustom && !newEditAndResendPref
+ ? CustomRequestPanel({
+ connector,
+ request,
+ })
+ : TabboxPanel({
+ activeTabId,
+ cloneSelectedRequest,
+ connector,
+ openLink,
+ request,
+ selectTab,
+ sourceMapURLService,
+ toggleNetworkDetails,
+ openNetworkDetails,
+ targetSearchResult,
+ })
+ );
+}
+
+NetworkDetailsBar.displayName = "NetworkDetailsBar";
+
+NetworkDetailsBar.propTypes = {
+ connector: PropTypes.object.isRequired,
+ activeTabId: PropTypes.string,
+ cloneSelectedRequest: PropTypes.func.isRequired,
+ open: PropTypes.bool,
+ request: PropTypes.object,
+ selectTab: PropTypes.func.isRequired,
+ sourceMapURLService: PropTypes.object,
+ toggleNetworkDetails: PropTypes.func.isRequired,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+};
+
+module.exports = connect(
+ state => ({
+ activeTabId: state.ui.detailsPanelSelectedTab,
+ request: getSelectedRequest(state),
+ targetSearchResult: state.search.targetSearchResult,
+ }),
+ dispatch => ({
+ cloneSelectedRequest: () => dispatch(Actions.cloneSelectedRequest()),
+ selectTab: tabId => dispatch(Actions.selectDetailsPanelTab(tabId)),
+ toggleNetworkDetails: () => dispatch(Actions.toggleNetworkDetails()),
+ openNetworkDetails: open => dispatch(Actions.openNetworkDetails(open)),
+ })
+)(NetworkDetailsBar);
diff --git a/devtools/client/netmonitor/src/components/request-details/PropertiesView.js b/devtools/client/netmonitor/src/components/request-details/PropertiesView.js
new file mode 100644
index 0000000000..759653c1aa
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/PropertiesView.js
@@ -0,0 +1,247 @@
+/* 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/. */
+
+/* eslint-disable react/prop-types */
+
+"use strict";
+
+const {
+ Component,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ setTargetSearchResult,
+} = require("resource://devtools/client/netmonitor/src/actions/search.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const TreeView = createFactory(TreeViewClass);
+const PropertiesViewContextMenu = require("resource://devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js");
+
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+// Constants
+const {
+ AUTO_EXPAND_MAX_LEVEL,
+ AUTO_EXPAND_MAX_NODES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div } = dom;
+
+/**
+ * Properties View component
+ * A scrollable tree view component which provides some useful features for
+ * representing object properties.
+ *
+ * Tree view
+ * Rep
+ */
+class PropertiesView extends Component {
+ static get propTypes() {
+ return {
+ object: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
+ provider: PropTypes.object,
+ enableInput: PropTypes.bool,
+ expandableStrings: PropTypes.bool,
+ expandedNodes: PropTypes.object,
+ useBaseTreeViewExpand: PropTypes.bool,
+ filterText: PropTypes.string,
+ cropLimit: PropTypes.number,
+ targetSearchResult: PropTypes.object,
+ resetTargetSearchResult: PropTypes.func,
+ selectPath: PropTypes.func,
+ mode: PropTypes.symbol,
+ defaultSelectFirstNode: PropTypes.bool,
+ useQuotes: PropTypes.bool,
+ onClickRow: PropTypes.func,
+ contextMenuFormatters: PropTypes.object,
+ };
+ }
+
+ static get defaultProps() {
+ return {
+ enableInput: true,
+ enableFilter: true,
+ expandableStrings: false,
+ cropLimit: 1024,
+ useQuotes: true,
+ contextMenuFormatters: {},
+ useBaseTreeViewExpand: false,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onFilter = this.onFilter.bind(this);
+ this.renderValueWithRep = this.renderValueWithRep.bind(this);
+ this.getSelectedPath = this.getSelectedPath.bind(this);
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The filter text has changed
+ * 3) The user selected another search result target.
+ */
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.object !== nextProps.object ||
+ this.props.filterText !== nextProps.filterText ||
+ (this.props.targetSearchResult !== nextProps.targetSearchResult &&
+ nextProps.targetSearchResult !== null)
+ );
+ }
+
+ onFilter(props) {
+ const { name, value } = props;
+ const { filterText } = this.props;
+
+ if (!filterText) {
+ return true;
+ }
+
+ const jsonString = JSON.stringify({ [name]: value }).toLowerCase();
+ return jsonString.includes(filterText.toLowerCase());
+ }
+
+ getSelectedPath(targetSearchResult) {
+ if (!targetSearchResult) {
+ return null;
+ }
+
+ return `/${targetSearchResult.label}`;
+ }
+
+ /**
+ * If target is selected, let's scroll the content
+ * so the property is visible. This is used for search result navigation,
+ * which happens when the user clicks on a search result.
+ */
+ scrollSelectedIntoView() {
+ const { targetSearchResult, resetTargetSearchResult, selectPath } =
+ this.props;
+ if (!targetSearchResult) {
+ return;
+ }
+
+ const path =
+ typeof selectPath == "function"
+ ? selectPath(targetSearchResult)
+ : this.getSelectedPath(targetSearchResult);
+ const element = document.getElementById(path);
+ if (element) {
+ element.scrollIntoView({ block: "center" });
+ }
+
+ resetTargetSearchResult();
+ }
+
+ onContextMenuRow(member, evt) {
+ evt.preventDefault();
+
+ const { object } = member;
+
+ // Select the right clicked row
+ this.selectRow({ props: { member } });
+
+ // if data exists and can be copied, then show the contextmenu
+ if (typeof object === "object") {
+ if (!this.contextMenu) {
+ this.contextMenu = new PropertiesViewContextMenu({
+ customFormatters: this.props.contextMenuFormatters,
+ });
+ }
+ this.contextMenu.open(evt, window.getSelection(), {
+ member,
+ object: this.props.object,
+ });
+ }
+ }
+
+ renderValueWithRep(props) {
+ const { member } = props;
+
+ /* Hide strings with following conditions
+ * - the `value` object has a `value` property (only happens in Cookies panel)
+ */
+ if (typeof member.value === "object" && member.value?.value) {
+ return null;
+ }
+
+ return Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text every time
+ member: Object.assign({}, member, { open: false }),
+ mode: this.props.mode || MODE.TINY,
+ cropLimit: this.props.cropLimit,
+ noGrip: true,
+ })
+ );
+ }
+
+ render() {
+ const {
+ useBaseTreeViewExpand,
+ expandedNodes,
+ object,
+ renderValue,
+ targetSearchResult,
+ selectPath,
+ } = this.props;
+
+ let currentExpandedNodes;
+ // In the TreeView, when the component is re-rendered
+ // the state of `expandedNodes` is persisted by default
+ // e.g. when you open a node and filter the properties list,
+ // the node remains open.
+ // We have the prop `useBaseTreeViewExpand` to flag when we want to use
+ // this functionality or not.
+ if (!useBaseTreeViewExpand) {
+ currentExpandedNodes =
+ expandedNodes ||
+ TreeViewClass.getExpandedNodes(object, {
+ maxLevel: AUTO_EXPAND_MAX_LEVEL,
+ maxNodes: AUTO_EXPAND_MAX_NODES,
+ });
+ }
+ return div(
+ { className: "properties-view" },
+ div(
+ { className: "tree-container" },
+ TreeView({
+ ...this.props,
+ ref: () => this.scrollSelectedIntoView(),
+ columns: [{ id: "value", width: "100%" }],
+
+ expandedNodes: currentExpandedNodes,
+
+ onFilter: props => this.onFilter(props),
+ renderValue: renderValue || this.renderValueWithRep,
+ onContextMenuRow: this.onContextMenuRow,
+ selected:
+ typeof selectPath == "function"
+ ? selectPath(targetSearchResult)
+ : this.getSelectedPath(targetSearchResult),
+ })
+ )
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ resetTargetSearchResult: () => dispatch(setTargetSearchResult(null)),
+}))(PropertiesView);
diff --git a/devtools/client/netmonitor/src/components/request-details/RequestPanel.js b/devtools/client/netmonitor/src/components/request-details/RequestPanel.js
new file mode 100644
index 0000000000..5306161d2e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/RequestPanel.js
@@ -0,0 +1,301 @@
+/* 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,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ parseFormData,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ sortObjectKeys,
+} = require("resource://devtools/client/netmonitor/src/utils/sort-utils.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ updateFormDataSections,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+loader.lazyGetter(this, "SourcePreview", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/SourcePreview.js")
+ );
+});
+
+const { div, input, label, span, h2 } = dom;
+
+const JSON_SCOPE_NAME = L10N.getStr("jsonScopeName");
+const REQUEST_EMPTY_TEXT = L10N.getStr("paramsNoPayloadText");
+const REQUEST_FILTER_TEXT = L10N.getStr("paramsFilterText");
+const REQUEST_FORM_DATA = L10N.getStr("paramsFormData");
+const REQUEST_POST_PAYLOAD = L10N.getStr("paramsPostPayload");
+const RAW_REQUEST_PAYLOAD = L10N.getStr("netmonitor.request.raw");
+const REQUEST_TRUNCATED = L10N.getStr("requestTruncated");
+
+/**
+ * Params panel component
+ * Displays the GET parameters and POST data of a request
+ */
+class RequestPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ updateRequest: PropTypes.func.isRequired,
+ targetSearchResult: PropTypes.object,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = {
+ filterText: "",
+ rawRequestPayloadDisplayed: !!props.targetSearchResult,
+ };
+
+ this.toggleRawRequestPayload = this.toggleRawRequestPayload.bind(this);
+ this.renderRawRequestPayloadBtn =
+ this.renderRawRequestPayloadBtn.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestPostData",
+ ]);
+ updateFormDataSections(this.props);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "requestPostData",
+ ]);
+ updateFormDataSections(nextProps);
+
+ if (nextProps.targetSearchResult !== null) {
+ this.setState({
+ rawRequestPayloadDisplayed: !!nextProps.targetSearchResult,
+ });
+ }
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The filter text has changed
+ * 2) The display got toggled between formatted and raw data
+ * 3) The user selected another search result target.
+ */
+ shouldComponentUpdate(nextProps, nextState) {
+ return (
+ this.props.request !== nextProps.request ||
+ this.state.filterText !== nextState.filterText ||
+ this.state.rawRequestPayloadDisplayed !==
+ nextState.rawRequestPayloadDisplayed ||
+ this.props.targetSearchResult !== nextProps.targetSearchResult
+ );
+ }
+
+ /**
+ * Mapping array to dict for TreeView usage.
+ * Since TreeView only support Object(dict) format.
+ * This function also deal with duplicate key case
+ * (for multiple selection and query params with same keys)
+ *
+ * This function is not sorting result properties since it can
+ * results in unexpected order of params. See bug 1469533
+ *
+ * @param {Object[]} arr - key-value pair array or form params
+ * @returns {Object} Rep compatible object
+ */
+ getProperties(arr) {
+ return arr.reduce((map, obj) => {
+ const value = map[obj.name];
+ if (value || value === "") {
+ if (typeof value !== "object") {
+ map[obj.name] = [value];
+ }
+ map[obj.name].push(obj.value);
+ } else {
+ map[obj.name] = obj.value;
+ }
+ return map;
+ }, {});
+ }
+
+ toggleRawRequestPayload() {
+ this.setState({
+ rawRequestPayloadDisplayed: !this.state.rawRequestPayloadDisplayed,
+ });
+ }
+
+ renderRawRequestPayloadBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawRequestPayloadBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_REQUEST_PAYLOAD),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderRequestPayload(component, componentProps) {
+ return component(componentProps);
+ }
+
+ render() {
+ const { request, targetSearchResult } = this.props;
+ const { filterText, rawRequestPayloadDisplayed } = this.state;
+ const { formDataSections, mimeType, requestPostData } = request;
+ const postData = requestPostData ? requestPostData.postData?.text : null;
+
+ if ((!formDataSections || formDataSections.length === 0) && !postData) {
+ return div({ className: "empty-notice" }, REQUEST_EMPTY_TEXT);
+ }
+
+ let component;
+ let componentProps;
+ let requestPayloadLabel = REQUEST_POST_PAYLOAD;
+ let hasFormattedDisplay = false;
+
+ let error;
+
+ // Form Data section
+ if (formDataSections && formDataSections.length) {
+ const sections = formDataSections.filter(str => /\S/.test(str)).join("&");
+ component = PropertiesView;
+ componentProps = {
+ object: this.getProperties(parseFormData(sections)),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ };
+ requestPayloadLabel = REQUEST_FORM_DATA;
+ hasFormattedDisplay = true;
+ }
+
+ // Request payload section
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.requestBodyLimit"
+ );
+
+ // Check if the request post data has been truncated from the backend,
+ // in which case no parse should be attempted.
+ if (postData && limit <= postData.length) {
+ error = REQUEST_TRUNCATED;
+ }
+ if (formDataSections && formDataSections.length === 0 && postData) {
+ if (!error) {
+ const jsonParsedPostData = parseJSON(postData);
+ const { json, strippedChars } = jsonParsedPostData;
+ // If XSSI characters were present in the request just display the raw
+ // data because a request should never have XSSI escape characters
+ if (strippedChars) {
+ hasFormattedDisplay = false;
+ } else if (json) {
+ component = PropertiesView;
+ componentProps = {
+ object: sortObjectKeys(json),
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ };
+ requestPayloadLabel = JSON_SCOPE_NAME;
+ hasFormattedDisplay = true;
+ }
+ }
+ }
+
+ if (
+ (!hasFormattedDisplay || this.state.rawRequestPayloadDisplayed) &&
+ postData
+ ) {
+ component = SourcePreview;
+ componentProps = {
+ text: postData,
+ mode: mimeType?.replace(/;.+/, ""),
+ targetSearchResult,
+ };
+ requestPayloadLabel = REQUEST_POST_PAYLOAD;
+ }
+
+ return div(
+ { className: "panel-container" },
+ error && div({ className: "request-error-header", title: error }, error),
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: text => this.setState({ filterText: text }),
+ placeholder: REQUEST_FILTER_TEXT,
+ })
+ ),
+ h2({ className: "data-header", role: "heading" }, [
+ span(
+ {
+ key: "data-label",
+ className: "data-label",
+ },
+ requestPayloadLabel
+ ),
+ hasFormattedDisplay &&
+ this.renderRawRequestPayloadBtn(
+ "request",
+ rawRequestPayloadDisplayed,
+ this.toggleRawRequestPayload
+ ),
+ ]),
+ this.renderRequestPayload(component, componentProps)
+ );
+ }
+}
+
+module.exports = connect(null, dispatch => ({
+ updateRequest: (id, data, batch) =>
+ dispatch(Actions.updateRequest(id, data, batch)),
+}))(RequestPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js b/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js
new file mode 100644
index 0000000000..ac4435ea1d
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/ResponsePanel.js
@@ -0,0 +1,496 @@
+/* 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,
+ createFactory,
+} = 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ decodeUnicodeBase64,
+ fetchNetworkUpdatePacket,
+ parseJSON,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getCORSErrorURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ Filters,
+} = require("resource://devtools/client/netmonitor/src/utils/filter-predicates.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ BLOCKED_REASON_MESSAGES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+const ImagePreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/ImagePreview.js")
+);
+const FontPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/FontPreview.js")
+);
+const SourcePreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/SourcePreview.js")
+);
+const HtmlPreview = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/previews/HtmlPreview.js")
+);
+let {
+ NotificationBox,
+ PriorityLevels,
+} = require("resource://devtools/client/shared/components/NotificationBox.js");
+NotificationBox = createFactory(NotificationBox);
+const MessagesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/messages/MessagesView.js")
+);
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+const { div, input, label, span, h2 } = dom;
+const JSON_SCOPE_NAME = L10N.getStr("jsonScopeName");
+const JSON_FILTER_TEXT = L10N.getStr("jsonFilterText");
+const RESPONSE_PAYLOAD = L10N.getStr("responsePayload");
+const RAW_RESPONSE_PAYLOAD = L10N.getStr("netmonitor.response.raw");
+const HTML_RESPONSE = L10N.getStr("netmonitor.response.html");
+const RESPONSE_EMPTY_TEXT = L10N.getStr("responseEmptyText");
+const RESPONSE_TRUNCATED = L10N.getStr("responseTruncated");
+
+const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view";
+
+/**
+ * Response panel component
+ * Displays the GET parameters and POST data of a request
+ */
+class ResponsePanel extends Component {
+ static get propTypes() {
+ return {
+ request: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ targetSearchResult: PropTypes.object,
+ connector: PropTypes.object.isRequired,
+ showMessagesView: PropTypes.bool,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.state = {
+ filterText: "",
+ rawResponsePayloadDisplayed: !!props.targetSearchResult,
+ };
+
+ this.toggleRawResponsePayload = this.toggleRawResponsePayload.bind(this);
+ this.renderCORSBlockedReason = this.renderCORSBlockedReason.bind(this);
+ this.renderRawResponsePayloadBtn =
+ this.renderRawResponsePayloadBtn.bind(this);
+ this.renderJsonHtmlAndSource = this.renderJsonHtmlAndSource.bind(this);
+ this.handleJSONResponse = this.handleJSONResponse.bind(this);
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseContent",
+ ]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, [
+ "responseContent",
+ ]);
+
+ // If the response contains XSSI stripped chars default to raw view
+ const text = nextProps.request?.responseContent?.content?.text;
+ const xssiStrippedChars = text && parseJSON(text)?.strippedChars;
+ if (xssiStrippedChars && !this.state.rawResponsePayloadDisplayed) {
+ this.toggleRawResponsePayload();
+ }
+
+ if (nextProps.targetSearchResult !== null) {
+ this.setState({
+ rawResponsePayloadDisplayed: !!nextProps.targetSearchResult,
+ });
+ }
+ }
+
+ /**
+ * Update only if:
+ * 1) The rendered object has changed
+ * 2) The user selected another search result target.
+ * 3) Internal state changes
+ */
+ shouldComponentUpdate(nextProps, nextState) {
+ return (
+ this.state !== nextState ||
+ this.props.request !== nextProps.request ||
+ nextProps.targetSearchResult !== null
+ );
+ }
+
+ /**
+ * Handle json, which we tentatively identify by checking the
+ * MIME type for "json" after any word boundary. This works
+ * for the standard "application/json", and also for custom
+ * types like "x-bigcorp-json". Additionally, we also
+ * directly parse the response text content to verify whether
+ * it's json or not, to handle responses incorrectly labeled
+ * as text/plain instead.
+ */
+ handleJSONResponse(mimeType, response) {
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.responseBodyLimit"
+ );
+ const { request } = this.props;
+
+ // Check if the response has been truncated, in which case no parse should
+ // be attempted.
+ if (limit > 0 && limit <= request.responseContent.content.size) {
+ const result = {};
+ result.error = RESPONSE_TRUNCATED;
+ return result;
+ }
+
+ const { json, error, jsonpCallback, strippedChars } = parseJSON(response);
+
+ if (/\bjson/.test(mimeType) || json) {
+ const result = {};
+ // Make sure this is a valid JSON object first. If so, nicely display
+ // the parsing results in a tree view.
+
+ // Valid JSON
+ if (json) {
+ result.json = json;
+ }
+ // Valid JSONP
+ if (jsonpCallback) {
+ result.jsonpCallback = jsonpCallback;
+ }
+ // Malformed JSON
+ if (error) {
+ result.error = "" + error;
+ }
+ // XSSI protection sequence
+ if (strippedChars) {
+ result.strippedChars = strippedChars;
+ }
+
+ return result;
+ }
+
+ return null;
+ }
+
+ renderCORSBlockedReason(blockedReason) {
+ // ensure that the blocked reason is in the CORS range
+ if (
+ typeof blockedReason != "number" ||
+ blockedReason < 1000 ||
+ blockedReason > 1015
+ ) {
+ return null;
+ }
+
+ const blockedMessage = BLOCKED_REASON_MESSAGES[blockedReason];
+ const messageText = L10N.getFormatStr(
+ "netmonitor.headers.blockedByCORS",
+ blockedMessage
+ );
+
+ const learnMoreTooltip = L10N.getStr(
+ "netmonitor.headers.blockedByCORSTooltip"
+ );
+
+ // Create a notifications map with the CORS error notification
+ const notifications = new Map();
+ notifications.set("CORS-error", {
+ label: messageText,
+ value: "CORS-error",
+ image: "",
+ priority: PriorityLevels.PRIORITY_INFO_HIGH,
+ type: "info",
+ eventCallback: e => {},
+ buttons: [
+ {
+ mdnUrl: getCORSErrorURL(blockedReason),
+ label: learnMoreTooltip,
+ },
+ ],
+ });
+
+ return NotificationBox({
+ notifications,
+ displayBorderTop: false,
+ displayBorderBottom: true,
+ displayCloseButton: false,
+ });
+ }
+
+ toggleRawResponsePayload() {
+ this.setState({
+ rawResponsePayloadDisplayed: !this.state.rawResponsePayloadDisplayed,
+ });
+ }
+
+ /**
+ * Pick correct component, componentprops, and other needed data to render
+ * the given response
+ *
+ * @returns {Object} shape:
+ * {component}: React component used to render response
+ * {Object} componetProps: Props passed to component
+ * {Error} error: JSON parsing error
+ * {Object} json: parsed JSON payload
+ * {bool} hasFormattedDisplay: whether the given payload has a formatted
+ * display or if it should be rendered raw
+ * {string} responsePayloadLabel: describes type in response panel
+ * {component} xssiStrippedCharsInfoBox: React component to notifiy users
+ * that XSSI characters were stripped from the response
+ */
+ renderJsonHtmlAndSource() {
+ const { request, targetSearchResult } = this.props;
+ const { responseContent } = request;
+ let { encoding, mimeType, text } = responseContent.content;
+ const { filterText, rawResponsePayloadDisplayed } = this.state;
+
+ // Decode response if it's coming from JSONView.
+ if (mimeType?.includes(JSON_VIEW_MIME_TYPE) && encoding === "base64") {
+ text = decodeUnicodeBase64(text);
+ }
+ const { json, jsonpCallback, error, strippedChars } =
+ this.handleJSONResponse(mimeType, text) || {};
+
+ let component;
+ let componentProps;
+ let xssiStrippedCharsInfoBox;
+ let responsePayloadLabel = RESPONSE_PAYLOAD;
+ let hasFormattedDisplay = false;
+
+ if (json) {
+ if (jsonpCallback) {
+ responsePayloadLabel = L10N.getFormatStr(
+ "jsonpScopeName",
+ jsonpCallback
+ );
+ } else {
+ responsePayloadLabel = JSON_SCOPE_NAME;
+ }
+
+ // If raw response payload is not displayed render xssi info box if
+ // there are stripped chars
+ if (!rawResponsePayloadDisplayed) {
+ xssiStrippedCharsInfoBox =
+ this.renderXssiStrippedCharsInfoBox(strippedChars);
+ } else {
+ xssiStrippedCharsInfoBox = null;
+ }
+
+ component = PropertiesView;
+ componentProps = {
+ object: json,
+ useQuotes: true,
+ filterText,
+ targetSearchResult,
+ defaultSelectFirstNode: false,
+ mode: MODE.LONG,
+ useBaseTreeViewExpand: true,
+ };
+ hasFormattedDisplay = true;
+ } else if (Filters.html(this.props.request)) {
+ // Display HTML
+ responsePayloadLabel = HTML_RESPONSE;
+ component = HtmlPreview;
+ componentProps = { responseContent };
+ hasFormattedDisplay = true;
+ }
+ if (!hasFormattedDisplay || rawResponsePayloadDisplayed) {
+ component = SourcePreview;
+ componentProps = {
+ text,
+ mode: json ? "application/json" : mimeType.replace(/;.+/, ""),
+ targetSearchResult,
+ };
+ }
+ return {
+ component,
+ componentProps,
+ error,
+ hasFormattedDisplay,
+ json,
+ responsePayloadLabel,
+ xssiStrippedCharsInfoBox,
+ };
+ }
+
+ renderRawResponsePayloadBtn(key, checked, onChange) {
+ return [
+ label(
+ {
+ key: `${key}RawResponsePayloadBtn`,
+ className: "raw-data-toggle",
+ htmlFor: `raw-${key}-checkbox`,
+ onClick: event => {
+ // stop the header click event
+ event.stopPropagation();
+ },
+ },
+ span({ className: "raw-data-toggle-label" }, RAW_RESPONSE_PAYLOAD),
+ span(
+ { className: "raw-data-toggle-input" },
+ input({
+ id: `raw-${key}-checkbox`,
+ checked,
+ className: "devtools-checkbox-toggle",
+ onChange,
+ type: "checkbox",
+ })
+ )
+ ),
+ ];
+ }
+
+ renderResponsePayload(component, componentProps) {
+ return component(componentProps);
+ }
+
+ /**
+ * This function takes a string of the XSSI protection characters
+ * removed from a JSON payload and produces a notification component
+ * letting the user know that they were removed
+ *
+ * @param {string} strippedChars: string of XSSI protection characters
+ * removed from JSON payload
+ * @returns {component} NotificationBox component
+ */
+ renderXssiStrippedCharsInfoBox(strippedChars) {
+ if (!strippedChars || this.state.rawRequestPayloadDisplayed) {
+ return null;
+ }
+ const message = L10N.getFormatStr("jsonXssiStripped", strippedChars);
+
+ const notifications = new Map();
+ notifications.set("xssi-string-removed-info-box", {
+ label: message,
+ value: "xssi-string-removed-info-box",
+ image: "",
+ priority: PriorityLevels.PRIORITY_INFO_MEDIUM,
+ type: "info",
+ eventCallback: e => {},
+ buttons: [],
+ });
+
+ return NotificationBox({
+ notifications,
+ displayBorderTop: false,
+ displayBorderBottom: true,
+ displayCloseButton: false,
+ });
+ }
+
+ render() {
+ const { connector, showMessagesView, request } = this.props;
+ const { blockedReason, responseContent, url } = request;
+ const { filterText, rawResponsePayloadDisplayed } = this.state;
+
+ // Display CORS blocked Reason info box
+ const CORSBlockedReasonDetails =
+ this.renderCORSBlockedReason(blockedReason);
+
+ if (showMessagesView) {
+ return MessagesView({ connector });
+ }
+
+ if (
+ !responseContent ||
+ typeof responseContent.content.text !== "string" ||
+ !responseContent.content.text
+ ) {
+ return div(
+ { className: "panel-container" },
+ CORSBlockedReasonDetails,
+ div({ className: "empty-notice" }, RESPONSE_EMPTY_TEXT)
+ );
+ }
+
+ const { encoding, mimeType, text } = responseContent.content;
+
+ if (Filters.images({ mimeType })) {
+ return ImagePreview({ encoding, mimeType, text, url });
+ }
+
+ if (Filters.fonts({ url, mimeType })) {
+ return FontPreview({ connector, mimeType, url });
+ }
+
+ // Get Data needed for formatted display
+ const {
+ component,
+ componentProps,
+ error,
+ hasFormattedDisplay,
+ json,
+ responsePayloadLabel,
+ xssiStrippedCharsInfoBox,
+ } = this.renderJsonHtmlAndSource();
+
+ const classList = ["panel-container"];
+ if (Filters.html(this.props.request)) {
+ classList.push("contains-html-preview");
+ }
+
+ return div(
+ { className: classList.join(" ") },
+ error && div({ className: "response-error-header", title: error }, error),
+ json &&
+ div(
+ { className: "devtools-toolbar devtools-input-toolbar" },
+ SearchBox({
+ delay: FILTER_SEARCH_DELAY,
+ type: "filter",
+ onChange: filter => this.setState({ filterText: filter }),
+ placeholder: JSON_FILTER_TEXT,
+ value: filterText,
+ })
+ ),
+ div({ tabIndex: "0" }, CORSBlockedReasonDetails),
+ h2({ className: "data-header", role: "heading" }, [
+ span(
+ {
+ key: "data-label",
+ className: "data-label",
+ },
+ responsePayloadLabel
+ ),
+ hasFormattedDisplay &&
+ this.renderRawResponsePayloadBtn(
+ "response",
+ rawResponsePayloadDisplayed,
+ this.toggleRawResponsePayload
+ ),
+ ]),
+ xssiStrippedCharsInfoBox,
+ this.renderResponsePayload(component, componentProps)
+ );
+ }
+}
+
+module.exports = ResponsePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js b/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js
new file mode 100644
index 0000000000..74dca02cc8
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/SecurityPanel.js
@@ -0,0 +1,283 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ getUrlHost,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// Components
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const PropertiesView = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-details/PropertiesView.js")
+);
+
+loader.lazyGetter(this, "Rep", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .REPS.Rep;
+});
+loader.lazyGetter(this, "MODE", function () {
+ return require("resource://devtools/client/shared/components/reps/index.js")
+ .MODE;
+});
+
+const { div, span } = dom;
+const NOT_AVAILABLE = L10N.getStr("netmonitor.security.notAvailable");
+const ERROR_LABEL = L10N.getStr("netmonitor.security.error");
+const CIPHER_SUITE_LABEL = L10N.getStr("netmonitor.security.cipherSuite");
+const WARNING_CIPHER_LABEL = L10N.getStr("netmonitor.security.warning.cipher");
+const ENABLED_LABEL = L10N.getStr("netmonitor.security.enabled");
+const DISABLED_LABEL = L10N.getStr("netmonitor.security.disabled");
+const CONNECTION_LABEL = L10N.getStr("netmonitor.security.connection");
+const PROTOCOL_VERSION_LABEL = L10N.getStr(
+ "netmonitor.security.protocolVersion"
+);
+const KEA_GROUP_LABEL = L10N.getStr("netmonitor.security.keaGroup");
+const KEA_GROUP_NONE = L10N.getStr("netmonitor.security.keaGroup.none");
+const KEA_GROUP_CUSTOM = L10N.getStr("netmonitor.security.keaGroup.custom");
+const KEA_GROUP_UNKNOWN = L10N.getStr("netmonitor.security.keaGroup.unknown");
+const SIGNATURE_SCHEME_LABEL = L10N.getStr(
+ "netmonitor.security.signatureScheme"
+);
+const SIGNATURE_SCHEME_NONE = L10N.getStr(
+ "netmonitor.security.signatureScheme.none"
+);
+const SIGNATURE_SCHEME_UNKNOWN = L10N.getStr(
+ "netmonitor.security.signatureScheme.unknown"
+);
+const HSTS_LABEL = L10N.getStr("netmonitor.security.hsts");
+const HPKP_LABEL = L10N.getStr("netmonitor.security.hpkp");
+const CERTIFICATE_LABEL = L10N.getStr("netmonitor.security.certificate");
+const CERTIFICATE_TRANSPARENCY_LABEL = L10N.getStr(
+ "certmgr.certificateTransparency.label"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_COMPLIANT = L10N.getStr(
+ "certmgr.certificateTransparency.status.ok"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_NOT_ENOUGH_SCTS = L10N.getStr(
+ "certmgr.certificateTransparency.status.notEnoughSCTS"
+);
+const CERTIFICATE_TRANSPARENCY_POLICY_NOT_DIVERSE_SCTS = L10N.getStr(
+ "certmgr.certificateTransparency.status.notDiverseSCTS"
+);
+const SUBJECT_INFO_LABEL = L10N.getStr("certmgr.subjectinfo.label");
+const CERT_DETAIL_COMMON_NAME_LABEL = L10N.getStr("certmgr.certdetail.cn");
+const CERT_DETAIL_ORG_LABEL = L10N.getStr("certmgr.certdetail.o");
+const CERT_DETAIL_ORG_UNIT_LABEL = L10N.getStr("certmgr.certdetail.ou");
+const ISSUER_INFO_LABEL = L10N.getStr("certmgr.issuerinfo.label");
+const PERIOD_OF_VALIDITY_LABEL = L10N.getStr("certmgr.periodofvalidity.label");
+const BEGINS_LABEL = L10N.getStr("certmgr.begins");
+const EXPIRES_LABEL = L10N.getStr("certmgr.expires");
+const FINGERPRINTS_LABEL = L10N.getStr("certmgr.fingerprints.label");
+const SHA256_FINGERPRINT_LABEL = L10N.getStr(
+ "certmgr.certdetail.sha256fingerprint"
+);
+const SHA1_FINGERPRINT_LABEL = L10N.getStr(
+ "certmgr.certdetail.sha1fingerprint"
+);
+
+/*
+ * Localize special values for key exchange group name,
+ * certificate signature scheme, and certificate
+ * transparency status.
+ */
+const formatSecurityInfo = securityInfo => {
+ const formattedSecurityInfo = { ...securityInfo };
+
+ const formatters = {
+ keaGroupName: value => {
+ if (value === "none") {
+ return KEA_GROUP_NONE;
+ }
+ if (value === "custom") {
+ return KEA_GROUP_CUSTOM;
+ }
+ if (value === "unknown group") {
+ return KEA_GROUP_UNKNOWN;
+ }
+ return value;
+ },
+ signatureSchemeName: value => {
+ if (value === "none") {
+ return SIGNATURE_SCHEME_NONE;
+ }
+ if (value === "unknown signature") {
+ return SIGNATURE_SCHEME_UNKNOWN;
+ }
+ return value;
+ },
+ certificateTransparency: value => {
+ if (value === 5) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_COMPLIANT;
+ }
+ if (value === 6) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_NOT_ENOUGH_SCTS;
+ }
+ if (value === 7) {
+ return CERTIFICATE_TRANSPARENCY_POLICY_NOT_DIVERSE_SCTS;
+ }
+ return value;
+ },
+ };
+
+ return Object.keys(formatters).reduce((acc, key) => {
+ const formatter = formatters[key];
+ acc[key] = formatter(acc[key]);
+ return acc;
+ }, formattedSecurityInfo);
+};
+
+const getConnectionLabel = securityInfo => ({
+ [PROTOCOL_VERSION_LABEL]: securityInfo.protocolVersion || NOT_AVAILABLE,
+ [CIPHER_SUITE_LABEL]: securityInfo.cipherSuite || NOT_AVAILABLE,
+ [KEA_GROUP_LABEL]: securityInfo.keaGroupName || NOT_AVAILABLE,
+ [SIGNATURE_SCHEME_LABEL]: securityInfo.signatureSchemeName || NOT_AVAILABLE,
+});
+
+const getHostHeaderLabel = securityInfo => ({
+ [HSTS_LABEL]: securityInfo.hsts ? ENABLED_LABEL : DISABLED_LABEL,
+ [HPKP_LABEL]: securityInfo.hpkp ? ENABLED_LABEL : DISABLED_LABEL,
+});
+
+const getCertificateLabel = securityInfo => {
+ const { fingerprint, issuer, subject, validity } = securityInfo.cert;
+
+ return {
+ [SUBJECT_INFO_LABEL]: {
+ [CERT_DETAIL_COMMON_NAME_LABEL]: subject?.commonName || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_LABEL]: subject?.organization || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_UNIT_LABEL]: subject?.organizationUnit || NOT_AVAILABLE,
+ },
+ [ISSUER_INFO_LABEL]: {
+ [CERT_DETAIL_COMMON_NAME_LABEL]: issuer?.commonName || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_LABEL]: issuer?.organization || NOT_AVAILABLE,
+ [CERT_DETAIL_ORG_UNIT_LABEL]: issuer?.organizationUnit || NOT_AVAILABLE,
+ },
+ [PERIOD_OF_VALIDITY_LABEL]: {
+ [BEGINS_LABEL]: validity?.start || NOT_AVAILABLE,
+ [EXPIRES_LABEL]: validity?.end || NOT_AVAILABLE,
+ },
+ [FINGERPRINTS_LABEL]: {
+ [SHA256_FINGERPRINT_LABEL]: fingerprint?.sha256 || NOT_AVAILABLE,
+ [SHA1_FINGERPRINT_LABEL]: fingerprint?.sha1 || NOT_AVAILABLE,
+ },
+ [CERTIFICATE_TRANSPARENCY_LABEL]:
+ securityInfo.certificateTransparency || NOT_AVAILABLE,
+ };
+};
+
+const getObject = ({ securityInfo, url }) => {
+ if (securityInfo.state !== "secure" && securityInfo.state !== "weak") {
+ return {
+ [ERROR_LABEL]: securityInfo.errorMessage || NOT_AVAILABLE,
+ };
+ }
+
+ const HOST_HEADER_LABEL = L10N.getFormatStr(
+ "netmonitor.security.hostHeader",
+ getUrlHost(url)
+ );
+ const formattedSecurityInfo = formatSecurityInfo(securityInfo);
+
+ return {
+ [CONNECTION_LABEL]: getConnectionLabel(formattedSecurityInfo),
+ [HOST_HEADER_LABEL]: getHostHeaderLabel(formattedSecurityInfo),
+ [CERTIFICATE_LABEL]: getCertificateLabel(formattedSecurityInfo),
+ };
+};
+
+/*
+ * Security panel component
+ * If the site is being served over HTTPS, you get an extra tab labeled "Security".
+ * This contains details about the secure connection used including the protocol,
+ * the cipher suite, and certificate details
+ */
+class SecurityPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ openLink: PropTypes.func,
+ request: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { request, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["securityInfo"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["securityInfo"]);
+ }
+
+ renderValue(props, weaknessReasons = []) {
+ const { member, value } = props;
+
+ // Hide object summary
+ if (typeof member.value === "object") {
+ return null;
+ }
+
+ return span(
+ { className: "security-info-value" },
+ member.name === ERROR_LABEL
+ ? // Display multiline text for security error for a label using a rep.
+ value
+ : Rep(
+ Object.assign(props, {
+ // FIXME: A workaround for the issue in StringRep
+ // Force StringRep to crop the text everytime
+ member: Object.assign({}, member, { open: false }),
+ mode: MODE.TINY,
+ cropLimit: 60,
+ noGrip: true,
+ })
+ ),
+ weaknessReasons.includes("cipher") && member.name === CIPHER_SUITE_LABEL
+ ? // Display an extra warning icon after the cipher suite
+ div({
+ id: "security-warning-cipher",
+ className: "security-warning-icon",
+ title: WARNING_CIPHER_LABEL,
+ })
+ : null
+ );
+ }
+
+ render() {
+ const { request } = this.props;
+ const { securityInfo, url } = request;
+
+ if (!securityInfo || !url) {
+ return null;
+ }
+
+ const object = getObject({ securityInfo, url });
+ return div(
+ { className: "panel-container security-panel" },
+ PropertiesView({
+ object,
+ renderValue: props =>
+ this.renderValue(props, securityInfo.weaknessReasons),
+ enableFilter: false,
+ expandedNodes: TreeViewClass.getExpandedNodes(object),
+ })
+ );
+ }
+}
+
+module.exports = SecurityPanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js b/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js
new file mode 100644
index 0000000000..6b01ee27b7
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/StackTracePanel.js
@@ -0,0 +1,81 @@
+/* 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,
+ createFactory,
+} = 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 {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+const { div } = dom;
+
+// Components
+const StackTrace = createFactory(
+ require("resource://devtools/client/shared/components/StackTrace.js")
+);
+
+/**
+ * This component represents a side panel responsible for
+ * rendering stack-trace info for selected request.
+ */
+class StackTracePanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object.isRequired,
+ sourceMapURLService: PropTypes.object,
+ openLink: PropTypes.func,
+ };
+ }
+
+ /**
+ * `componentDidMount` is called when opening the StackTracePanel
+ * for the first time
+ */
+ componentDidMount() {
+ const { request, connector } = this.props;
+ if (!request.stacktrace) {
+ fetchNetworkUpdatePacket(connector.requestData, request, ["stackTrace"]);
+ }
+ }
+
+ /**
+ * `componentWillReceiveProps` is the only method called when
+ * switching between two requests while this panel is displayed.
+ */
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { request, connector } = nextProps;
+ // Only try to fetch the stacktrace if we don't already have the stacktrace yet
+ if (!request.stacktrace) {
+ fetchNetworkUpdatePacket(connector.requestData, request, ["stackTrace"]);
+ }
+ }
+
+ render() {
+ const { connector, openLink, request, sourceMapURLService } = this.props;
+
+ const { stacktrace } = request;
+
+ return div(
+ { className: "panel-container" },
+ StackTrace({
+ stacktrace: stacktrace || [],
+ onViewSourceInDebugger: ({ url, line, column }) => {
+ return connector.viewSourceInDebugger(url, line, column);
+ },
+ sourceMapURLService,
+ openLink,
+ })
+ );
+ }
+}
+
+module.exports = StackTracePanel;
diff --git a/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js b/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js
new file mode 100644
index 0000000000..30053f09ea
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/TimingsPanel.js
@@ -0,0 +1,229 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ Component,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getNetMonitorTimingsURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+const MDNLink = require("resource://devtools/client/shared/components/MdnLink.js");
+
+const { div, span } = dom;
+
+const TIMINGS_END_PADDING = "80px";
+
+/**
+ * Timings panel component
+ * Display timeline bars that shows the total wait time for various stages
+ */
+class TimingsPanel extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ request: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { connector, request } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, request } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, request, ["eventTimings"]);
+ }
+
+ renderServerTimings() {
+ const { serverTimings, totalTime } = this.props.request.eventTimings;
+
+ if (!serverTimings?.length) {
+ return null;
+ }
+
+ return div(
+ {},
+ div(
+ { className: "label-separator" },
+ L10N.getStr("netmonitor.timings.serverTiming")
+ ),
+ ...serverTimings.map(({ name, duration, description }, index) => {
+ const color = name === "total" ? "total" : (index % 3) + 1;
+
+ return div(
+ {
+ key: index,
+ className: "tabpanel-summary-container timings-container server",
+ },
+ span(
+ { className: "tabpanel-summary-label timings-label" },
+ description || name
+ ),
+ div(
+ { className: "requests-list-timings-container" },
+ span({
+ className: "requests-list-timings-offset",
+ style: {
+ width: `calc(${
+ (totalTime - duration) / totalTime
+ } * (100% - ${TIMINGS_END_PADDING})`,
+ },
+ }),
+ span({
+ className: `requests-list-timings-box server-timings-color-${color}`,
+ style: {
+ width: `calc(${
+ duration / totalTime
+ } * (100% - ${TIMINGS_END_PADDING}))`,
+ },
+ }),
+ span(
+ { className: "requests-list-timings-total" },
+ getFormattedTime(duration)
+ )
+ )
+ );
+ })
+ );
+ }
+
+ render() {
+ const { eventTimings, totalTime, startedMs } = this.props.request;
+ const { firstRequestStartedMs } = this.props;
+
+ if (!eventTimings) {
+ return div(
+ {
+ className:
+ "tabpanel-summary-container timings-container empty-notice",
+ },
+ L10N.getStr("netmonitor.timings.noTimings")
+ );
+ }
+
+ const { timings, offsets } = eventTimings;
+ let queuedAt, startedAt, downloadedAt;
+ const isFirstRequestStartedAvailable = firstRequestStartedMs !== null;
+
+ if (isFirstRequestStartedAvailable) {
+ queuedAt = startedMs - firstRequestStartedMs;
+ startedAt = queuedAt + timings.blocked;
+ downloadedAt = queuedAt + totalTime;
+ }
+
+ const timelines = TIMING_KEYS.map((type, idx) => {
+ // Determine the relative offset for each timings box. For example, the
+ // offset of third timings box will be 0 + blocked offset + dns offset
+ // If offsets sent from the backend aren't available calculate it
+ // from the timing info.
+ const offset = offsets
+ ? offsets[type]
+ : TIMING_KEYS.slice(0, idx).reduce(
+ (acc, cur) => acc + timings[cur] || 0,
+ 0
+ );
+
+ const offsetScale = offset / totalTime || 0;
+ const timelineScale = timings[type] / totalTime || 0;
+
+ return div(
+ {
+ key: type,
+ id: `timings-summary-${type}`,
+ className: "tabpanel-summary-container timings-container request",
+ },
+ span(
+ { className: "tabpanel-summary-label timings-label" },
+ L10N.getStr(`netmonitor.timings.${type}`)
+ ),
+ div(
+ { className: "requests-list-timings-container" },
+ span({
+ className: "requests-list-timings-offset",
+ style: {
+ width: `calc(${offsetScale} * (100% - ${TIMINGS_END_PADDING})`,
+ },
+ }),
+ span({
+ className: `requests-list-timings-box ${type}`,
+ style: {
+ width: `calc(${timelineScale} * (100% - ${TIMINGS_END_PADDING}))`,
+ },
+ }),
+ span(
+ { className: "requests-list-timings-total" },
+ getFormattedTime(timings[type])
+ )
+ )
+ );
+ });
+
+ return div(
+ { className: "panel-container" },
+ isFirstRequestStartedAvailable &&
+ div(
+ { className: "timings-overview" },
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.queuedAt",
+ getFormattedTime(queuedAt)
+ )
+ ),
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.startedAt",
+ getFormattedTime(startedAt)
+ )
+ ),
+ span(
+ { className: "timings-overview-item" },
+ L10N.getFormatStr(
+ "netmonitor.timings.downloadedAt",
+ getFormattedTime(downloadedAt)
+ )
+ )
+ ),
+ div(
+ { className: "label-separator" },
+ L10N.getStr("netmonitor.timings.requestTiming")
+ ),
+ timelines,
+ this.renderServerTimings(),
+ MDNLink({
+ url: getNetMonitorTimingsURL(),
+ title: L10N.getStr("netmonitor.timings.learnMore"),
+ })
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ firstRequestStartedMs: state.requests ? state.requests.firstStartedMs : null,
+}))(TimingsPanel);
diff --git a/devtools/client/netmonitor/src/components/request-details/moz.build b/devtools/client/netmonitor/src/components/request-details/moz.build
new file mode 100644
index 0000000000..09896f2de3
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-details/moz.build
@@ -0,0 +1,16 @@
+# 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/.
+
+DevToolsModules(
+ "CachePanel.js",
+ "CookiesPanel.js",
+ "HeadersPanel.js",
+ "NetworkDetailsBar.js",
+ "PropertiesView.js",
+ "RequestPanel.js",
+ "ResponsePanel.js",
+ "SecurityPanel.js",
+ "StackTracePanel.js",
+ "TimingsPanel.js",
+)
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestList.js b/devtools/client/netmonitor/src/components/request-list/RequestList.js
new file mode 100644
index 0000000000..63640e389c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestList.js
@@ -0,0 +1,50 @@
+/* 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 {
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div } = dom;
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+// Components
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusBar.js")
+);
+
+loader.lazyGetter(this, "RequestListContent", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListContent.js")
+ );
+});
+loader.lazyGetter(this, "RequestListEmptyNotice", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js")
+ );
+});
+
+/**
+ * Request panel component
+ */
+function RequestList({ connector, isEmpty }) {
+ return div(
+ { className: "request-list-container" },
+ isEmpty
+ ? RequestListEmptyNotice({ connector })
+ : RequestListContent({ connector }),
+ StatusBar({ connector })
+ );
+}
+
+RequestList.displayName = "RequestList";
+
+RequestList.propTypes = {
+ connector: PropTypes.object.isRequired,
+ isEmpty: PropTypes.bool.isRequired,
+};
+
+module.exports = RequestList;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js
new file mode 100644
index 0000000000..4c20d4aebe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js
@@ -0,0 +1,38 @@
+/* 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 {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+class RequestListColumnContentSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.contentSize !== nextProps.item.contentSize;
+ }
+
+ render() {
+ const { contentSize } = this.props.item;
+ const size =
+ typeof contentSize === "number" ? getFormattedSize(contentSize) : null;
+ return dom.td(
+ { className: "requests-list-column requests-list-size", title: size },
+ size
+ );
+ }
+}
+
+module.exports = RequestListColumnContentSize;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js
new file mode 100644
index 0000000000..0c1431ed60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js
@@ -0,0 +1,61 @@
+/* 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 {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnCookies extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["requestCookies"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["requestCookies"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ let { requestCookies: currRequestCookies = { cookies: [] } } =
+ this.props.item;
+ let { requestCookies: nextRequestCookies = { cookies: [] } } =
+ nextProps.item;
+ currRequestCookies = currRequestCookies.cookies || currRequestCookies;
+ nextRequestCookies = nextRequestCookies.cookies || nextRequestCookies;
+ return currRequestCookies !== nextRequestCookies;
+ }
+
+ render() {
+ let { requestCookies = { cookies: [] } } = this.props.item;
+ requestCookies = requestCookies.cookies || requestCookies;
+ const requestCookiesLength = requestCookies.length
+ ? requestCookies.length
+ : "";
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-cookies",
+ title: requestCookiesLength,
+ },
+ requestCookiesLength
+ );
+ }
+}
+
+module.exports = RequestListColumnCookies;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js
new file mode 100644
index 0000000000..3ca6841da6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js
@@ -0,0 +1,66 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ td,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const SecurityState = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/SecurityState.js")
+);
+
+const UPDATED_DOMAIN_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class RequestListColumnDomain extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_DOMAIN_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ remoteAddress,
+ remotePort,
+ urlDetails: { host, isLocal },
+ } = item;
+
+ const title =
+ host +
+ (remoteAddress
+ ? ` (${getFormattedIPAndPort(remoteAddress, remotePort)})`
+ : "");
+
+ return td(
+ { className: "requests-list-column requests-list-domain", title },
+ SecurityState({ item, onSecurityIconMouseDown, isLocal }),
+ host
+ );
+ }
+}
+
+module.exports = RequestListColumnDomain;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js
new file mode 100644
index 0000000000..f824cdb973
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js
@@ -0,0 +1,91 @@
+/* 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 {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+const UPDATED_FILE_PROPS = ["urlDetails", "waitingTime"];
+
+class RequestListColumnFile extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ slowLimit: PropTypes.number,
+ onWaterfallMouseDown: PropTypes.func,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_FILE_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ item: { urlDetails, waitingTime },
+ slowLimit,
+ onWaterfallMouseDown,
+ } = this.props;
+
+ const originalFileURL = urlDetails.url;
+ const decodedFileURL = urlDetails.unicodeUrl;
+ const ORIGINAL_FILE_URL = L10N.getFormatStr(
+ "netRequest.originalFileURL.tooltip",
+ originalFileURL
+ );
+ const DECODED_FILE_URL = L10N.getFormatStr(
+ "netRequest.decodedFileURL.tooltip",
+ decodedFileURL
+ );
+ const requestedFile = urlDetails.baseNameWithQuery;
+ const fileToolTip =
+ originalFileURL === decodedFileURL
+ ? originalFileURL
+ : ORIGINAL_FILE_URL + "\n\n" + DECODED_FILE_URL;
+
+ const isSlow = slowLimit > 0 && !!waitingTime && waitingTime > slowLimit;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-file",
+ title: fileToolTip,
+ },
+ dom.div({}, requestedFile),
+ isSlow &&
+ dom.div({
+ title: L10N.getFormatStr(
+ "netmonitor.audits.slowIconTooltip",
+ getFormattedTime(waitingTime),
+ getFormattedTime(slowLimit)
+ ),
+ onMouseDown: onWaterfallMouseDown,
+ className: "requests-list-slow-button",
+ })
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ slowLimit: state.ui.slowLimit,
+}))(RequestListColumnFile);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js
new file mode 100644
index 0000000000..0c08387fa1
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js
@@ -0,0 +1,65 @@
+/* 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 {
+ getUrlBaseName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+
+class RequestListColumnInitiator extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.cause !== nextProps.item.cause;
+ }
+
+ render() {
+ const {
+ item: { cause },
+ onInitiatorBadgeMouseDown,
+ } = this.props;
+
+ let initiator = "";
+ let lineNumber = "";
+
+ const lastFrameExists = cause && cause.lastFrame;
+ if (lastFrameExists) {
+ const { filename, lineNumber: _lineNumber } = cause.lastFrame;
+ initiator = getUrlBaseName(filename);
+ lineNumber = ":" + _lineNumber;
+ }
+
+ // Legacy server might send a numeric value. Display it as "unknown"
+ const causeType = typeof cause.type === "string" ? cause.type : "unknown";
+ const causeStr = lastFrameExists ? " (" + causeType + ")" : causeType;
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-initiator",
+ title: initiator + lineNumber + causeStr,
+ },
+ dom.div(
+ {
+ className: "requests-list-initiator-lastframe",
+ onMouseDown: onInitiatorBadgeMouseDown,
+ },
+ dom.span({ className: "requests-list-initiator-filename" }, initiator),
+ dom.span({ className: "requests-list-initiator-line" }, lineNumber)
+ ),
+ dom.div({ className: "requests-list-initiator-cause" }, causeStr)
+ );
+ }
+}
+
+module.exports = RequestListColumnInitiator;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js
new file mode 100644
index 0000000000..08434a76fe
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js
@@ -0,0 +1,33 @@
+/* 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");
+
+class RequestListColumnMethod extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.method !== nextProps.item.method;
+ }
+
+ render() {
+ const { method } = this.props.item;
+ return dom.td(
+ { className: "requests-list-column requests-list-method" },
+ method
+ );
+ }
+}
+
+module.exports = RequestListColumnMethod;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js
new file mode 100644
index 0000000000..56f33ec3de
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js
@@ -0,0 +1,36 @@
+/* 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 {
+ getRequestPriorityAsText,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+class RequestListColumnPriority extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.method !== nextProps.item.method;
+ }
+
+ render() {
+ const { priority } = this.props.item;
+ return dom.td(
+ { className: "requests-list-column" },
+ getRequestPriorityAsText(priority)
+ );
+ }
+}
+
+module.exports = RequestListColumnPriority;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js
new file mode 100644
index 0000000000..d77ad43406
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js
@@ -0,0 +1,43 @@
+/* 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 {
+ getFormattedProtocol,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnProtocol extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ getFormattedProtocol(this.props.item) !==
+ getFormattedProtocol(nextProps.item)
+ );
+ }
+
+ render() {
+ const protocol = getFormattedProtocol(this.props.item);
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-protocol",
+ title: protocol,
+ },
+ protocol
+ );
+ }
+}
+
+module.exports = RequestListColumnProtocol;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js
new file mode 100644
index 0000000000..4fa22aa2b2
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js
@@ -0,0 +1,43 @@
+/* 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 {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+
+class RequestListColumnRemoteIP extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.remoteAddress !== nextProps.item.remoteAddress;
+ }
+
+ render() {
+ const { remoteAddress, remotePort } = this.props.item;
+ const remoteIP = remoteAddress
+ ? getFormattedIPAndPort(remoteAddress, remotePort)
+ : "unknown";
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-remoteip",
+ title: remoteIP,
+ },
+ remoteIP
+ );
+ }
+}
+
+module.exports = RequestListColumnRemoteIP;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js
new file mode 100644
index 0000000000..de02da0bc5
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js
@@ -0,0 +1,59 @@
+/* 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 {
+ getResponseHeader,
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * Renders a response header column in the requests list. The actual
+ * header to show is passed as a prop.
+ */
+class RequestListColumnResponseHeader extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ header: PropTypes.string.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseHeaders"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseHeaders"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ const currHeader = getResponseHeader(this.props.item, this.props.header);
+ const nextHeader = getResponseHeader(nextProps.item, nextProps.header);
+ return currHeader !== nextHeader;
+ }
+
+ render() {
+ const header = getResponseHeader(this.props.item, this.props.header);
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-response-header",
+ title: header,
+ },
+ header
+ );
+ }
+}
+
+module.exports = RequestListColumnResponseHeader;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js
new file mode 100644
index 0000000000..7309a17d60
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js
@@ -0,0 +1,38 @@
+/* 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");
+
+class RequestListColumnScheme extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ this.props.item.urlDetails.scheme !== nextProps.item.urlDetails.scheme
+ );
+ }
+
+ render() {
+ const { urlDetails } = this.props.item;
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-scheme",
+ title: urlDetails.scheme,
+ },
+ urlDetails.scheme
+ );
+ }
+}
+
+module.exports = RequestListColumnScheme;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js
new file mode 100644
index 0000000000..0ee8164411
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js
@@ -0,0 +1,61 @@
+/* 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 {
+ fetchNetworkUpdatePacket,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnSetCookies extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseCookies"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["responseCookies"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ let { responseCookies: currResponseCookies = { cookies: [] } } =
+ this.props.item;
+ let { responseCookies: nextResponseCookies = { cookies: [] } } =
+ nextProps.item;
+ currResponseCookies = currResponseCookies.cookies || currResponseCookies;
+ nextResponseCookies = nextResponseCookies.cookies || nextResponseCookies;
+ return currResponseCookies !== nextResponseCookies;
+ }
+
+ render() {
+ let { responseCookies = { cookies: [] } } = this.props.item;
+ responseCookies = responseCookies.cookies || responseCookies;
+ const responseCookiesLength = responseCookies.length
+ ? responseCookies.length
+ : "";
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-set-cookies",
+ title: responseCookiesLength,
+ },
+ responseCookiesLength
+ );
+ }
+}
+
+module.exports = RequestListColumnSetCookies;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js
new file mode 100644
index 0000000000..180d280b1b
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js
@@ -0,0 +1,39 @@
+/* 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,
+ createFactory,
+} = 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");
+
+// Components
+
+const StatusCode = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/StatusCode.js")
+);
+
+class RequestListColumnStatus extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ render() {
+ const { item } = this.props;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-status",
+ },
+ StatusCode({ item })
+ );
+ }
+}
+
+module.exports = RequestListColumnStatus;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js
new file mode 100644
index 0000000000..4ee35d196f
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js
@@ -0,0 +1,91 @@
+/* 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 {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ fetchNetworkUpdatePacket,
+ getResponseTime,
+ getStartTime,
+ getEndTime,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * This component represents a column displaying selected
+ * timing value. There are following possible values this
+ * column can render:
+ * - Start Time
+ * - End Time
+ * - Response Time
+ * - Duration Time
+ * - Latency Time
+ */
+class RequestListColumnTime extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ item: PropTypes.object.isRequired,
+ type: PropTypes.oneOf(["start", "end", "response", "duration", "latency"])
+ .isRequired,
+ };
+ }
+
+ componentDidMount() {
+ const { item, connector } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { item, connector } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.getTime(this.props) !== this.getTime(nextProps);
+ }
+
+ getTime(props) {
+ const { firstRequestStartedMs, item, type } = props;
+
+ switch (type) {
+ case "start":
+ return getStartTime(item, firstRequestStartedMs);
+ case "end":
+ return getEndTime(item, firstRequestStartedMs);
+ case "response":
+ return getResponseTime(item, firstRequestStartedMs);
+ case "duration":
+ return item.totalTime;
+ case "latency":
+ return item.eventTimings ? item.eventTimings.timings.wait : undefined;
+ }
+
+ return 0;
+ }
+
+ render() {
+ const { type } = this.props;
+ const time = getFormattedTime(this.getTime(this.props));
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-" + type + "-time",
+ title: time,
+ },
+ time
+ );
+ }
+}
+
+module.exports = RequestListColumnTime;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js
new file mode 100644
index 0000000000..63cc7a7009
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js
@@ -0,0 +1,99 @@
+/* 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 {
+ getFormattedSize,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ BLOCKED_REASON_MESSAGES,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const SIZE_CACHED = L10N.getStr("networkMenu.sizeCached");
+const SIZE_SERVICE_WORKER = L10N.getStr("networkMenu.sizeServiceWorker");
+const SIZE_UNAVAILABLE = L10N.getStr("networkMenu.sizeUnavailable");
+const SIZE_UNAVAILABLE_TITLE = L10N.getStr("networkMenu.sizeUnavailable.title");
+const UPDATED_TRANSFERRED_PROPS = [
+ "transferredSize",
+ "fromCache",
+ "isRacing",
+ "fromServiceWorker",
+];
+
+class RequestListColumnTransferredSize extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_TRANSFERRED_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ blockedReason,
+ blockingExtension,
+ fromCache,
+ fromServiceWorker,
+ status,
+ transferredSize,
+ isRacing,
+ } = this.props.item;
+ let text;
+
+ if (blockedReason && blockingExtension) {
+ text = L10N.getFormatStr("networkMenu.blockedby", blockingExtension);
+ } else if (blockedReason) {
+ // If we receive a platform error code, print it as-is
+ if (typeof blockedReason == "string" && blockedReason.startsWith("NS_")) {
+ text = blockedReason;
+ } else {
+ text =
+ BLOCKED_REASON_MESSAGES[blockedReason] ||
+ L10N.getStr("networkMenu.blocked2");
+ }
+ } else if (fromCache || status === "304") {
+ text = SIZE_CACHED;
+ } else if (fromServiceWorker) {
+ text = SIZE_SERVICE_WORKER;
+ } else if (typeof transferredSize == "number") {
+ text = getFormattedSize(transferredSize);
+ if (isRacing && typeof isRacing == "boolean") {
+ text = L10N.getFormatStr("networkMenu.raced", text);
+ }
+ } else if (transferredSize === null) {
+ text = SIZE_UNAVAILABLE;
+ }
+
+ const title = text == SIZE_UNAVAILABLE ? SIZE_UNAVAILABLE_TITLE : text;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-transferred",
+ title,
+ },
+ text
+ );
+ }
+}
+
+module.exports = RequestListColumnTransferredSize;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js
new file mode 100644
index 0000000000..783245dc19
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js
@@ -0,0 +1,45 @@
+/* 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 {
+ getAbbreviatedMimeType,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+class RequestListColumnType extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return this.props.item.mimeType !== nextProps.item.mimeType;
+ }
+
+ render() {
+ const { mimeType } = this.props.item;
+ let abbrevType;
+
+ if (mimeType) {
+ abbrevType = getAbbreviatedMimeType(mimeType);
+ }
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-type",
+ title: mimeType,
+ },
+ abbrevType
+ );
+ }
+}
+
+module.exports = RequestListColumnType;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js
new file mode 100644
index 0000000000..9782e9e820
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js
@@ -0,0 +1,89 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ td,
+} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ getFormattedIPAndPort,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const SecurityState = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/SecurityState.js")
+);
+const UPDATED_FILE_PROPS = ["remoteAddress", "securityState", "urlDetails"];
+
+class RequestListColumnUrl extends Component {
+ static get propTypes() {
+ return {
+ item: PropTypes.object.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ };
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return !propertiesEqual(
+ UPDATED_FILE_PROPS,
+ this.props.item,
+ nextProps.item
+ );
+ }
+
+ render() {
+ const {
+ item: { urlDetails },
+ } = this.props;
+
+ const { item, onSecurityIconMouseDown } = this.props;
+
+ const {
+ remoteAddress,
+ remotePort,
+ urlDetails: { isLocal },
+ } = item;
+
+ const title = remoteAddress
+ ? ` (${getFormattedIPAndPort(remoteAddress, remotePort)})`
+ : "";
+
+ // deals with returning whole url
+ const originalURL = urlDetails.url;
+ const decodedFileURL = urlDetails.unicodeUrl;
+ const ORIGINAL_FILE_URL = L10N.getFormatStr(
+ "netRequest.originalFileURL.tooltip",
+ originalURL
+ );
+ const DECODED_FILE_URL = L10N.getFormatStr(
+ "netRequest.decodedFileURL.tooltip",
+ decodedFileURL
+ );
+ const urlToolTip =
+ originalURL === decodedFileURL
+ ? originalURL
+ : ORIGINAL_FILE_URL + "\n\n" + DECODED_FILE_URL;
+
+ return td(
+ {
+ className: "requests-list-column requests-list-url",
+ title: urlToolTip + title,
+ },
+ SecurityState({ item, onSecurityIconMouseDown, isLocal }),
+ originalURL
+ );
+ }
+}
+
+module.exports = RequestListColumnUrl;
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js b/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js
new file mode 100644
index 0000000000..19523399b6
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js
@@ -0,0 +1,209 @@
+/* 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ getWaterfallScale,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ fetchNetworkUpdatePacket,
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+// List of properties of the timing info we want to create boxes for
+const {
+ TIMING_KEYS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+const { div } = dom;
+
+const UPDATED_WATERFALL_ITEM_PROPS = ["eventTimings", "totalTime"];
+const UPDATED_WATERFALL_PROPS = [
+ "item",
+ "firstRequestStartedMs",
+ "scale",
+ "isVisible",
+];
+
+class RequestListColumnWaterfall extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ item: PropTypes.object.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ scale: PropTypes.number,
+ isVisible: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor() {
+ super();
+ this.handleMouseOver = this.handleMouseOver.bind(this);
+ }
+
+ componentDidMount() {
+ const { connector, item } = this.props;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ if (nextProps.isVisible && nextProps.item.totalTime) {
+ const { connector, item } = nextProps;
+ fetchNetworkUpdatePacket(connector.requestData, item, ["eventTimings"]);
+ }
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ nextProps.isVisible &&
+ (!propertiesEqual(UPDATED_WATERFALL_PROPS, this.props, nextProps) ||
+ !propertiesEqual(
+ UPDATED_WATERFALL_ITEM_PROPS,
+ this.props.item,
+ nextProps.item
+ ))
+ );
+ }
+
+ handleMouseOver({ target }) {
+ if (!target.title) {
+ target.title = this.timingTooltip();
+ }
+ }
+
+ timingTooltip() {
+ const { eventTimings, totalTime } = this.props.item;
+ const tooltip = [];
+
+ if (eventTimings) {
+ for (const key of TIMING_KEYS) {
+ const width = eventTimings.timings[key];
+
+ if (width > 0) {
+ tooltip.push(
+ L10N.getFormatStr("netmonitor.waterfall.tooltip." + key, width)
+ );
+ }
+ }
+ }
+
+ if (typeof totalTime === "number") {
+ tooltip.push(
+ L10N.getFormatStr("netmonitor.waterfall.tooltip.total", totalTime)
+ );
+ }
+
+ return tooltip.join(L10N.getStr("netmonitor.waterfall.tooltip.separator"));
+ }
+
+ timingBoxes() {
+ const {
+ scale,
+ item: { eventTimings, totalTime },
+ } = this.props;
+ const boxes = [];
+
+ // Physical pixel as minimum size
+ const minPixel = 1 / window.devicePixelRatio;
+
+ if (typeof totalTime === "number") {
+ if (eventTimings) {
+ // Add a set of boxes representing timing information.
+ for (const key of TIMING_KEYS) {
+ if (eventTimings.timings[key] > 0) {
+ boxes.push(
+ div({
+ key,
+ className: `requests-list-timings-box ${key}`,
+ style: {
+ width: Math.max(eventTimings.timings[key] * scale, minPixel),
+ },
+ })
+ );
+ }
+ }
+ }
+ // Minimal box to at least show start and total time
+ if (!boxes.length) {
+ boxes.push(
+ div({
+ className: "requests-list-timings-box filler",
+ key: "filler",
+ style: { width: Math.max(totalTime * scale, minPixel) },
+ })
+ );
+ }
+
+ const title = L10N.getFormatStr("networkMenu.totalMS2", totalTime);
+ boxes.push(
+ div(
+ {
+ key: "total",
+ className: "requests-list-timings-total",
+ title,
+ },
+ title
+ )
+ );
+ } else {
+ // Pending requests are marked for start time
+ boxes.push(
+ div({
+ className: "requests-list-timings-box filler",
+ key: "pending",
+ style: { width: minPixel },
+ })
+ );
+ }
+
+ return boxes;
+ }
+
+ render() {
+ const {
+ firstRequestStartedMs,
+ item: { startedMs },
+ scale,
+ onWaterfallMouseDown,
+ } = this.props;
+
+ return dom.td(
+ {
+ className: "requests-list-column requests-list-waterfall",
+ onMouseOver: this.handeMouseOver,
+ },
+ div(
+ {
+ className: "requests-list-timings",
+ style: {
+ paddingInlineStart: `${
+ (startedMs - firstRequestStartedMs) * scale
+ }px`,
+ },
+ onMouseDown: onWaterfallMouseDown,
+ },
+ this.timingBoxes()
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ scale: getWaterfallScale(state),
+}))(RequestListColumnWaterfall);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListContent.js b/devtools/client/netmonitor/src/components/request-list/RequestListContent.js
new file mode 100644
index 0000000000..0ee91cc48e
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListContent.js
@@ -0,0 +1,524 @@
+/* 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,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ HTMLTooltip,
+} = require("resource://devtools/client/shared/widgets/tooltip/HTMLTooltip.js");
+
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ formDataURI,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ getDisplayedRequests,
+ getColumns,
+ getSelectedRequest,
+ getClickedRequest,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+
+loader.lazyRequireGetter(
+ this,
+ "openRequestInTab",
+ "resource://devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js",
+ true
+);
+loader.lazyGetter(this, "setImageTooltip", function () {
+ return require("resource://devtools/client/shared/widgets/tooltip/ImageTooltipHelper.js")
+ .setImageTooltip;
+});
+loader.lazyGetter(this, "getImageDimensions", function () {
+ return require("resource://devtools/client/shared/widgets/tooltip/ImageTooltipHelper.js")
+ .getImageDimensions;
+});
+
+// Components
+const RequestListHeader = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListHeader.js")
+);
+const RequestListItem = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListItem.js")
+);
+const RequestListContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestListContextMenu.js");
+
+const { div } = dom;
+
+// Tooltip show / hide delay in ms
+const REQUESTS_TOOLTIP_TOGGLE_DELAY = 500;
+// Tooltip image maximum dimension in px
+const REQUESTS_TOOLTIP_IMAGE_MAX_DIM = 400;
+
+const LEFT_MOUSE_BUTTON = 0;
+const MIDDLE_MOUSE_BUTTON = 1;
+const RIGHT_MOUSE_BUTTON = 2;
+
+/**
+ * Renders the actual contents of the request list.
+ */
+class RequestListContent extends Component {
+ static get propTypes() {
+ return {
+ blockedUrls: PropTypes.array.isRequired,
+ connector: PropTypes.object.isRequired,
+ columns: PropTypes.object.isRequired,
+ networkActionOpen: PropTypes.bool,
+ networkDetailsOpen: PropTypes.bool.isRequired,
+ networkDetailsWidth: PropTypes.number,
+ networkDetailsHeight: PropTypes.number,
+ cloneRequest: PropTypes.func.isRequired,
+ clickedRequest: PropTypes.object,
+ openDetailsPanelTab: PropTypes.func.isRequired,
+ openHTTPCustomRequestTab: PropTypes.func.isRequired,
+ closeHTTPCustomRequestTab: PropTypes.func.isRequired,
+ sendCustomRequest: PropTypes.func.isRequired,
+ sendHTTPCustomRequest: PropTypes.func.isRequired,
+ displayedRequests: PropTypes.array.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ fromCache: PropTypes.bool,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ onItemRightMouseButtonDown: PropTypes.func.isRequired,
+ onItemMouseDown: PropTypes.func.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ onSelectDelta: PropTypes.func.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ openStatistics: PropTypes.func.isRequired,
+ openRequestBlockingAndAddUrl: PropTypes.func.isRequired,
+ openRequestBlockingAndDisableUrls: PropTypes.func.isRequired,
+ removeBlockedUrl: PropTypes.func.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ selectRequest: PropTypes.func.isRequired,
+ selectedRequest: PropTypes.object,
+ requestFilterTypes: PropTypes.object.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.onHover = this.onHover.bind(this);
+ this.onScroll = this.onScroll.bind(this);
+ this.onResize = this.onResize.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.openRequestInTab = this.openRequestInTab.bind(this);
+ this.onDoubleClick = this.onDoubleClick.bind(this);
+ this.onDragStart = this.onDragStart.bind(this);
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.onMouseDown = this.onMouseDown.bind(this);
+ this.hasOverflow = false;
+ this.onIntersect = this.onIntersect.bind(this);
+ this.intersectionObserver = null;
+ this.state = {
+ onscreenItems: new Set(),
+ };
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ this.tooltip = new HTMLTooltip(window.parent.document, { type: "arrow" });
+ window.addEventListener("resize", this.onResize);
+ }
+
+ componentDidMount() {
+ // Install event handler for displaying a tooltip
+ this.tooltip.startTogglingOnHover(this.refs.scrollEl, this.onHover, {
+ toggleDelay: REQUESTS_TOOLTIP_TOGGLE_DELAY,
+ interactive: true,
+ });
+ // Install event handler to hide the tooltip on scroll
+ this.refs.scrollEl.addEventListener("scroll", this.onScroll, true);
+ this.onResize();
+ this.intersectionObserver = new IntersectionObserver(this.onIntersect, {
+ root: this.refs.scrollEl,
+ // Render 10% more columns for a scrolling headstart
+ rootMargin: "10%",
+ });
+ // Prime IntersectionObserver with existing entries
+ for (const item of this.refs.scrollEl.querySelectorAll(
+ ".request-list-item"
+ )) {
+ this.intersectionObserver.observe(item);
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ const output = this.refs.scrollEl;
+ if (!this.hasOverflow && output.scrollHeight > output.clientHeight) {
+ output.scrollTop = output.scrollHeight;
+ this.hasOverflow = true;
+ }
+ if (
+ prevProps.networkDetailsOpen !== this.props.networkDetailsOpen ||
+ prevProps.networkDetailsWidth !== this.props.networkDetailsWidth ||
+ prevProps.networkDetailsHeight !== this.props.networkDetailsHeight
+ ) {
+ this.onResize();
+ }
+ }
+
+ componentWillUnmount() {
+ this.refs.scrollEl.removeEventListener("scroll", this.onScroll, true);
+
+ // Uninstall the tooltip event handler
+ this.tooltip.stopTogglingOnHover();
+ window.removeEventListener("resize", this.onResize);
+ if (this.intersectionObserver !== null) {
+ this.intersectionObserver.disconnect();
+ this.intersectionObserver = null;
+ }
+ }
+
+ /*
+ * Removing onResize() method causes perf regression - too many repaints of the panel.
+ * So it is needed in ComponentDidMount and ComponentDidUpdate. See Bug 1532914.
+ */
+ onResize() {
+ const parent = this.refs.scrollEl.parentNode;
+ this.refs.scrollEl.style.width = parent.offsetWidth + "px";
+ this.refs.scrollEl.style.height = parent.offsetHeight + "px";
+ }
+
+ onIntersect(entries) {
+ // Track when off screen elements moved on screen to ensure updates
+ let onscreenDidChange = false;
+ const onscreenItems = new Set(this.state.onscreenItems);
+ for (const { target, isIntersecting } of entries) {
+ const { id } = target.dataset;
+ if (isIntersecting) {
+ if (onscreenItems.add(id)) {
+ onscreenDidChange = true;
+ }
+ } else {
+ onscreenItems.delete(id);
+ }
+ }
+ if (onscreenDidChange) {
+ // Remove ids that are no longer displayed
+ const itemIds = new Set(this.props.displayedRequests.map(({ id }) => id));
+ for (const id of onscreenItems) {
+ if (!itemIds.has(id)) {
+ onscreenItems.delete(id);
+ }
+ }
+ this.setState({ onscreenItems });
+ }
+ }
+
+ /**
+ * The predicate used when deciding whether a popup should be shown
+ * over a request item or not.
+ *
+ * @param Node target
+ * The element node currently being hovered.
+ * @param object tooltip
+ * The current tooltip instance.
+ * @return {Promise}
+ */
+ async onHover(target, tooltip) {
+ const itemEl = target.closest(".request-list-item");
+ if (!itemEl) {
+ return false;
+ }
+ const itemId = itemEl.dataset.id;
+ if (!itemId) {
+ return false;
+ }
+ const requestItem = this.props.displayedRequests.find(r => r.id == itemId);
+ if (!requestItem) {
+ return false;
+ }
+
+ if (!target.closest(".requests-list-file")) {
+ return false;
+ }
+
+ const { mimeType } = requestItem;
+ if (!mimeType || !mimeType.includes("image/")) {
+ return false;
+ }
+
+ const responseContent = await this.props.connector.requestData(
+ requestItem.id,
+ "responseContent"
+ );
+ const { encoding, text } = responseContent.content;
+ const src = formDataURI(mimeType, encoding, text);
+ const maxDim = REQUESTS_TOOLTIP_IMAGE_MAX_DIM;
+ const { naturalWidth, naturalHeight } = await getImageDimensions(
+ tooltip.doc,
+ src
+ );
+ const options = { maxDim, naturalWidth, naturalHeight };
+ setImageTooltip(tooltip, tooltip.doc, src, options);
+
+ return itemEl.querySelector(".requests-list-file");
+ }
+
+ /**
+ * Scroll listener for the requests menu view.
+ */
+ onScroll() {
+ this.tooltip.hide();
+ }
+
+ onMouseDown(evt, id, request) {
+ if (evt.button === LEFT_MOUSE_BUTTON) {
+ this.props.selectRequest(id, request);
+ } else if (evt.button === RIGHT_MOUSE_BUTTON) {
+ this.props.onItemRightMouseButtonDown(id);
+ } else if (evt.button === MIDDLE_MOUSE_BUTTON) {
+ this.onMiddleMouseButtonDown(request);
+ }
+ }
+
+ /**
+ * Handler for keyboard events. For arrow up/down, page up/down, home/end,
+ * move the selection up or down.
+ */
+ onKeyDown(evt) {
+ let delta;
+
+ switch (evt.key) {
+ case "ArrowUp":
+ delta = -1;
+ break;
+ case "ArrowDown":
+ delta = +1;
+ break;
+ case "PageUp":
+ delta = "PAGE_UP";
+ break;
+ case "PageDown":
+ delta = "PAGE_DOWN";
+ break;
+ case "Home":
+ delta = -Infinity;
+ break;
+ case "End":
+ delta = +Infinity;
+ break;
+ }
+
+ if (delta) {
+ // Prevent scrolling when pressing navigation keys.
+ evt.preventDefault();
+ evt.stopPropagation();
+ this.props.onSelectDelta(delta);
+ }
+ }
+
+ /**
+ * Opens selected item in a new tab.
+ */
+ async openRequestInTab(id, url, requestHeaders, requestPostData) {
+ requestHeaders =
+ requestHeaders ||
+ (await this.props.connector.requestData(id, "requestHeaders"));
+
+ requestPostData =
+ requestPostData ||
+ (await this.props.connector.requestData(id, "requestPostData"));
+
+ openRequestInTab(url, requestHeaders, requestPostData);
+ }
+
+ onDoubleClick({ id, url, requestHeaders, requestPostData }) {
+ this.openRequestInTab(id, url, requestHeaders, requestPostData);
+ }
+
+ onMiddleMouseButtonDown({ id, url, requestHeaders, requestPostData }) {
+ this.openRequestInTab(id, url, requestHeaders, requestPostData);
+ }
+
+ onDragStart(evt, { url }) {
+ evt.dataTransfer.setData("text/plain", url);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ const { clickedRequest, displayedRequests, blockedUrls } = this.props;
+
+ if (!this.contextMenu) {
+ const {
+ connector,
+ cloneRequest,
+ openDetailsPanelTab,
+ openHTTPCustomRequestTab,
+ closeHTTPCustomRequestTab,
+ sendCustomRequest,
+ sendHTTPCustomRequest,
+ openStatistics,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ removeBlockedUrl,
+ } = this.props;
+ this.contextMenu = new RequestListContextMenu({
+ connector,
+ cloneRequest,
+ openDetailsPanelTab,
+ openHTTPCustomRequestTab,
+ closeHTTPCustomRequestTab,
+ sendCustomRequest,
+ sendHTTPCustomRequest,
+ openStatistics,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ removeBlockedUrl,
+ openRequestInTab: this.openRequestInTab,
+ });
+ }
+
+ this.contextMenu.open(evt, clickedRequest, displayedRequests, blockedUrls);
+ }
+
+ render() {
+ const {
+ connector,
+ columns,
+ displayedRequests,
+ firstRequestStartedMs,
+ onInitiatorBadgeMouseDown,
+ onSecurityIconMouseDown,
+ onWaterfallMouseDown,
+ requestFilterTypes,
+ selectedRequest,
+ selectedActionBarTabId,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ networkActionOpen,
+ networkDetailsOpen,
+ } = this.props;
+
+ return div(
+ {
+ ref: "scrollEl",
+ className: "requests-list-scroll",
+ },
+ [
+ dom.table(
+ {
+ className: "requests-list-table",
+ key: "table",
+ },
+ RequestListHeader(),
+ dom.tbody(
+ {
+ ref: "rowGroupEl",
+ className: "requests-list-row-group",
+ tabIndex: 0,
+ onKeyDown: this.onKeyDown,
+ },
+ displayedRequests.map((item, index) => {
+ return RequestListItem({
+ blocked: !!item.blockedReason,
+ firstRequestStartedMs,
+ fromCache: item.status === "304" || item.fromCache,
+ networkDetailsOpen,
+ networkActionOpen,
+ selectedActionBarTabId,
+ connector,
+ columns,
+ item,
+ index,
+ isSelected: item.id === selectedRequest?.id,
+ isVisible: this.state.onscreenItems.has(item.id),
+ key: item.id,
+ intersectionObserver: this.intersectionObserver,
+ onContextMenu: this.onContextMenu,
+ onDoubleClick: () => this.onDoubleClick(item),
+ onDragStart: evt => this.onDragStart(evt, item),
+ onMouseDown: evt => this.onMouseDown(evt, item.id, item),
+ onInitiatorBadgeMouseDown: () =>
+ onInitiatorBadgeMouseDown(item.cause),
+ onSecurityIconMouseDown: () =>
+ onSecurityIconMouseDown(item.securityState),
+ onWaterfallMouseDown,
+ requestFilterTypes,
+ openRequestBlockingAndAddUrl,
+ openRequestBlockingAndDisableUrls,
+ });
+ })
+ )
+ ), // end of requests-list-row-group">
+ dom.div({
+ className: "requests-list-anchor",
+ key: "anchor",
+ }),
+ ]
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ blockedUrls: state.requestBlocking.blockedUrls
+ .map(({ enabled, url }) => (enabled ? url : null))
+ .filter(Boolean),
+ columns: getColumns(state),
+ networkActionOpen: state.ui.networkActionOpen,
+ networkDetailsOpen: state.ui.networkDetailsOpen,
+ networkDetailsWidth: state.ui.networkDetailsWidth,
+ networkDetailsHeight: state.ui.networkDetailsHeight,
+ clickedRequest: getClickedRequest(state),
+ displayedRequests: getDisplayedRequests(state),
+ firstRequestStartedMs: state.requests.firstStartedMs,
+ selectedActionBarTabId: state.ui.selectedActionBarTabId,
+ selectedRequest: getSelectedRequest(state),
+ requestFilterTypes: state.filters.requestFilterTypes,
+ }),
+ (dispatch, props) => ({
+ cloneRequest: id => dispatch(Actions.cloneRequest(id)),
+ openDetailsPanelTab: () => dispatch(Actions.openNetworkDetails(true)),
+ openHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(true)),
+ closeHTTPCustomRequestTab: () =>
+ dispatch(Actions.openHTTPCustomRequest(false)),
+ sendCustomRequest: () => dispatch(Actions.sendCustomRequest()),
+ sendHTTPCustomRequest: request =>
+ dispatch(Actions.sendHTTPCustomRequest(request)),
+ openStatistics: open =>
+ dispatch(Actions.openStatistics(props.connector, open)),
+ openRequestBlockingAndAddUrl: url =>
+ dispatch(Actions.openRequestBlockingAndAddUrl(url)),
+ removeBlockedUrl: url => dispatch(Actions.removeBlockedUrl(url)),
+ openRequestBlockingAndDisableUrls: url =>
+ dispatch(Actions.openRequestBlockingAndDisableUrls(url)),
+ /**
+ * A handler that opens the stack trace tab when a stack trace is available
+ */
+ onInitiatorBadgeMouseDown: cause => {
+ if (cause.lastFrame) {
+ dispatch(Actions.selectDetailsPanelTab("stack-trace"));
+ }
+ },
+ selectRequest: (id, request) =>
+ dispatch(Actions.selectRequest(id, request)),
+ onItemRightMouseButtonDown: id => dispatch(Actions.rightClickRequest(id)),
+ onItemMouseDown: id => dispatch(Actions.selectRequest(id)),
+ /**
+ * A handler that opens the security tab in the details view if secure or
+ * broken security indicator is clicked.
+ */
+ onSecurityIconMouseDown: securityState => {
+ if (securityState && securityState !== "insecure") {
+ dispatch(Actions.selectDetailsPanelTab("security"));
+ }
+ },
+ onSelectDelta: delta => dispatch(Actions.selectDelta(delta)),
+ /**
+ * A handler that opens the timing sidebar panel if the waterfall is clicked.
+ */
+ onWaterfallMouseDown: () => {
+ dispatch(Actions.selectDetailsPanelTab("timings"));
+ },
+ })
+)(RequestListContent);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js b/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js
new file mode 100644
index 0000000000..318078b782
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js
@@ -0,0 +1,107 @@
+/* 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,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ ACTIVITY_TYPE,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const {
+ getPerformanceAnalysisURL,
+} = require("resource://devtools/client/netmonitor/src/utils/doc-utils.js");
+
+// Components
+const MDNLink = createFactory(
+ require("resource://devtools/client/shared/components/MdnLink.js")
+);
+
+const { button, div, span } = dom;
+
+const RELOAD_NOTICE_1 = L10N.getStr("netmonitor.reloadNotice1");
+const RELOAD_NOTICE_2 = L10N.getStr("netmonitor.reloadNotice2");
+const RELOAD_NOTICE_3 = L10N.getStr("netmonitor.reloadNotice3");
+const RELOAD_NOTICE_BT = L10N.getStr("netmonitor.emptyBrowserToolbox");
+const PERFORMANCE_NOTICE_1 = L10N.getStr("netmonitor.perfNotice1");
+const PERFORMANCE_NOTICE_2 = L10N.getStr("netmonitor.perfNotice2");
+const PERFORMANCE_NOTICE_3 = L10N.getStr("netmonitor.perfNotice3");
+const PERFORMANCE_LEARN_MORE = L10N.getStr("charts.learnMore");
+
+/**
+ * UI displayed when the request list is empty. Contains instructions on reloading
+ * the page and on triggering performance analysis of the page.
+ */
+class RequestListEmptyNotice extends Component {
+ static get propTypes() {
+ return {
+ connector: PropTypes.object.isRequired,
+ onReloadClick: PropTypes.func.isRequired,
+ onPerfClick: PropTypes.func.isRequired,
+ };
+ }
+
+ render() {
+ const { connector } = this.props;
+ const toolbox = connector.getToolbox();
+
+ return div(
+ {
+ className: "request-list-empty-notice",
+ },
+ !toolbox.isBrowserToolbox
+ ? div(
+ { className: "notice-reload-message empty-notice-element" },
+ span(null, RELOAD_NOTICE_1),
+ button(
+ {
+ className: "devtools-button requests-list-reload-notice-button",
+ "data-standalone": true,
+ onClick: this.props.onReloadClick,
+ },
+ RELOAD_NOTICE_2
+ ),
+ span(null, RELOAD_NOTICE_3)
+ )
+ : div(
+ { className: "notice-reload-message empty-notice-element" },
+ span(null, RELOAD_NOTICE_BT)
+ ),
+ !toolbox.isBrowserToolbox
+ ? div(
+ { className: "notice-perf-message empty-notice-element" },
+ span(null, PERFORMANCE_NOTICE_1),
+ button({
+ title: PERFORMANCE_NOTICE_3,
+ className: "devtools-button requests-list-perf-notice-button",
+ "data-standalone": true,
+ onClick: this.props.onPerfClick,
+ }),
+ span(null, PERFORMANCE_NOTICE_2),
+ MDNLink({
+ url: getPerformanceAnalysisURL(),
+ title: PERFORMANCE_LEARN_MORE,
+ })
+ )
+ : null
+ );
+ }
+}
+
+module.exports = connect(undefined, (dispatch, props) => ({
+ onPerfClick: () => dispatch(Actions.openStatistics(props.connector, true)),
+ onReloadClick: () =>
+ props.connector.triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_DEFAULT),
+}))(RequestListEmptyNotice);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js b/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js
new file mode 100644
index 0000000000..d02e993b02
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListHeader.js
@@ -0,0 +1,731 @@
+/* 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 {
+ createRef,
+ Component,
+ createFactory,
+} = 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 {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ getTheme,
+ addThemeObserver,
+ removeThemeObserver,
+} = require("resource://devtools/client/shared/theme.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ HEADERS,
+ REQUESTS_WATERFALL,
+ MIN_COLUMN_WIDTH,
+ DEFAULT_COLUMN_WIDTH,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const {
+ getColumns,
+ getWaterfallScale,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const {
+ getFormattedTime,
+} = require("resource://devtools/client/netmonitor/src/utils/format-utils.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const RequestListHeaderContextMenu = require("resource://devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js");
+const WaterfallBackground = require("resource://devtools/client/netmonitor/src/widgets/WaterfallBackground.js");
+const Draggable = createFactory(
+ require("resource://devtools/client/shared/components/splitter/Draggable.js")
+);
+
+const { div, button } = dom;
+
+/**
+ * Render the request list header with sorting arrows for columns.
+ * Displays tick marks in the waterfall column header.
+ * Also draws the waterfall background canvas and updates it when needed.
+ */
+class RequestListHeader extends Component {
+ static get propTypes() {
+ return {
+ columns: PropTypes.object.isRequired,
+ resetColumns: PropTypes.func.isRequired,
+ resetSorting: PropTypes.func.isRequired,
+ resizeWaterfall: PropTypes.func.isRequired,
+ scale: PropTypes.number,
+ sort: PropTypes.object,
+ sortBy: PropTypes.func.isRequired,
+ toggleColumn: PropTypes.func.isRequired,
+ waterfallWidth: PropTypes.number,
+ columnsData: PropTypes.object.isRequired,
+ setColumnsWidth: PropTypes.func.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.requestListHeader = createRef();
+
+ this.onContextMenu = this.onContextMenu.bind(this);
+ this.drawBackground = this.drawBackground.bind(this);
+ this.resizeWaterfall = this.resizeWaterfall.bind(this);
+ this.waterfallDivisionLabels = this.waterfallDivisionLabels.bind(this);
+ this.waterfallLabel = this.waterfallLabel.bind(this);
+ this.onHeaderClick = this.onHeaderClick.bind(this);
+ this.resizeColumnToFitContent = this.resizeColumnToFitContent.bind(this);
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillMount() {
+ const { resetColumns, resetSorting, toggleColumn } = this.props;
+ this.contextMenu = new RequestListHeaderContextMenu({
+ resetColumns,
+ resetSorting,
+ toggleColumn,
+ resizeColumnToFitContent: this.resizeColumnToFitContent,
+ });
+ }
+
+ componentDidMount() {
+ // Create the object that takes care of drawing the waterfall canvas background
+ this.background = new WaterfallBackground(document);
+ this.drawBackground();
+ // When visible columns add up to less or more than 100% => update widths in prefs.
+ if (this.shouldUpdateWidths()) {
+ this.updateColumnsWidth();
+ }
+ this.resizeWaterfall();
+ window.addEventListener("resize", this.resizeWaterfall);
+ addThemeObserver(this.drawBackground);
+ }
+
+ componentDidUpdate() {
+ this.drawBackground();
+ // check if the widths in prefs need to be updated
+ // e.g. after hide/show column
+ if (this.shouldUpdateWidths()) {
+ this.updateColumnsWidth();
+ this.resizeWaterfall();
+ }
+ }
+
+ componentWillUnmount() {
+ this.background.destroy();
+ this.background = null;
+ window.removeEventListener("resize", this.resizeWaterfall);
+ removeThemeObserver(this.drawBackground);
+ }
+
+ /**
+ * Helper method to get the total width of cell's content.
+ * Used for resizing columns to fit their content.
+ */
+ totalCellWidth(cellEl) {
+ return [...cellEl.childNodes]
+ .map(cNode => {
+ if (cNode.nodeType === 3) {
+ // if it's text node
+ return Math.ceil(
+ cNode.getBoxQuads()[0].p2.x - cNode.getBoxQuads()[0].p1.x
+ );
+ }
+ return cNode.getBoundingClientRect().width;
+ })
+ .reduce((a, b) => a + b, 0);
+ }
+
+ /**
+ * Resize column to fit its content.
+ * Additionally, resize other columns (starting from last) to compensate.
+ */
+ resizeColumnToFitContent(name) {
+ const headerRef = this.refs[`${name}Header`];
+ const parentEl = headerRef.closest(".requests-list-table");
+ const width = headerRef.getBoundingClientRect().width;
+ const parentWidth = parentEl.getBoundingClientRect().width;
+ const items = parentEl.querySelectorAll(".request-list-item");
+ const columnIndex = headerRef.cellIndex;
+ const widths = [...items].map(item =>
+ this.totalCellWidth(item.children[columnIndex])
+ );
+
+ const minW = this.getMinWidth(name);
+
+ // Add 11 to account for cell padding (padding-right + padding-left = 9px), not accurate.
+ let maxWidth = 11 + Math.max.apply(null, widths);
+
+ if (maxWidth < minW) {
+ maxWidth = minW;
+ }
+
+ // Pixel value which, if added to this column's width, will fit its content.
+ let change = maxWidth - width;
+
+ // Max change we can do while taking other columns into account.
+ let maxAllowedChange = 0;
+ const visibleColumns = this.getVisibleColumns();
+ const newWidths = [];
+
+ // Calculate new widths for other columns to compensate.
+ // Start from the 2nd last column if last column is waterfall.
+ // This is done to comply with the existing resizing behavior.
+ const delta =
+ visibleColumns[visibleColumns.length - 1].name === "waterfall" ? 2 : 1;
+
+ for (let i = visibleColumns.length - delta; i > 0; i--) {
+ if (i !== columnIndex) {
+ const columnName = visibleColumns[i].name;
+ const columnHeaderRef = this.refs[`${columnName}Header`];
+ const columnWidth = columnHeaderRef.getBoundingClientRect().width;
+ const minWidth = this.getMinWidth(columnName);
+ const newWidth = columnWidth - change;
+
+ // If this column can compensate for all the remaining change.
+ if (newWidth >= minWidth) {
+ maxAllowedChange += change;
+ change = 0;
+ newWidths.push({
+ name: columnName,
+ width: this.px2percent(newWidth, parentWidth),
+ });
+ break;
+ } else {
+ // Max change we can do in this column.
+ let maxColumnChange = columnWidth - minWidth;
+ maxColumnChange = maxColumnChange > change ? change : maxColumnChange;
+ maxAllowedChange += maxColumnChange;
+ change -= maxColumnChange;
+ newWidths.push({
+ name: columnName,
+ width: this.px2percent(columnWidth - maxColumnChange, parentWidth),
+ });
+ }
+ }
+ }
+ newWidths.push({
+ name,
+ width: this.px2percent(width + maxAllowedChange, parentWidth),
+ });
+ this.props.setColumnsWidth(newWidths);
+ }
+
+ onContextMenu(evt) {
+ evt.preventDefault();
+ this.contextMenu.open(evt, this.props.columns);
+ }
+
+ onHeaderClick(evt, headerName) {
+ const { sortBy, resetSorting } = this.props;
+ if (evt.button == 1) {
+ // reset sort state on middle click
+ resetSorting();
+ } else {
+ sortBy(headerName);
+ }
+ }
+
+ drawBackground() {
+ // The background component is theme dependent, so add the current theme to the props.
+ const props = Object.assign({}, this.props, {
+ theme: getTheme(),
+ });
+ this.background.draw(props);
+ }
+
+ resizeWaterfall() {
+ const { waterfallHeader } = this.refs;
+ if (waterfallHeader) {
+ // Measure its width and update the 'waterfallWidth' property in the store.
+ // The 'waterfallWidth' will be further updated on every window resize.
+ window.cancelIdleCallback(this._resizeTimerId);
+ this._resizeTimerId = window.requestIdleCallback(() =>
+ this.props.resizeWaterfall(
+ waterfallHeader.getBoundingClientRect().width
+ )
+ );
+ }
+ }
+
+ /**
+ * Build the waterfall header - timing tick marks with the right spacing
+ */
+ waterfallDivisionLabels(waterfallWidth, scale) {
+ const labels = [];
+
+ // Build new millisecond tick labels...
+ const timingStep = REQUESTS_WATERFALL.HEADER_TICKS_MULTIPLE;
+ let scaledStep = scale * timingStep;
+
+ // Ignore any divisions that would end up being too close to each other.
+ while (scaledStep < REQUESTS_WATERFALL.HEADER_TICKS_SPACING_MIN) {
+ scaledStep *= 2;
+ }
+
+ // Insert one label for each division on the current scale.
+ for (let x = 0; x < waterfallWidth; x += scaledStep) {
+ const millisecondTime = x / scale;
+ let divisionScale = "millisecond";
+
+ // If the division is greater than 1 minute.
+ if (millisecondTime > 60000) {
+ divisionScale = "minute";
+ } else if (millisecondTime > 1000) {
+ // If the division is greater than 1 second.
+ divisionScale = "second";
+ }
+
+ let width = ((x + scaledStep) | 0) - (x | 0);
+ // Adjust the first marker for the borders
+ if (x == 0) {
+ width -= 2;
+ }
+ // Last marker doesn't need a width specified at all
+ if (x + scaledStep >= waterfallWidth) {
+ width = undefined;
+ }
+
+ labels.push(
+ div(
+ {
+ key: labels.length,
+ className: "requests-list-timings-division",
+ "data-division-scale": divisionScale,
+ style: { width },
+ },
+ getFormattedTime(millisecondTime)
+ )
+ );
+ }
+
+ return labels;
+ }
+
+ waterfallLabel(waterfallWidth, scale, label) {
+ let className = "button-text requests-list-waterfall-label-wrapper";
+
+ if (waterfallWidth !== null && scale !== null) {
+ label = this.waterfallDivisionLabels(waterfallWidth, scale);
+ className += " requests-list-waterfall-visible";
+ }
+
+ return div({ className }, label);
+ }
+
+ // Dragging Events
+
+ /**
+ * Set 'resizing' cursor on entire container dragging.
+ * This avoids cursor-flickering when the mouse leaves
+ * the column-resizer area (happens frequently).
+ */
+ onStartMove() {
+ // Set cursor to dragging
+ const container = document.querySelector(".request-list-container");
+ container.style.cursor = "ew-resize";
+ // Class .dragging is used to disable pointer events while dragging - see css.
+ this.requestListHeader.classList.add("dragging");
+ }
+
+ /**
+ * A handler that calculates the new width of the columns
+ * based on mouse position and adjusts the width.
+ */
+ onMove(name, x) {
+ const parentEl = document.querySelector(".requests-list-headers");
+ const parentWidth = parentEl.getBoundingClientRect().width;
+
+ // Get the current column handle and save its old width
+ // before changing so we can compute the adjustment in width
+ const headerRef = this.refs[`${name}Header`];
+ const headerRefRect = headerRef.getBoundingClientRect();
+ const oldWidth = headerRefRect.width;
+
+ // Get the column handle that will compensate the width change.
+ const compensateHeaderName = this.getCompensateHeader();
+
+ if (name === compensateHeaderName) {
+ // this is the case where we are resizing waterfall
+ this.moveWaterfall(x, parentWidth);
+ return;
+ }
+
+ const compensateHeaderRef = this.refs[`${compensateHeaderName}Header`];
+ const compensateHeaderRefRect = compensateHeaderRef.getBoundingClientRect();
+ const oldCompensateWidth = compensateHeaderRefRect.width;
+ const sumOfBothColumns = oldWidth + oldCompensateWidth;
+
+ // Get minimal widths for both changed columns (in px).
+ const minWidth = this.getMinWidth(name);
+ const minCompensateWidth = this.getMinWidth(compensateHeaderName);
+
+ // Calculate new width (according to the mouse x-position) and set to style.
+ // Do not allow to set it below minWidth.
+ let newWidth =
+ document.dir == "ltr" ? x - headerRefRect.left : headerRefRect.right - x;
+ newWidth = Math.max(newWidth, minWidth);
+ headerRef.style.width = `${this.px2percent(newWidth, parentWidth)}%`;
+ const adjustment = oldWidth - newWidth;
+
+ // Calculate new compensate width as the original width + adjustment.
+ // Do not allow to set it below minCompensateWidth.
+ const newCompensateWidth = Math.max(
+ adjustment + oldCompensateWidth,
+ minCompensateWidth
+ );
+ compensateHeaderRef.style.width = `${this.px2percent(
+ newCompensateWidth,
+ parentWidth
+ )}%`;
+
+ // Do not allow to reset size of column when compensate column is at minWidth.
+ if (newCompensateWidth === minCompensateWidth) {
+ headerRef.style.width = `${this.px2percent(
+ sumOfBothColumns - newCompensateWidth,
+ parentWidth
+ )}%`;
+ }
+ }
+
+ /**
+ * After resizing - we get the width for each 'column'
+ * and convert it into % and store it in user prefs.
+ * Also resets the 'resizing' cursor back to initial.
+ */
+ onStopMove() {
+ this.updateColumnsWidth();
+ // If waterfall is visible and width has changed, call resizeWaterfall.
+ const waterfallRef = this.refs.waterfallHeader;
+ if (waterfallRef) {
+ const { waterfallWidth } = this.props;
+ const realWaterfallWidth = waterfallRef.getBoundingClientRect().width;
+ if (Math.round(waterfallWidth) !== Math.round(realWaterfallWidth)) {
+ this.resizeWaterfall();
+ }
+ }
+
+ // Restore cursor back to default.
+ const container = document.querySelector(".request-list-container");
+ container.style.cursor = "initial";
+ this.requestListHeader.classList.remove("dragging");
+ }
+
+ /**
+ * Helper method to get the name of the column that will compensate
+ * the width change. It should be the last column before waterfall,
+ * (if waterfall visible) otherwise it is simply the last visible column.
+ */
+ getCompensateHeader() {
+ const visibleColumns = this.getVisibleColumns();
+ const lastColumn = visibleColumns[visibleColumns.length - 1].name;
+ const delta = lastColumn === "waterfall" ? 2 : 1;
+ return visibleColumns[visibleColumns.length - delta].name;
+ }
+
+ /**
+ * Called from onMove() when resizing waterfall column
+ * because waterfall is a special case, where ALL other
+ * columns are made smaller when waterfall is bigger and vice versa.
+ */
+ moveWaterfall(x, parentWidth) {
+ const visibleColumns = this.getVisibleColumns();
+ const minWaterfall = this.getMinWidth("waterfall");
+ const waterfallRef = this.refs.waterfallHeader;
+
+ // Compute and set style.width for waterfall.
+ const waterfallRefRect = waterfallRef.getBoundingClientRect();
+ const oldWidth = waterfallRefRect.width;
+ const adjustment =
+ document.dir == "ltr"
+ ? waterfallRefRect.left - x
+ : x - waterfallRefRect.right;
+ if (this.allColumnsAtMinWidth() && adjustment > 0) {
+ // When we want to make waterfall wider but all
+ // other columns are already at minWidth => return.
+ return;
+ }
+
+ const newWidth = Math.max(oldWidth + adjustment, minWaterfall);
+
+ // Now distribute evenly the change in width to all other columns except waterfall.
+ const changeInWidth = oldWidth - newWidth;
+ const widths = this.autoSizeWidths(changeInWidth, visibleColumns);
+
+ // Set the new computed width for waterfall into array widths.
+ widths[widths.length - 1] = newWidth;
+
+ // Update style for all columns from array widths.
+ let i = 0;
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ headerRef.style.width = `${this.px2percent(widths[i], parentWidth)}%`;
+ i++;
+ });
+ }
+
+ /**
+ * Helper method that checks if all columns have reached their minWidth.
+ * This can happen when making waterfall column wider.
+ */
+ allColumnsAtMinWidth() {
+ const visibleColumns = this.getVisibleColumns();
+ // Do not check width for waterfall because
+ // when all are getting smaller, waterfall is getting bigger.
+ for (let i = 0; i < visibleColumns.length - 1; i++) {
+ const { name } = visibleColumns[i];
+ const headerRef = this.refs[`${name}Header`];
+ const minColWidth = this.getMinWidth(name);
+ if (headerRef.getBoundingClientRect().width > minColWidth) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Method takes the total change in width for waterfall column
+ * and distributes it among all other columns. Returns an array
+ * where all visible columns have newly computed width in pixels.
+ */
+ autoSizeWidths(changeInWidth, visibleColumns) {
+ const widths = visibleColumns.map(col => {
+ const headerRef = this.refs[`${col.name}Header`];
+ const colWidth = headerRef.getBoundingClientRect().width;
+ return colWidth;
+ });
+
+ // Divide changeInWidth among all columns but waterfall (that's why -1).
+ const changeInWidthPerColumn = changeInWidth / (widths.length - 1);
+
+ while (changeInWidth) {
+ const lastChangeInWidth = changeInWidth;
+ // In the loop adjust all columns except last one - waterfall
+ for (let i = 0; i < widths.length - 1; i++) {
+ const { name } = visibleColumns[i];
+ const minColWidth = this.getMinWidth(name);
+ const newColWidth = Math.max(
+ widths[i] + changeInWidthPerColumn,
+ minColWidth
+ );
+
+ widths[i] = newColWidth;
+ if (changeInWidth > 0) {
+ changeInWidth -= newColWidth - widths[i];
+ } else {
+ changeInWidth += newColWidth - widths[i];
+ }
+ if (!changeInWidth) {
+ break;
+ }
+ }
+ if (lastChangeInWidth == changeInWidth) {
+ break;
+ }
+ }
+ return widths;
+ }
+
+ /**
+ * Method returns 'true' - if the column widths need to be updated
+ * when the total % is less or more than 100%.
+ * It returns 'false' if they add up to 100% => no need to update.
+ */
+ shouldUpdateWidths() {
+ const visibleColumns = this.getVisibleColumns();
+ let totalPercent = 0;
+
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ // Get column width from style.
+ let widthFromStyle = 0;
+ // In case the column is in visibleColumns but has display:none
+ // we don't want to count its style.width into totalPercent.
+ if (headerRef.getBoundingClientRect().width > 0) {
+ widthFromStyle = headerRef.style.width.slice(0, -1);
+ }
+ totalPercent += +widthFromStyle; // + converts it to a number
+ });
+
+ // Do not update if total percent is from 99-101% or when it is 0
+ // - it means that no columns are displayed (e.g. other panel is currently selected).
+ return Math.round(totalPercent) !== 100 && totalPercent !== 0;
+ }
+
+ /**
+ * Method reads real width of each column header
+ * and updates the style.width for that header.
+ * It returns updated columnsData.
+ */
+ updateColumnsWidth() {
+ const visibleColumns = this.getVisibleColumns();
+ const parentEl = document.querySelector(".requests-list-headers");
+ const parentElRect = parentEl.getBoundingClientRect();
+ const parentWidth = parentElRect.width;
+ const newWidths = [];
+ visibleColumns.forEach(col => {
+ const { name } = col;
+ const headerRef = this.refs[`${name}Header`];
+ const headerWidth = headerRef.getBoundingClientRect().width;
+
+ // Get actual column width, change into %, update style
+ const width = this.px2percent(headerWidth, parentWidth);
+
+ if (width > 0) {
+ // This prevents saving width 0 for waterfall when it is not showing for
+ // @media (max-width: 700px)
+ newWidths.push({ name, width });
+ }
+ });
+ this.props.setColumnsWidth(newWidths);
+ }
+
+ /**
+ * Helper method to convert pixels into percent based on parent container width
+ */
+ px2percent(pxWidth, parentWidth) {
+ const percent = Math.round(((100 * pxWidth) / parentWidth) * 100) / 100;
+ return percent;
+ }
+
+ /**
+ * Helper method to get visibleColumns;
+ */
+ getVisibleColumns() {
+ const { columns } = this.props;
+ return HEADERS.filter(header => columns[header.name]);
+ }
+
+ /**
+ * Helper method to get minWidth from columnsData;
+ */
+ getMinWidth(colName) {
+ const { columnsData } = this.props;
+ if (columnsData.has(colName)) {
+ return columnsData.get(colName).minWidth;
+ }
+ return MIN_COLUMN_WIDTH;
+ }
+
+ /**
+ * Render one column header from the table headers.
+ */
+ renderColumn(header) {
+ const { columnsData } = this.props;
+ const visibleColumns = this.getVisibleColumns();
+ const lastVisibleColumn = visibleColumns[visibleColumns.length - 1].name;
+ const { name } = header;
+ const boxName = header.boxName || name;
+ const label = header.noLocalization
+ ? name
+ : L10N.getStr(`netmonitor.toolbar.${header.label || name}`);
+
+ const { scale, sort, waterfallWidth } = this.props;
+ let sorted, sortedTitle;
+ const active = sort.type == name ? true : undefined;
+
+ if (active) {
+ sorted = sort.ascending ? "ascending" : "descending";
+ sortedTitle = L10N.getStr(
+ sort.ascending ? "networkMenu.sortedAsc" : "networkMenu.sortedDesc"
+ );
+ }
+
+ // If the pref for this column width exists, set the style
+ // otherwise use default.
+ let colWidth = DEFAULT_COLUMN_WIDTH;
+ if (columnsData.has(name)) {
+ const oneColumnEl = columnsData.get(name);
+ colWidth = oneColumnEl.width;
+ }
+ const columnStyle = {
+ width: colWidth + "%",
+ };
+
+ // Support for columns resizing is currently hidden behind a pref.
+ const draggable = Draggable({
+ className: "column-resizer ",
+ title: L10N.getStr("netmonitor.toolbar.resizeColumnToFitContent.title"),
+ onStart: () => this.onStartMove(),
+ onStop: () => this.onStopMove(),
+ onMove: x => this.onMove(name, x),
+ onDoubleClick: () => this.resizeColumnToFitContent(name),
+ });
+
+ return dom.th(
+ {
+ id: `requests-list-${boxName}-header-box`,
+ className: `requests-list-column requests-list-${boxName}`,
+ scope: "col",
+ style: columnStyle,
+ key: name,
+ ref: `${name}Header`,
+ // Used to style the next column.
+ "data-active": active,
+ },
+ button(
+ {
+ id: `requests-list-${name}-button`,
+ className: `requests-list-header-button`,
+ "data-sorted": sorted,
+ "data-name": name,
+ title: sortedTitle ? `${label} (${sortedTitle})` : label,
+ onClick: evt => this.onHeaderClick(evt, name),
+ },
+ name === "waterfall"
+ ? this.waterfallLabel(waterfallWidth, scale, label)
+ : div({ className: "button-text" }, label),
+ div({ className: "button-icon" })
+ ),
+ name !== lastVisibleColumn && draggable
+ );
+ }
+
+ /**
+ * Render all columns in the table header
+ */
+ renderColumns() {
+ const visibleColumns = this.getVisibleColumns();
+ return visibleColumns.map(header => this.renderColumn(header));
+ }
+
+ render() {
+ return dom.thead(
+ { className: "requests-list-headers-group" },
+ dom.tr(
+ {
+ className: "requests-list-headers",
+ onContextMenu: this.onContextMenu,
+ ref: node => {
+ this.requestListHeader = node;
+ },
+ },
+ this.renderColumns()
+ )
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ columns: getColumns(state),
+ columnsData: state.ui.columnsData,
+ firstRequestStartedMs: state.requests.firstStartedMs,
+ scale: getWaterfallScale(state),
+ sort: state.sort,
+ timingMarkers: state.timingMarkers,
+ waterfallWidth: state.ui.waterfallWidth,
+ }),
+ dispatch => ({
+ resetColumns: () => dispatch(Actions.resetColumns()),
+ resetSorting: () => dispatch(Actions.sortBy(null)),
+ resizeWaterfall: width => dispatch(Actions.resizeWaterfall(width)),
+ sortBy: type => dispatch(Actions.sortBy(type)),
+ toggleColumn: column => dispatch(Actions.toggleColumn(column)),
+ setColumnsWidth: widths => dispatch(Actions.setColumnsWidth(widths)),
+ })
+)(RequestListHeader);
diff --git a/devtools/client/netmonitor/src/components/request-list/RequestListItem.js b/devtools/client/netmonitor/src/components/request-list/RequestListItem.js
new file mode 100644
index 0000000000..5c70b44e00
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/RequestListItem.js
@@ -0,0 +1,412 @@
+/* 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,
+ createFactory,
+} = 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 {
+ fetchNetworkUpdatePacket,
+ propertiesEqual,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+const {
+ PANELS,
+ RESPONSE_HEADERS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+// Components
+/* global
+ RequestListColumnInitiator,
+ RequestListColumnContentSize,
+ RequestListColumnCookies,
+ RequestListColumnDomain,
+ RequestListColumnFile,
+ RequestListColumnMethod,
+ RequestListColumnProtocol,
+ RequestListColumnRemoteIP,
+ RequestListColumnResponseHeader,
+ RequestListColumnScheme,
+ RequestListColumnSetCookies,
+ RequestListColumnStatus,
+ RequestListColumnTime,
+ RequestListColumnTransferredSize,
+ RequestListColumnType,
+ RequestListColumnUrl,
+ RequestListColumnWaterfall,
+ RequestListColumnPriority
+*/
+loader.lazyGetter(this, "RequestListColumnInitiator", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnContentSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnCookies", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnDomain", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnFile", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnUrl", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnMethod", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnProtocol", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnRemoteIP", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnResponseHeader", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnTime", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnScheme", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnSetCookies", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnStatus", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnTransferredSize", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnType", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnWaterfall", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js")
+ );
+});
+loader.lazyGetter(this, "RequestListColumnPriority", function () {
+ return createFactory(
+ require("resource://devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js")
+ );
+});
+
+/**
+ * Used by shouldComponentUpdate: compare two items, and compare only properties
+ * relevant for rendering the RequestListItem. Other properties (like request and
+ * response headers, cookies, bodies) are ignored. These are very useful for the
+ * network details, but not here.
+ */
+const UPDATED_REQ_ITEM_PROPS = [
+ "mimeType",
+ "eventTimings",
+ "securityState",
+ "status",
+ "statusText",
+ "fromCache",
+ "isRacing",
+ "fromServiceWorker",
+ "method",
+ "url",
+ "remoteAddress",
+ "cause",
+ "contentSize",
+ "transferredSize",
+ "startedMs",
+ "totalTime",
+ "requestCookies",
+ "requestHeaders",
+ "responseCookies",
+ "responseHeaders",
+ "waitingTime",
+ "isEventStream",
+ "priority",
+];
+
+const UPDATED_REQ_PROPS = [
+ "firstRequestStartedMs",
+ "index",
+ "networkDetailsOpen",
+ "isSelected",
+ "isVisible",
+ "requestFilterTypes",
+];
+
+/**
+ * Used by render: renders the given ColumnComponent if the flag for this column
+ * is set in the columns prop. The list of props are used to determine which of
+ * RequestListItem's need to be passed to the ColumnComponent. Any objects contained
+ * in that list are passed as props verbatim.
+ */
+const COLUMN_COMPONENTS = [
+ { column: "status", ColumnComponent: RequestListColumnStatus },
+ { column: "method", ColumnComponent: RequestListColumnMethod },
+ {
+ column: "domain",
+ ColumnComponent: RequestListColumnDomain,
+ props: ["onSecurityIconMouseDown"],
+ },
+ {
+ column: "file",
+ ColumnComponent: RequestListColumnFile,
+ props: ["onWaterfallMouseDown"],
+ },
+ {
+ column: "url",
+ ColumnComponent: RequestListColumnUrl,
+ props: ["onSecurityIconMouseDown"],
+ },
+ { column: "protocol", ColumnComponent: RequestListColumnProtocol },
+ { column: "scheme", ColumnComponent: RequestListColumnScheme },
+ { column: "remoteip", ColumnComponent: RequestListColumnRemoteIP },
+ {
+ column: "initiator",
+ ColumnComponent: RequestListColumnInitiator,
+ props: ["onInitiatorBadgeMouseDown"],
+ },
+ { column: "type", ColumnComponent: RequestListColumnType },
+ {
+ column: "cookies",
+ ColumnComponent: RequestListColumnCookies,
+ props: ["connector"],
+ },
+ {
+ column: "setCookies",
+ ColumnComponent: RequestListColumnSetCookies,
+ props: ["connector"],
+ },
+ { column: "transferred", ColumnComponent: RequestListColumnTransferredSize },
+ { column: "contentSize", ColumnComponent: RequestListColumnContentSize },
+ { column: "priority", ColumnComponent: RequestListColumnPriority },
+ {
+ column: "startTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "start" }],
+ },
+ {
+ column: "endTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "end" }],
+ },
+ {
+ column: "responseTime",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "response" }],
+ },
+ {
+ column: "duration",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "duration" }],
+ },
+ {
+ column: "latency",
+ ColumnComponent: RequestListColumnTime,
+ props: ["connector", "firstRequestStartedMs", { type: "latency" }],
+ },
+];
+
+/**
+ * Render one row in the request list.
+ */
+class RequestListItem extends Component {
+ static get propTypes() {
+ return {
+ blocked: PropTypes.bool,
+ connector: PropTypes.object.isRequired,
+ columns: PropTypes.object.isRequired,
+ item: PropTypes.object.isRequired,
+ index: PropTypes.number.isRequired,
+ isSelected: PropTypes.bool.isRequired,
+ isVisible: PropTypes.bool.isRequired,
+ firstRequestStartedMs: PropTypes.number.isRequired,
+ fromCache: PropTypes.bool,
+ networkActionOpen: PropTypes.bool,
+ networkDetailsOpen: PropTypes.bool,
+ onInitiatorBadgeMouseDown: PropTypes.func.isRequired,
+ onDoubleClick: PropTypes.func.isRequired,
+ onDragStart: PropTypes.func.isRequired,
+ onContextMenu: PropTypes.func.isRequired,
+ onFocusedNodeChange: PropTypes.func,
+ onMouseDown: PropTypes.func.isRequired,
+ onSecurityIconMouseDown: PropTypes.func.isRequired,
+ onWaterfallMouseDown: PropTypes.func.isRequired,
+ requestFilterTypes: PropTypes.object.isRequired,
+ selectedActionBarTabId: PropTypes.string,
+ intersectionObserver: PropTypes.object,
+ };
+ }
+
+ componentDidMount() {
+ if (this.props.isSelected) {
+ this.refs.listItem.focus();
+ }
+ if (this.props.intersectionObserver) {
+ this.props.intersectionObserver.observe(this.refs.listItem);
+ }
+
+ const { connector, item, requestFilterTypes } = this.props;
+ // Filtering XHR & WS require to lazily fetch requestHeaders & responseHeaders
+ if (requestFilterTypes.xhr || requestFilterTypes.ws) {
+ fetchNetworkUpdatePacket(connector.requestData, item, [
+ "requestHeaders",
+ "responseHeaders",
+ ]);
+ }
+ }
+
+ // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
+ UNSAFE_componentWillReceiveProps(nextProps) {
+ const { connector, item, requestFilterTypes } = nextProps;
+ // Filtering XHR & WS require to lazily fetch requestHeaders & responseHeaders
+ if (requestFilterTypes.xhr || requestFilterTypes.ws) {
+ fetchNetworkUpdatePacket(connector.requestData, item, [
+ "requestHeaders",
+ "responseHeaders",
+ ]);
+ }
+ }
+
+ shouldComponentUpdate(nextProps) {
+ return (
+ !propertiesEqual(
+ UPDATED_REQ_ITEM_PROPS,
+ this.props.item,
+ nextProps.item
+ ) ||
+ !propertiesEqual(UPDATED_REQ_PROPS, this.props, nextProps) ||
+ this.props.columns !== nextProps.columns
+ );
+ }
+
+ componentDidUpdate(prevProps) {
+ if (!prevProps.isSelected && this.props.isSelected) {
+ this.refs.listItem.focus();
+ if (this.props.onFocusedNodeChange) {
+ this.props.onFocusedNodeChange();
+ }
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.props.intersectionObserver) {
+ this.props.intersectionObserver.unobserve(this.refs.listItem);
+ }
+ }
+
+ render() {
+ const {
+ blocked,
+ connector,
+ columns,
+ item,
+ index,
+ isSelected,
+ isVisible,
+ firstRequestStartedMs,
+ fromCache,
+ networkActionOpen,
+ onDoubleClick,
+ onDragStart,
+ onContextMenu,
+ onMouseDown,
+ onWaterfallMouseDown,
+ selectedActionBarTabId,
+ } = this.props;
+
+ const classList = ["request-list-item", index % 2 ? "odd" : "even"];
+ isSelected && classList.push("selected");
+ fromCache && classList.push("fromCache");
+ blocked && classList.push("blocked");
+
+ return dom.tr(
+ {
+ ref: "listItem",
+ className: classList.join(" "),
+ "data-id": item.id,
+ draggable:
+ !blocked &&
+ networkActionOpen &&
+ selectedActionBarTabId === PANELS.BLOCKING,
+ tabIndex: 0,
+ onContextMenu,
+ onMouseDown,
+ onDoubleClick,
+ onDragStart,
+ },
+ ...COLUMN_COMPONENTS.filter(({ column }) => columns[column]).map(
+ ({ column, ColumnComponent, props: columnProps }) => {
+ return ColumnComponent({
+ key: column,
+ item,
+ ...(columnProps || []).reduce((acc, keyOrObject) => {
+ if (typeof keyOrObject == "string") {
+ acc[keyOrObject] = this.props[keyOrObject];
+ } else {
+ Object.assign(acc, keyOrObject);
+ }
+ return acc;
+ }, {}),
+ });
+ }
+ ),
+ ...RESPONSE_HEADERS.filter(header => columns[header]).map(header =>
+ RequestListColumnResponseHeader({
+ connector,
+ item,
+ header,
+ })
+ ),
+ // The last column is Waterfall (aka Timeline)
+ columns.waterfall &&
+ RequestListColumnWaterfall({
+ connector,
+ firstRequestStartedMs,
+ item,
+ onWaterfallMouseDown,
+ isVisible,
+ })
+ );
+ }
+}
+
+module.exports = RequestListItem;
diff --git a/devtools/client/netmonitor/src/components/request-list/moz.build b/devtools/client/netmonitor/src/components/request-list/moz.build
new file mode 100644
index 0000000000..22f0602b00
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/request-list/moz.build
@@ -0,0 +1,29 @@
+# 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/.
+
+DevToolsModules(
+ "RequestList.js",
+ "RequestListColumnContentSize.js",
+ "RequestListColumnCookies.js",
+ "RequestListColumnDomain.js",
+ "RequestListColumnFile.js",
+ "RequestListColumnInitiator.js",
+ "RequestListColumnMethod.js",
+ "RequestListColumnPriority.js",
+ "RequestListColumnProtocol.js",
+ "RequestListColumnRemoteIP.js",
+ "RequestListColumnResponseHeader.js",
+ "RequestListColumnScheme.js",
+ "RequestListColumnSetCookies.js",
+ "RequestListColumnStatus.js",
+ "RequestListColumnTime.js",
+ "RequestListColumnTransferredSize.js",
+ "RequestListColumnType.js",
+ "RequestListColumnUrl.js",
+ "RequestListColumnWaterfall.js",
+ "RequestListContent.js",
+ "RequestListEmptyNotice.js",
+ "RequestListHeader.js",
+ "RequestListItem.js",
+)
diff --git a/devtools/client/netmonitor/src/components/search/SearchPanel.js b/devtools/client/netmonitor/src/components/search/SearchPanel.js
new file mode 100644
index 0000000000..11301a7d9c
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/SearchPanel.js
@@ -0,0 +1,264 @@
+/* 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,
+ createRef,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const { div, span } = dom;
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const {
+ PANELS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const TreeViewClass = require("resource://devtools/client/shared/components/tree/TreeView.js");
+const TreeView = createFactory(TreeViewClass);
+const LabelCell = createFactory(
+ require("resource://devtools/client/shared/components/tree/LabelCell.js")
+);
+const {
+ SearchProvider,
+} = require("resource://devtools/client/netmonitor/src/components/search/search-provider.js");
+const Toolbar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/Toolbar.js")
+);
+const StatusBar = createFactory(
+ require("resource://devtools/client/netmonitor/src/components/search/StatusBar.js")
+);
+const {
+ limitTooltipLength,
+} = require("resource://devtools/client/netmonitor/src/utils/tooltips.js");
+// There are two levels in the search panel tree hierarchy:
+// 0: Resource - represents the source request object
+// 1: Search Result - represents a match coming from the parent resource
+const RESOURCE_LEVEL = 0;
+const SEARCH_RESULT_LEVEL = 1;
+
+/**
+ * This component is responsible for rendering all search results
+ * coming from the current search.
+ */
+class SearchPanel extends Component {
+ static get propTypes() {
+ return {
+ clearSearchResults: PropTypes.func.isRequired,
+ openSearch: PropTypes.func.isRequired,
+ closeSearch: PropTypes.func.isRequired,
+ search: PropTypes.func.isRequired,
+ caseSensitive: PropTypes.bool,
+ connector: PropTypes.object.isRequired,
+ addSearchQuery: PropTypes.func.isRequired,
+ query: PropTypes.string.isRequired,
+ results: PropTypes.array,
+ navigate: PropTypes.func.isRequired,
+ isDisplaying: PropTypes.bool.isRequired,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+
+ this.searchboxRef = createRef();
+ this.renderValue = this.renderValue.bind(this);
+ this.renderLabel = this.renderLabel.bind(this);
+ this.onClickTreeRow = this.onClickTreeRow.bind(this);
+ this.provider = SearchProvider;
+ }
+
+ componentDidMount() {
+ if (this.searchboxRef) {
+ this.searchboxRef.current.focus();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.isDisplaying && !prevProps.isDisplaying) {
+ this.searchboxRef.current.focus();
+ }
+ }
+
+ onClickTreeRow(path, event, member) {
+ if (member.object.parentResource) {
+ this.props.navigate(member.object);
+ }
+ }
+
+ /**
+ * Custom TreeView label rendering. The search result
+ * value isn't rendered in separate column, but in the
+ * same column as the label (to save space).
+ */
+ renderLabel(props) {
+ const { member } = props;
+ const level = member.level || 0;
+ const className = level == RESOURCE_LEVEL ? "resourceCell" : "resultCell";
+
+ // Customize label rendering by adding a suffix/value
+ const renderSuffix = () => {
+ return dom.span(
+ {
+ className,
+ },
+ " ",
+ this.renderValue(props)
+ );
+ };
+
+ return LabelCell({
+ ...props,
+ title:
+ member.level == 1
+ ? limitTooltipLength(member.object.value)
+ : this.provider.getResourceTooltipLabel(member.object),
+ renderSuffix,
+ });
+ }
+
+ renderTree() {
+ const { results } = this.props;
+ return TreeView({
+ object: results,
+ provider: this.provider,
+ expandableStrings: false,
+ renderLabelCell: this.renderLabel,
+ columns: [],
+ onClickRow: this.onClickTreeRow,
+ });
+ }
+
+ /**
+ * Custom tree value rendering. This method is responsible for
+ * rendering highlighted query string within the search result
+ * result tree.
+ */
+ renderValue(props) {
+ const { member } = props;
+ const { query, caseSensitive } = this.props;
+
+ // Handle only second level (zero based) that displays
+ // the search result. Find the query string inside the
+ // search result value (`props.object`) and render it
+ // within a span element with proper class name.
+ // level 0 = resource name
+ if (member.level === SEARCH_RESULT_LEVEL) {
+ const { object } = member;
+
+ // Handles multiple matches in a string
+ if (object.startIndex && object.startIndex.length > 1) {
+ let indexStart = 0;
+ const allMatches = object.startIndex.map((match, index) => {
+ if (index === 0) {
+ indexStart = match - 50;
+ }
+
+ const highlightedMatch = [
+ span(
+ { key: "match-" + match },
+ object.value.substring(indexStart, match - query.length)
+ ),
+ span(
+ {
+ className: "query-match",
+ key: "match-" + match + "-highlight",
+ },
+ object.value.substring(match - query.length, match)
+ ),
+ ];
+
+ indexStart = match;
+
+ return highlightedMatch;
+ });
+
+ return span(
+ {
+ title: limitTooltipLength(object.value),
+ },
+ allMatches
+ );
+ }
+
+ const indexStart = caseSensitive
+ ? object.value.indexOf(query)
+ : object.value.toLowerCase().indexOf(query.toLowerCase());
+ const indexEnd = indexStart + query.length;
+
+ // Handles a match in a string
+ if (indexStart >= 0) {
+ return span(
+ { title: limitTooltipLength(object.value) },
+ span({}, object.value.substring(0, indexStart)),
+ span(
+ { className: "query-match" },
+ object.value.substring(indexStart, indexStart + query.length)
+ ),
+ span({}, object.value.substring(indexEnd, object.value.length))
+ );
+ }
+
+ // Default for key:value matches where query might not
+ // be present in the value, but found in the key.
+ return span(
+ { title: limitTooltipLength(object.value) },
+ span({}, object.value)
+ );
+ }
+
+ return this.provider.getValue(member.object);
+ }
+
+ render() {
+ const {
+ openSearch,
+ closeSearch,
+ clearSearchResults,
+ connector,
+ addSearchQuery,
+ search,
+ } = this.props;
+ return div(
+ { className: "search-panel", style: { width: "100%" } },
+ Toolbar({
+ searchboxRef: this.searchboxRef,
+ openSearch,
+ closeSearch,
+ clearSearchResults,
+ addSearchQuery,
+ search,
+ connector,
+ }),
+ div(
+ { className: "search-panel-content", style: { width: "100%" } },
+ this.renderTree()
+ ),
+ StatusBar()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ query: state.search.query,
+ caseSensitive: state.search.caseSensitive,
+ results: state.search.results,
+ ongoingSearch: state.search.ongoingSearch,
+ isDisplaying: state.ui.selectedActionBarTabId === PANELS.SEARCH,
+ status: state.search.status,
+ }),
+ dispatch => ({
+ closeSearch: () => dispatch(Actions.closeSearch()),
+ openSearch: () => dispatch(Actions.openSearch()),
+ search: () => dispatch(Actions.search()),
+ clearSearchResults: () => dispatch(Actions.clearSearchResults()),
+ addSearchQuery: query => dispatch(Actions.addSearchQuery(query)),
+ navigate: searchResult => dispatch(Actions.navigate(searchResult)),
+ })
+)(SearchPanel);
diff --git a/devtools/client/netmonitor/src/components/search/StatusBar.js b/devtools/client/netmonitor/src/components/search/StatusBar.js
new file mode 100644
index 0000000000..31ecdeffe9
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/StatusBar.js
@@ -0,0 +1,97 @@
+/* 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 PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ getSearchStatus,
+ getSearchResultCount,
+ getSearchResourceCount,
+} = require("resource://devtools/client/netmonitor/src/selectors/index.js");
+const { PluralForm } = require("resource://devtools/shared/plural-form.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const { div, span } = dom;
+const {
+ SEARCH_STATUS,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+
+/**
+ * Displays the number of lines found for results and resource count (files)
+ */
+class StatusBar extends Component {
+ static get propTypes() {
+ return {
+ status: PropTypes.string,
+ resultsCount: PropTypes.string,
+ resourceCount: PropTypes.string,
+ };
+ }
+
+ getSearchStatusDoneLabel(lines, files) {
+ const matchingLines = PluralForm.get(
+ lines,
+ L10N.getStr("netmonitor.search.status.labels.matchingLines")
+ ).replace("#1", lines);
+ const matchingFiles = PluralForm.get(
+ files,
+ L10N.getStr("netmonitor.search.status.labels.fileCount")
+ ).replace("#1", files);
+
+ return L10N.getFormatStr(
+ "netmonitor.search.status.labels.done",
+ matchingLines,
+ matchingFiles
+ );
+ }
+
+ renderStatus() {
+ const { status, resultsCount, resourceCount } = this.props;
+
+ switch (status) {
+ case SEARCH_STATUS.FETCHING:
+ return L10N.getStr("netmonitor.search.status.labels.fetching");
+ case SEARCH_STATUS.DONE:
+ return this.getSearchStatusDoneLabel(resultsCount, resourceCount);
+ case SEARCH_STATUS.ERROR:
+ return L10N.getStr("netmonitor.search.status.labels.error");
+ case SEARCH_STATUS.CANCELED:
+ return L10N.getStr("netmonitor.search.status.labels.canceled");
+ default:
+ return "";
+ }
+ }
+
+ render() {
+ const { status } = this.props;
+ return div(
+ { className: "devtools-toolbar devtools-toolbar-bottom" },
+ div(
+ {
+ className: "status-bar-label",
+ title: this.renderStatus(),
+ },
+ this.renderStatus(),
+ status === SEARCH_STATUS.FETCHING
+ ? span({ className: "img loader" })
+ : ""
+ )
+ );
+ }
+}
+
+module.exports = connect(state => ({
+ status: getSearchStatus(state),
+ resultsCount: getSearchResultCount(state),
+ resourceCount: getSearchResourceCount(state),
+}))(StatusBar);
diff --git a/devtools/client/netmonitor/src/components/search/Toolbar.js b/devtools/client/netmonitor/src/components/search/Toolbar.js
new file mode 100644
index 0000000000..0f39cfa17a
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/Toolbar.js
@@ -0,0 +1,160 @@
+/* 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,
+ createFactory,
+} = require("resource://devtools/client/shared/vendor/react.js");
+const {
+ connect,
+} = require("resource://devtools/client/shared/redux/visibility-handler-connect.js");
+const {
+ FILTER_SEARCH_DELAY,
+} = require("resource://devtools/client/netmonitor/src/constants.js");
+const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
+const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js");
+const dom = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
+const {
+ L10N,
+} = require("resource://devtools/client/netmonitor/src/utils/l10n.js");
+const { button, span, div } = dom;
+
+// Components
+const SearchBox = createFactory(
+ require("resource://devtools/client/shared/components/SearchBox.js")
+);
+
+/**
+ * Network Search toolbar component.
+ *
+ * Provides tools for greater control over search.
+ */
+class Toolbar extends Component {
+ static get propTypes() {
+ return {
+ searchboxRef: PropTypes.object.isRequired,
+ clearSearchResults: PropTypes.func.isRequired,
+ search: PropTypes.func.isRequired,
+ closeSearch: PropTypes.func.isRequired,
+ addSearchQuery: PropTypes.func.isRequired,
+ clearSearchResultAndCancel: PropTypes.func.isRequired,
+ caseSensitive: PropTypes.bool.isRequired,
+ toggleCaseSensitiveSearch: PropTypes.func.isRequired,
+ connector: PropTypes.object.isRequired,
+ query: PropTypes.string,
+ };
+ }
+
+ /**
+ * Render a separator.
+ */
+ renderSeparator() {
+ return span({ className: "devtools-separator" });
+ }
+
+ /**
+ * Handles what we do when key is pressed in search input.
+ * @param event
+ * @param conn
+ */
+ onKeyDown(event, connector) {
+ switch (event.key) {
+ case "Escape":
+ event.preventDefault();
+ this.props.closeSearch();
+ break;
+ case "Enter":
+ event.preventDefault();
+ this.props.addSearchQuery(event.target.value);
+ this.props.search(connector, event.target.value);
+ break;
+ }
+ }
+
+ renderModifiers() {
+ return div(
+ { className: "search-modifiers" },
+ span({ className: "pipe-divider" }),
+ this.renderCaseSensitiveButton()
+ );
+ }
+
+ /**
+ * Render a clear button to clear search results.
+ */
+ renderClearButton() {
+ return button({
+ className:
+ "devtools-button devtools-clear-icon ws-frames-list-clear-button",
+ title: L10N.getStr("netmonitor.search.toolbar.clear"),
+ onClick: () => {
+ this.props.clearSearchResults();
+ },
+ });
+ }
+
+ /**
+ * Render the case sensitive search modifier button
+ */
+ renderCaseSensitiveButton() {
+ const { caseSensitive, toggleCaseSensitiveSearch } = this.props;
+ const active = caseSensitive ? "checked" : "";
+
+ return button({
+ id: "devtools-network-search-caseSensitive",
+ className: `devtools-button ${active}`,
+ title: L10N.getStr("netmonitor.search.toolbar.caseSensitive"),
+ onClick: toggleCaseSensitiveSearch,
+ });
+ }
+
+ /**
+ * Render Search box.
+ */
+ renderFilterBox() {
+ const { addSearchQuery, clearSearchResultAndCancel, connector, query } =
+ this.props;
+ return SearchBox({
+ keyShortcut: "CmdOrCtrl+Shift+F",
+ placeholder: L10N.getStr("netmonitor.search.toolbar.inputPlaceholder"),
+ type: "search",
+ delay: FILTER_SEARCH_DELAY,
+ ref: this.props.searchboxRef,
+ value: query,
+ onClearButtonClick: () => clearSearchResultAndCancel(),
+ onChange: newQuery => addSearchQuery(newQuery),
+ onKeyDown: event => this.onKeyDown(event, connector),
+ });
+ }
+
+ render() {
+ return div(
+ {
+ id: "netmonitor-toolbar-container",
+ className: "devtools-toolbar devtools-input-toolbar",
+ },
+ this.renderFilterBox(),
+ this.renderModifiers()
+ );
+ }
+}
+
+module.exports = connect(
+ state => ({
+ caseSensitive: state.search.caseSensitive,
+ query: state.search.query,
+ }),
+ dispatch => ({
+ closeSearch: () => dispatch(Actions.closeSearch()),
+ openSearch: () => dispatch(Actions.openSearch()),
+ clearSearchResultAndCancel: () =>
+ dispatch(Actions.clearSearchResultAndCancel()),
+ toggleCaseSensitiveSearch: () =>
+ dispatch(Actions.toggleCaseSensitiveSearch()),
+ search: (connector, query) => dispatch(Actions.search(connector, query)),
+ addSearchQuery: query => dispatch(Actions.addSearchQuery(query)),
+ })
+)(Toolbar);
diff --git a/devtools/client/netmonitor/src/components/search/moz.build b/devtools/client/netmonitor/src/components/search/moz.build
new file mode 100644
index 0000000000..7c48392d10
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/moz.build
@@ -0,0 +1,10 @@
+# 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/.
+
+DevToolsModules(
+ "search-provider.js",
+ "SearchPanel.js",
+ "StatusBar.js",
+ "Toolbar.js",
+)
diff --git a/devtools/client/netmonitor/src/components/search/search-provider.js b/devtools/client/netmonitor/src/components/search/search-provider.js
new file mode 100644
index 0000000000..d076f35856
--- /dev/null
+++ b/devtools/client/netmonitor/src/components/search/search-provider.js
@@ -0,0 +1,91 @@
+/* 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 {
+ ObjectProvider,
+} = require("resource://devtools/client/shared/components/tree/ObjectProvider.js");
+const {
+ getFileName,
+} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js");
+
+/**
+ * This provider is responsible for providing data from the
+ * search reducer to the SearchPanel.
+ */
+const SearchProvider = {
+ ...ObjectProvider,
+
+ getChildren(object) {
+ if (Array.isArray(object)) {
+ return object;
+ } else if (object.resource) {
+ return object.results;
+ } else if (object.type) {
+ return [];
+ }
+ return ObjectProvider.getLabel(object);
+ },
+
+ hasChildren(object) {
+ return !!this.getChildren(object).length;
+ },
+
+ getLabel(object) {
+ if (object.resource) {
+ return this.getResourceLabel(object);
+ } else if (object.label) {
+ return object.label;
+ }
+ return ObjectProvider.getLabel(object);
+ },
+
+ getValue(object) {
+ if (object.resource) {
+ return "";
+ } else if (object.type) {
+ return object.value;
+ }
+ return ObjectProvider.getValue(object);
+ },
+
+ getKey(object) {
+ if (object.resource) {
+ return object.resource.id;
+ } else if (object.type) {
+ return object.key;
+ }
+ return ObjectProvider.getKey(object);
+ },
+
+ getType(object) {
+ if (object.resource) {
+ return "resource";
+ } else if (object.type) {
+ return "result";
+ }
+ return ObjectProvider.getType(object);
+ },
+
+ getResourceTooltipLabel(object) {
+ const { resource } = object;
+ if (resource.urlDetails?.url) {
+ return resource.urlDetails.url;
+ }
+
+ return this.getResourceLabel(object);
+ },
+
+ getResourceLabel(object) {
+ return (
+ getFileName(object.resource.urlDetails.baseNameWithQuery) ||
+ object.resource.urlDetails.host
+ );
+ },
+};
+
+module.exports = {
+ SearchProvider,
+};