From 6bf0a5cb5034a7e684dcc3500e841785237ce2dd Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 19:32:43 +0200 Subject: Adding upstream version 1:115.7.0. Signed-off-by: Daniel Baumann --- devtools/client/netmonitor/docs/architecture.md | 30 + devtools/client/netmonitor/index.html | 17 + devtools/client/netmonitor/initializer.js | 109 + devtools/client/netmonitor/moz.build | 19 + devtools/client/netmonitor/panel.js | 37 + devtools/client/netmonitor/src/actions/batching.js | 50 + devtools/client/netmonitor/src/actions/filters.js | 58 + .../netmonitor/src/actions/http-custom-request.js | 128 + devtools/client/netmonitor/src/actions/index.js | 32 + devtools/client/netmonitor/src/actions/messages.js | 188 ++ devtools/client/netmonitor/src/actions/moz.build | 18 + .../netmonitor/src/actions/request-blocking.js | 155 + devtools/client/netmonitor/src/actions/requests.js | 183 + devtools/client/netmonitor/src/actions/search.js | 316 ++ .../client/netmonitor/src/actions/selection.js | 80 + devtools/client/netmonitor/src/actions/sort.js | 20 + .../netmonitor/src/actions/timing-markers.js | 22 + devtools/client/netmonitor/src/actions/ui.js | 257 ++ devtools/client/netmonitor/src/api.js | 216 ++ devtools/client/netmonitor/src/app.js | 135 + .../netmonitor/src/assets/icons/arrow-up.svg | 6 + .../client/netmonitor/src/assets/icons/play.svg | 8 + .../client/netmonitor/src/assets/icons/shield.svg | 6 + .../client/netmonitor/src/assets/icons/turtle.svg | 6 + .../src/assets/styles/CustomRequestPanel.css | 181 + .../src/assets/styles/HTTPCustomRequestPanel.css | 379 +++ .../netmonitor/src/assets/styles/HeadersPanel.css | 210 ++ .../src/assets/styles/NetworkActionBar.css | 11 + .../src/assets/styles/NetworkDetailsBar.css | 574 ++++ .../src/assets/styles/RequestBlockingPanel.css | 184 + .../netmonitor/src/assets/styles/RequestList.css | 653 ++++ .../src/assets/styles/StatisticsPanel.css | 171 + .../netmonitor/src/assets/styles/StatusBar.css | 62 + .../netmonitor/src/assets/styles/StatusCode.css | 100 + .../netmonitor/src/assets/styles/Toolbar.css | 102 + .../netmonitor/src/assets/styles/UrlPreview.css | 100 + .../netmonitor/src/assets/styles/messages.css | 165 + .../netmonitor/src/assets/styles/netmonitor.css | 84 + .../client/netmonitor/src/assets/styles/search.css | 155 + .../netmonitor/src/assets/styles/variables.css | 45 + devtools/client/netmonitor/src/components/App.js | 119 + .../src/components/CustomRequestPanel.js | 371 ++ .../netmonitor/src/components/DropHarHandler.js | 141 + .../netmonitor/src/components/MonitorPanel.js | 271 ++ .../netmonitor/src/components/NetworkActionBar.js | 136 + .../netmonitor/src/components/SecurityState.js | 78 + .../netmonitor/src/components/SourceEditor.js | 137 + .../netmonitor/src/components/StatisticsPanel.js | 413 +++ .../client/netmonitor/src/components/StatusBar.js | 175 + .../client/netmonitor/src/components/StatusCode.js | 129 + .../netmonitor/src/components/TabboxPanel.js | 242 ++ .../client/netmonitor/src/components/Toolbar.js | 688 ++++ .../src/components/messages/ColumnData.js | 60 + .../src/components/messages/ColumnEventName.js | 40 + .../src/components/messages/ColumnFinBit.js | 40 + .../src/components/messages/ColumnLastEventId.js | 40 + .../src/components/messages/ColumnMaskBit.js | 40 + .../src/components/messages/ColumnOpCode.js | 40 + .../src/components/messages/ColumnRetry.js | 40 + .../src/components/messages/ColumnSize.js | 43 + .../src/components/messages/ColumnTime.js | 56 + .../src/components/messages/MessageFilterMenu.js | 122 + .../src/components/messages/MessageListContent.js | 398 +++ .../components/messages/MessageListContextMenu.js | 62 + .../src/components/messages/MessageListHeader.js | 121 + .../messages/MessageListHeaderContextMenu.js | 61 + .../src/components/messages/MessageListItem.js | 127 + .../src/components/messages/MessagePayload.js | 403 +++ .../src/components/messages/MessagesView.js | 173 + .../netmonitor/src/components/messages/RawData.js | 34 + .../src/components/messages/StatusBar.js | 130 + .../netmonitor/src/components/messages/Toolbar.js | 152 + .../netmonitor/src/components/messages/cbor.js | 270 ++ .../netmonitor/src/components/messages/moz.build | 32 + .../netmonitor/src/components/messages/msgpack.js | 365 ++ .../src/components/messages/parsers/moz.build | 11 + .../messages/parsers/signalr/HandshakeProtocol.js | 82 + .../messages/parsers/signalr/IHubProtocol.js | 33 + .../messages/parsers/signalr/JSONHubProtocol.js | 120 + .../messages/parsers/signalr/TextMessageFormat.js | 33 + .../components/messages/parsers/signalr/Utils.js | 25 + .../components/messages/parsers/signalr/index.js | 13 + .../components/messages/parsers/signalr/moz.build | 12 + .../messages/parsers/socket-io/binary.js | 48 + .../parsers/socket-io/component-emitter.js | 84 + .../components/messages/parsers/socket-io/index.js | 292 ++ .../messages/parsers/socket-io/is-buffer.js | 40 + .../messages/parsers/socket-io/moz.build | 10 + .../components/messages/parsers/sockjs/index.js | 56 + .../components/messages/parsers/sockjs/moz.build | 7 + .../src/components/messages/parsers/stomp/byte.js | 25 + .../src/components/messages/parsers/stomp/frame.js | 204 ++ .../src/components/messages/parsers/stomp/index.js | 40 + .../components/messages/parsers/stomp/moz.build | 10 + .../components/messages/parsers/stomp/parser.js | 230 ++ .../messages/parsers/wamp/arrayParser.js | 274 ++ .../src/components/messages/parsers/wamp/moz.build | 8 + .../messages/parsers/wamp/serializers.js | 73 + .../client/netmonitor/src/components/moz.build | 28 + .../new-request/HTTPCustomRequestPanel.js | 511 +++ .../src/components/new-request/InputMap.js | 211 ++ .../src/components/new-request/moz.build | 8 + .../src/components/previews/FontPreview.js | 135 + .../src/components/previews/HtmlPreview.js | 75 + .../src/components/previews/ImagePreview.js | 91 + .../src/components/previews/SourcePreview.js | 178 + .../src/components/previews/UrlPreview.js | 290 ++ .../netmonitor/src/components/previews/moz.build | 11 + .../request-blocking/RequestBlockingPanel.js | 350 ++ .../src/components/request-blocking/moz.build | 7 + .../src/components/request-details/CachePanel.js | 144 + .../src/components/request-details/CookiesPanel.js | 225 ++ .../src/components/request-details/HeadersPanel.js | 850 +++++ .../request-details/NetworkDetailsBar.js | 106 + .../components/request-details/PropertiesView.js | 247 ++ .../src/components/request-details/RequestPanel.js | 301 ++ .../components/request-details/ResponsePanel.js | 496 +++ .../components/request-details/SecurityPanel.js | 283 ++ .../components/request-details/StackTracePanel.js | 81 + .../src/components/request-details/TimingsPanel.js | 229 ++ .../src/components/request-details/moz.build | 16 + .../src/components/request-list/RequestList.js | 50 + .../request-list/RequestListColumnContentSize.js | 38 + .../request-list/RequestListColumnCookies.js | 61 + .../request-list/RequestListColumnDomain.js | 66 + .../request-list/RequestListColumnFile.js | 91 + .../request-list/RequestListColumnInitiator.js | 65 + .../request-list/RequestListColumnMethod.js | 33 + .../request-list/RequestListColumnPriority.js | 36 + .../request-list/RequestListColumnProtocol.js | 43 + .../request-list/RequestListColumnRemoteIP.js | 43 + .../RequestListColumnResponseHeader.js | 59 + .../request-list/RequestListColumnScheme.js | 38 + .../request-list/RequestListColumnSetCookies.js | 61 + .../request-list/RequestListColumnStatus.js | 39 + .../request-list/RequestListColumnTime.js | 91 + .../RequestListColumnTransferredSize.js | 99 + .../request-list/RequestListColumnType.js | 45 + .../request-list/RequestListColumnUrl.js | 89 + .../request-list/RequestListColumnWaterfall.js | 209 ++ .../components/request-list/RequestListContent.js | 524 +++ .../request-list/RequestListEmptyNotice.js | 107 + .../components/request-list/RequestListHeader.js | 731 ++++ .../src/components/request-list/RequestListItem.js | 412 +++ .../src/components/request-list/moz.build | 29 + .../src/components/search/SearchPanel.js | 264 ++ .../netmonitor/src/components/search/StatusBar.js | 97 + .../netmonitor/src/components/search/Toolbar.js | 160 + .../netmonitor/src/components/search/moz.build | 10 + .../src/components/search/search-provider.js | 91 + .../src/connector/firefox-data-provider.js | 832 +++++ .../src/connector/har-metadata-collector.js | 97 + devtools/client/netmonitor/src/connector/index.js | 543 +++ devtools/client/netmonitor/src/connector/moz.build | 9 + devtools/client/netmonitor/src/constants.js | 597 ++++ devtools/client/netmonitor/src/create-store.js | 172 + devtools/client/netmonitor/src/har/README.md | 42 + .../client/netmonitor/src/har/har-automation.js | 253 ++ .../client/netmonitor/src/har/har-builder-utils.js | 30 + devtools/client/netmonitor/src/har/har-builder.js | 656 ++++ .../client/netmonitor/src/har/har-collector.js | 488 +++ devtools/client/netmonitor/src/har/har-exporter.js | 230 ++ devtools/client/netmonitor/src/har/har-importer.js | 166 + .../client/netmonitor/src/har/har-menu-utils.js | 118 + devtools/client/netmonitor/src/har/har-utils.js | 167 + devtools/client/netmonitor/src/har/moz.build | 19 + .../src/har/test/browser-harautomation.ini | 16 + .../client/netmonitor/src/har/test/browser.ini | 29 + .../src/har/test/browser_harautomation_simple.js | 35 + .../har/test/browser_net_har_copy_all_as_har.js | 220 ++ .../src/har/test/browser_net_har_import.js | 149 + .../src/har/test/browser_net_har_import_no-mime.js | 78 + .../src/har/test/browser_net_har_multipage.js | 153 + .../src/har/test/browser_net_har_post_data.js | 51 + .../har/test/browser_net_har_post_data_on_get.js | 43 + .../har/test/browser_net_har_throttle_upload.js | 69 + devtools/client/netmonitor/src/har/test/head.js | 45 + .../src/har/test/html_har_import-test-page.html | 51 + .../src/har/test/html_har_multipage_iframe.html | 24 + .../src/har/test/html_har_multipage_page.html | 30 + .../src/har/test/html_har_post-data-test-page.html | 55 + .../src/har/test/sjs_cache-test-server.sjs | 14 + .../src/har/test/sjs_cookies-test-server.sjs | 10 + .../client/netmonitor/src/middleware/batching.js | 146 + .../netmonitor/src/middleware/event-telemetry.js | 192 ++ .../client/netmonitor/src/middleware/moz.build | 11 + devtools/client/netmonitor/src/middleware/prefs.js | 116 + .../netmonitor/src/middleware/request-blocking.js | 58 + .../client/netmonitor/src/middleware/throttling.js | 26 + devtools/client/netmonitor/src/moz.build | 23 + .../client/netmonitor/src/reducers/batching.js | 27 + devtools/client/netmonitor/src/reducers/filters.js | 102 + devtools/client/netmonitor/src/reducers/index.js | 47 + .../client/netmonitor/src/reducers/messages.js | 335 ++ devtools/client/netmonitor/src/reducers/moz.build | 16 + .../netmonitor/src/reducers/request-blocking.js | 187 ++ .../client/netmonitor/src/reducers/requests.js | 313 ++ devtools/client/netmonitor/src/reducers/search.js | 118 + devtools/client/netmonitor/src/reducers/sort.js | 48 + .../netmonitor/src/reducers/timing-markers.js | 78 + devtools/client/netmonitor/src/reducers/ui.js | 260 ++ devtools/client/netmonitor/src/selectors/index.js | 13 + .../client/netmonitor/src/selectors/messages.js | 162 + devtools/client/netmonitor/src/selectors/moz.build | 12 + .../client/netmonitor/src/selectors/requests.js | 198 ++ devtools/client/netmonitor/src/selectors/search.js | 33 + .../netmonitor/src/selectors/timing-markers.js | 18 + devtools/client/netmonitor/src/selectors/ui.js | 81 + .../netmonitor/src/utils/context-menu-utils.js | 32 + devtools/client/netmonitor/src/utils/doc-utils.js | 224 ++ .../src/utils/filter-autocomplete-provider.js | 209 ++ .../netmonitor/src/utils/filter-predicates.js | 137 + .../netmonitor/src/utils/filter-text-utils.js | 291 ++ .../client/netmonitor/src/utils/firefox/moz.build | 8 + .../src/utils/firefox/open-request-in-tab.js | 67 + .../client/netmonitor/src/utils/format-utils.js | 132 + .../netmonitor/src/utils/headers-provider.js | 90 + devtools/client/netmonitor/src/utils/l10n.js | 11 + devtools/client/netmonitor/src/utils/moz.build | 27 + .../netmonitor/src/utils/open-request-in-tab.js | 63 + devtools/client/netmonitor/src/utils/powershell.js | 142 + devtools/client/netmonitor/src/utils/prefs.js | 18 + .../netmonitor/src/utils/request-blocking.js | 13 + .../client/netmonitor/src/utils/request-utils.js | 769 +++++ .../client/netmonitor/src/utils/sort-predicates.js | 319 ++ devtools/client/netmonitor/src/utils/sort-utils.js | 42 + devtools/client/netmonitor/src/utils/tooltips.js | 18 + .../src/widgets/HeadersPanelContextMenu.js | 137 + .../src/widgets/PropertiesViewContextMenu.js | 113 + .../src/widgets/RequestBlockingContextMenu.js | 78 + .../src/widgets/RequestListContextMenu.js | 793 +++++ .../src/widgets/RequestListHeaderContextMenu.js | 105 + .../netmonitor/src/widgets/WaterfallBackground.js | 163 + devtools/client/netmonitor/src/widgets/moz.build | 12 + devtools/client/netmonitor/src/workers/moz.build | 8 + .../client/netmonitor/src/workers/search/index.js | 25 + .../client/netmonitor/src/workers/search/moz.build | 10 + .../client/netmonitor/src/workers/search/search.js | 349 ++ .../client/netmonitor/src/workers/search/worker.js | 17 + devtools/client/netmonitor/test/.eslintrc.js | 7 + devtools/client/netmonitor/test/OstrichLicense.txt | 41 + devtools/client/netmonitor/test/browser.ini | 330 ++ devtools/client/netmonitor/test/browser_http3.ini | 11 + .../test/browser_net-ws-filter-freetext.js | 93 + .../test/browser_net_accessibility-01.js | 87 + .../test/browser_net_accessibility-02.js | 137 + .../netmonitor/test/browser_net_api-calls.js | 47 + .../netmonitor/test/browser_net_autoscroll.js | 114 + .../test/browser_net_background_update.js | 57 + .../netmonitor/test/browser_net_basic-search.js | 68 + .../netmonitor/test/browser_net_block-context.js | 135 + .../netmonitor/test/browser_net_block-csp.js | 111 + .../test/browser_net_block-draganddrop.js | 159 + .../test/browser_net_block-extensions.js | 103 + .../netmonitor/test/browser_net_block-pattern.js | 106 + .../test/browser_net_block-serviceworker.js | 58 + .../client/netmonitor/test/browser_net_block.js | 169 + .../client/netmonitor/test/browser_net_brotli.js | 81 + .../netmonitor/test/browser_net_cache_details.js | 102 + .../netmonitor/test/browser_net_cached-status.js | 130 + .../netmonitor/test/browser_net_cause_redirect.js | 80 + .../test/browser_net_cause_source_map.js | 60 + .../netmonitor/test/browser_net_charts-01.js | 153 + .../netmonitor/test/browser_net_charts-02.js | 72 + .../netmonitor/test/browser_net_charts-03.js | 195 ++ .../netmonitor/test/browser_net_charts-04.js | 117 + .../netmonitor/test/browser_net_charts-05.js | 94 + .../netmonitor/test/browser_net_charts-06.js | 62 + .../netmonitor/test/browser_net_charts-07.js | 97 + .../client/netmonitor/test/browser_net_clear.js | 145 + .../test/browser_net_column-resize-fit.js | 95 + .../test/browser_net_column_headers_tooltips.js | 30 + .../browser_net_column_slow-request-indicator.js | 69 + .../test/browser_net_columns_last_column.js | 64 + .../netmonitor/test/browser_net_columns_pref.js | 59 + .../netmonitor/test/browser_net_columns_reset.js | 43 + .../test/browser_net_columns_showhide.js | 181 + .../netmonitor/test/browser_net_columns_time.js | 61 + .../netmonitor/test/browser_net_complex-params.js | 310 ++ .../netmonitor/test/browser_net_content-type.js | 358 ++ .../netmonitor/test/browser_net_cookies_sorted.js | 85 + .../netmonitor/test/browser_net_copy_as_curl.js | 242 ++ .../netmonitor/test/browser_net_copy_as_fetch.js | 92 + .../test/browser_net_copy_as_powershell.js | 167 + .../netmonitor/test/browser_net_copy_headers.js | 105 + .../test/browser_net_copy_image_as_data_uri.js | 41 + .../netmonitor/test/browser_net_copy_params.js | 167 + .../netmonitor/test/browser_net_copy_response.js | 38 + .../test/browser_net_copy_svg_image_as_data_uri.js | 48 + .../client/netmonitor/test/browser_net_copy_url.js | 50 + .../netmonitor/test/browser_net_cors_requests.js | 54 + .../netmonitor/test/browser_net_curl-utils.js | 385 +++ .../netmonitor/test/browser_net_cyrillic-01.js | 64 + .../netmonitor/test/browser_net_cyrillic-02.js | 76 + .../netmonitor/test/browser_net_decode-params.js | 35 + .../netmonitor/test/browser_net_decode-url.js | 42 + .../netmonitor/test/browser_net_details_copy.js | 295 ++ .../test/browser_net_domain-not-found.js | 41 + .../test/browser_net_edit_resend_cancel.js | 68 + .../test/browser_net_edit_resend_caret.js | 102 + .../test/browser_net_edit_resend_with_filtering.js | 153 + .../netmonitor/test/browser_net_edit_resend_xhr.js | 135 + .../test/browser_net_error-boundary-01.js | 31 + .../netmonitor/test/browser_net_filter-01.js | 558 +++ .../netmonitor/test/browser_net_filter-02.js | 307 ++ .../netmonitor/test/browser_net_filter-03.js | 163 + .../netmonitor/test/browser_net_filter-04.js | 80 + .../test/browser_net_filter-autocomplete.js | 207 ++ .../netmonitor/test/browser_net_filter-flags.js | 435 +++ .../test/browser_net_filter-sts-search.js | 59 + .../test/browser_net_filter-value-preserved.js | 55 + .../test/browser_net_fission_switch_target.js | 54 + .../client/netmonitor/test/browser_net_fonts.js | 84 + .../netmonitor/test/browser_net_footer-summary.js | 114 + .../client/netmonitor/test/browser_net_frame.js | 272 ++ .../netmonitor/test/browser_net_header-docs.js | 74 + .../test/browser_net_header-ref-policy.js | 62 + .../test/browser_net_header-request-priority.js | 43 + .../test/browser_net_headers-alignment.js | 65 + .../test/browser_net_headers-link_clickable.js | 44 + .../netmonitor/test/browser_net_headers-resize.js | 279 ++ .../netmonitor/test/browser_net_headers_filter.js | 80 + .../netmonitor/test/browser_net_headers_sorted.js | 194 ++ .../netmonitor/test/browser_net_html-preview.js | 176 + .../test/browser_net_http3_request_details.js | 153 + .../netmonitor/test/browser_net_image-tooltip.js | 117 + .../netmonitor/test/browser_net_image_cache.js | 76 + .../netmonitor/test/browser_net_initiator.js | 291 ++ .../test/browser_net_internal-stylesheet.js | 37 + .../client/netmonitor/test/browser_net_json-b64.js | 103 + .../netmonitor/test/browser_net_json-empty.js | 79 + .../netmonitor/test/browser_net_json-long.js | 174 + .../netmonitor/test/browser_net_json-malformed.js | 97 + .../netmonitor/test/browser_net_json-nogrip.js | 51 + .../netmonitor/test/browser_net_json-null.js | 114 + .../test/browser_net_json-xssi-protection.js | 96 + .../test/browser_net_json_custom_mime.js | 133 + .../netmonitor/test/browser_net_json_text_mime.js | 136 + .../client/netmonitor/test/browser_net_jsonp.js | 179 + .../netmonitor/test/browser_net_large-response.js | 92 + .../test/browser_net_leak_on_tab_close.js | 20 + .../test/browser_net_new_request_panel.js | 98 + .../browser_net_new_request_panel_clear_button.js | 87 + ...browser_net_new_request_panel_content-length.js | 94 + .../browser_net_new_request_panel_context_menu.js | 208 ++ ...wser_net_new_request_panel_persisted_content.js | 149 + .../browser_net_new_request_panel_send_request.js | 166 + ...rowser_net_new_request_panel_sync_url_params.js | 194 ++ .../test/browser_net_open_in_debugger.js | 40 + .../test/browser_net_open_in_style_editor.js | 44 + .../test/browser_net_open_request_in_tab.js | 264 ++ .../netmonitor/test/browser_net_pane-collapse.js | 68 + .../test/browser_net_pane-network-details.js | 149 + .../netmonitor/test/browser_net_pane-toggle.js | 107 + .../netmonitor/test/browser_net_params_sorted.js | 83 + .../client/netmonitor/test/browser_net_pause.js | 151 + .../netmonitor/test/browser_net_persistent_logs.js | 77 + .../test/browser_net_post-data-json-payloads.js | 105 + ...data-raw-payloads-with-upload-stream-headers.js | 202 ++ .../test/browser_net_post-data-raw-payloads.js | 89 + .../netmonitor/test/browser_net_post-data.js | 195 ++ .../netmonitor/test/browser_net_prefs-and-l10n.js | 78 + .../netmonitor/test/browser_net_prefs-reload.js | 327 ++ .../netmonitor/test/browser_net_raw_headers.js | 132 + .../netmonitor/test/browser_net_reload-button.js | 30 + .../netmonitor/test/browser_net_reload-markers.js | 34 + .../netmonitor/test/browser_net_req-resp-bodies.js | 83 + .../client/netmonitor/test/browser_net_resend.js | 385 +++ .../netmonitor/test/browser_net_resend_cors.js | 132 + .../netmonitor/test/browser_net_resend_csp.js | 153 + .../netmonitor/test/browser_net_resend_headers.js | 89 + .../test/browser_net_resend_hidden_headers.js | 88 + .../netmonitor/test/browser_net_resend_xhr.js | 57 + .../test/browser_net_response_CORS_blocked.js | 117 + .../test/browser_net_response_node-expanded.js | 57 + .../netmonitor/test/browser_net_search-results.js | 233 ++ .../test/browser_net_security-details.js | 116 + .../netmonitor/test/browser_net_security-error.js | 38 + .../test/browser_net_security-icon-click.js | 75 + .../test/browser_net_security-redirect.js | 67 + .../netmonitor/test/browser_net_security-state.js | 109 + .../test/browser_net_security-tab-deselect.js | 67 + .../test/browser_net_security-tab-visibility.js | 142 + .../test/browser_net_security-warnings.js | 66 + .../test/browser_net_send-beacon-other-tab.js | 49 + .../netmonitor/test/browser_net_send-beacon.js | 44 + .../netmonitor/test/browser_net_server_timings.js | 74 + .../test/browser_net_service-worker-status.js | 112 + .../test/browser_net_set-cookie-same-site.js | 85 + .../test/browser_net_simple-request-data.js | 488 +++ .../test/browser_net_simple-request-details.js | 388 +++ .../netmonitor/test/browser_net_simple-request.js | 99 + .../client/netmonitor/test/browser_net_sort-01.js | 316 ++ .../client/netmonitor/test/browser_net_sort-02.js | 460 +++ .../netmonitor/test/browser_net_sort-reset.js | 284 ++ .../netmonitor/test/browser_net_sse-basic.js | 119 + .../test/browser_net_stacktraces-visibility.js | 86 + .../netmonitor/test/browser_net_statistics-01.js | 65 + .../netmonitor/test/browser_net_statistics-02.js | 74 + .../test/browser_net_statistics-edge-case.js | 112 + .../browser_net_status-bar-transferred-size.js | 77 + .../netmonitor/test/browser_net_status-bar.js | 60 + .../netmonitor/test/browser_net_status-codes.js | 213 ++ .../test/browser_net_streaming-response.js | 89 + .../netmonitor/test/browser_net_tabbar_focus.js | 90 + .../test/browser_net_telemetry_edit_resend.js | 71 + .../test/browser_net_telemetry_filters_changed.js | 100 + ...browser_net_telemetry_persist_toggle_changed.js | 81 + .../test/browser_net_telemetry_select_ws_frame.js | 83 + .../browser_net_telemetry_sidepanel_changed.js | 61 + .../test/browser_net_telemetry_throttle_changed.js | 50 + .../client/netmonitor/test/browser_net_throttle.js | 60 + .../test/browser_net_throttling_profiles.js | 67 + .../netmonitor/test/browser_net_timeline_ticks.js | 208 ++ .../netmonitor/test/browser_net_timing-division.js | 67 + .../test/browser_net_tracking-resources.js | 50 + .../test/browser_net_truncate-post-data.js | 78 + .../client/netmonitor/test/browser_net_truncate.js | 59 + .../netmonitor/test/browser_net_url-preview.js | 203 ++ .../netmonitor/test/browser_net_use_as_fetch.js | 85 + .../test/browser_net_view-source-debugger.js | 80 + .../netmonitor/test/browser_net_waterfall-click.js | 36 + .../test/browser_net_websocket_stacks.js | 94 + .../netmonitor/test/browser_net_worker_stacks.js | 119 + .../client/netmonitor/test/browser_net_ws-basic.js | 79 + .../client/netmonitor/test/browser_net_ws-clear.js | 84 + .../test/browser_net_ws-connection-closed.js | 54 + .../test/browser_net_ws-early-connection.js | 62 + .../test/browser_net_ws-filter-dropdown.js | 136 + .../netmonitor/test/browser_net_ws-filter-regex.js | 76 + .../browser_net_ws-json-action-cable-payload.js | 109 + .../netmonitor/test/browser_net_ws-json-payload.js | 112 + .../test/browser_net_ws-json-stomp-payload.js | 115 + .../test/browser_net_ws-keep-future-frames.js | 87 + .../netmonitor/test/browser_net_ws-limit-frames.js | 63 + .../test/browser_net_ws-limit-payload.js | 80 + .../test/browser_net_ws-messages-navigation.js | 106 + .../test/browser_net_ws-sockjs-stomp-payload.js | 115 + .../test/browser_net_ws-sse-persist-columns.js | 268 ++ .../test/browser_net_ws-stomp-payload.js | 115 + devtools/client/netmonitor/test/dropmarker.svg | 6 + .../client/netmonitor/test/file_ws_backend_wsh.py | 13 + devtools/client/netmonitor/test/head.js | 1493 ++++++++ .../netmonitor/test/html_api-calls-test-page.html | 45 + .../netmonitor/test/html_brotli-test-page.html | 41 + .../netmonitor/test/html_cache-test-page.html | 28 + .../netmonitor/test/html_cause-test-page.html | 98 + .../html_content-type-without-cache-test-page.html | 47 + .../client/netmonitor/test/html_copy-as-curl.html | 33 + .../netmonitor/test/html_cors-test-page.html | 34 + .../netmonitor/test/html_csp-frame-test-page.html | 9 + .../netmonitor/test/html_csp-resend-test-page.html | 25 + .../client/netmonitor/test/html_csp-test-page.html | 18 + .../client/netmonitor/test/html_curl-utils.html | 136 + .../netmonitor/test/html_custom-get-page.html | 48 + .../netmonitor/test/html_cyrillic-test-page.html | 42 + .../netmonitor/test/html_filter-test-page.html | 58 + .../netmonitor/test/html_fonts-test-page.html | 45 + .../netmonitor/test/html_frame-subdocument.html | 50 + .../netmonitor/test/html_frame-test-page.html | 51 + .../netmonitor/test/html_header-test-page.html | 43 + .../client/netmonitor/test/html_image-cache.html | 7 + .../test/html_image-tooltip-test-page.html | 29 + .../netmonitor/test/html_infinite-get-page.html | 50 + .../netmonitor/test/html_internal-stylesheet.html | 15 + devtools/client/netmonitor/test/html_json-b64.html | 41 + .../client/netmonitor/test/html_json-basic.html | 43 + .../test/html_json-custom-mime-test-page.html | 41 + .../client/netmonitor/test/html_json-empty.html | 42 + .../netmonitor/test/html_json-long-test-page.html | 41 + .../test/html_json-malformed-test-page.html | 41 + .../test/html_json-text-mime-test-page.html | 41 + .../netmonitor/test/html_json-xssi-protection.html | 42 + .../netmonitor/test/html_jsonp-test-page.html | 42 + .../netmonitor/test/html_maps-test-page.html | 24 + .../netmonitor/test/html_navigate-test-page.html | 18 + .../netmonitor/test/html_open-request-in-tab.html | 33 + .../netmonitor/test/html_params-test-page.html | 78 + .../netmonitor/test/html_pause-test-page.html | 36 + .../test/html_post-array-data-test-page.html | 34 + .../netmonitor/test/html_post-data-test-page.html | 82 + .../netmonitor/test/html_post-json-test-page.html | 48 + .../netmonitor/test/html_post-raw-test-page.html | 43 + .../test/html_post-raw-with-headers-test-page.html | 67 + .../client/netmonitor/test/html_send-beacon.html | 26 + .../netmonitor/test/html_simple-test-page.html | 18 + .../netmonitor/test/html_single-get-page.html | 40 + .../test/html_slow-requests-test-page.html | 15 + .../netmonitor/test/html_sorting-test-page.html | 18 + .../client/netmonitor/test/html_sse-test-page.html | 31 + .../test/html_statistics-edge-case-page.html | 23 + .../netmonitor/test/html_statistics-test-page.html | 42 + .../test/html_status-codes-test-page.html | 55 + .../netmonitor/test/html_tracking-protection.html | 21 + .../netmonitor/test/html_websocket-test-page.html | 10 + .../netmonitor/test/html_worker-test-page.html | 13 + .../test/html_ws-early-connection-page.html | 24 + .../netmonitor/test/html_ws-sse-test-page.html | 59 + .../client/netmonitor/test/html_ws-test-page.html | 56 + .../netmonitor/test/js_websocket-worker-test.js | 6 + devtools/client/netmonitor/test/js_worker-test.js | 30 + devtools/client/netmonitor/test/js_worker-test2.js | 3 + .../client/netmonitor/test/node/jest.config.js | 12 + devtools/client/netmonitor/test/node/package.json | 15 + .../netmonitor/test/node/reducers/sort.spec.js | 28 + devtools/client/netmonitor/test/node/yarn.lock | 3553 ++++++++++++++++++++ devtools/client/netmonitor/test/ostrich-black.ttf | Bin 0 -> 12872 bytes .../client/netmonitor/test/ostrich-regular.ttf | Bin 0 -> 12476 bytes .../service-workers/status-codes-service-worker.js | 16 + .../test/service-workers/status-codes.html | 62 + .../test/sjs_content-type-test-server.sjs | 421 +++ .../netmonitor/test/sjs_cors-test-server.sjs | 18 + .../netmonitor/test/sjs_hsts-test-server.sjs | 23 + .../test/sjs_https-redirect-test-server.sjs | 19 + .../netmonitor/test/sjs_json-test-server.sjs | 28 + .../netmonitor/test/sjs_long-polling-server.sjs | 35 + .../netmonitor/test/sjs_method-test-server.sjs | 35 + .../netmonitor/test/sjs_search-test-server.sjs | 10 + .../netmonitor/test/sjs_set-cookie-same-site.sjs | 11 + .../netmonitor/test/sjs_simple-test-server.sjs | 22 + .../sjs_simple-unsorted-cookies-test-server.sjs | 20 + .../netmonitor/test/sjs_slow-script-server.sjs | 18 + .../netmonitor/test/sjs_slow-test-server.sjs | 20 + .../netmonitor/test/sjs_sorting-test-server.sjs | 36 + .../client/netmonitor/test/sjs_sse-test-server.sjs | 7 + .../test/sjs_status-codes-test-server.sjs | 71 + .../netmonitor/test/sjs_timings-test-server.sjs | 45 + .../netmonitor/test/sjs_truncate-test-server.sjs | 21 + devtools/client/netmonitor/test/test-image.png | Bin 0 -> 580 bytes devtools/client/netmonitor/test/xhr_bundle.js | 91 + devtools/client/netmonitor/test/xhr_bundle.js.map | 1 + devtools/client/netmonitor/test/xhr_original.js | 13 + .../client/netmonitor/test/xpcshell/.eslintrc.js | 6 + .../netmonitor/test/xpcshell/test_doc-utils.js | 62 + .../test_request-utils-fetchNetworkUpdatePacket.js | 54 + .../test_request-utils-js-getFormattedProtocol.js | 235 ++ .../test/xpcshell/test_request-utils-parseJSON.js | 78 + .../client/netmonitor/test/xpcshell/xpcshell.ini | 10 + 538 files changed, 67027 insertions(+) create mode 100644 devtools/client/netmonitor/docs/architecture.md create mode 100644 devtools/client/netmonitor/index.html create mode 100644 devtools/client/netmonitor/initializer.js create mode 100644 devtools/client/netmonitor/moz.build create mode 100644 devtools/client/netmonitor/panel.js create mode 100644 devtools/client/netmonitor/src/actions/batching.js create mode 100644 devtools/client/netmonitor/src/actions/filters.js create mode 100644 devtools/client/netmonitor/src/actions/http-custom-request.js create mode 100644 devtools/client/netmonitor/src/actions/index.js create mode 100644 devtools/client/netmonitor/src/actions/messages.js create mode 100644 devtools/client/netmonitor/src/actions/moz.build create mode 100644 devtools/client/netmonitor/src/actions/request-blocking.js create mode 100644 devtools/client/netmonitor/src/actions/requests.js create mode 100644 devtools/client/netmonitor/src/actions/search.js create mode 100644 devtools/client/netmonitor/src/actions/selection.js create mode 100644 devtools/client/netmonitor/src/actions/sort.js create mode 100644 devtools/client/netmonitor/src/actions/timing-markers.js create mode 100644 devtools/client/netmonitor/src/actions/ui.js create mode 100644 devtools/client/netmonitor/src/api.js create mode 100644 devtools/client/netmonitor/src/app.js create mode 100644 devtools/client/netmonitor/src/assets/icons/arrow-up.svg create mode 100644 devtools/client/netmonitor/src/assets/icons/play.svg create mode 100644 devtools/client/netmonitor/src/assets/icons/shield.svg create mode 100644 devtools/client/netmonitor/src/assets/icons/turtle.svg create mode 100644 devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css create mode 100644 devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css create mode 100644 devtools/client/netmonitor/src/assets/styles/HeadersPanel.css create mode 100644 devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css create mode 100644 devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css create mode 100644 devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css create mode 100644 devtools/client/netmonitor/src/assets/styles/RequestList.css create mode 100644 devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css create mode 100644 devtools/client/netmonitor/src/assets/styles/StatusBar.css create mode 100644 devtools/client/netmonitor/src/assets/styles/StatusCode.css create mode 100644 devtools/client/netmonitor/src/assets/styles/Toolbar.css create mode 100644 devtools/client/netmonitor/src/assets/styles/UrlPreview.css create mode 100644 devtools/client/netmonitor/src/assets/styles/messages.css create mode 100644 devtools/client/netmonitor/src/assets/styles/netmonitor.css create mode 100644 devtools/client/netmonitor/src/assets/styles/search.css create mode 100644 devtools/client/netmonitor/src/assets/styles/variables.css create mode 100644 devtools/client/netmonitor/src/components/App.js create mode 100644 devtools/client/netmonitor/src/components/CustomRequestPanel.js create mode 100644 devtools/client/netmonitor/src/components/DropHarHandler.js create mode 100644 devtools/client/netmonitor/src/components/MonitorPanel.js create mode 100644 devtools/client/netmonitor/src/components/NetworkActionBar.js create mode 100644 devtools/client/netmonitor/src/components/SecurityState.js create mode 100644 devtools/client/netmonitor/src/components/SourceEditor.js create mode 100644 devtools/client/netmonitor/src/components/StatisticsPanel.js create mode 100644 devtools/client/netmonitor/src/components/StatusBar.js create mode 100644 devtools/client/netmonitor/src/components/StatusCode.js create mode 100644 devtools/client/netmonitor/src/components/TabboxPanel.js create mode 100644 devtools/client/netmonitor/src/components/Toolbar.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnData.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnEventName.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnFinBit.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnLastEventId.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnMaskBit.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnOpCode.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnRetry.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnSize.js create mode 100644 devtools/client/netmonitor/src/components/messages/ColumnTime.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageFilterMenu.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageListContent.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageListContextMenu.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageListHeader.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageListHeaderContextMenu.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessageListItem.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessagePayload.js create mode 100644 devtools/client/netmonitor/src/components/messages/MessagesView.js create mode 100644 devtools/client/netmonitor/src/components/messages/RawData.js create mode 100644 devtools/client/netmonitor/src/components/messages/StatusBar.js create mode 100644 devtools/client/netmonitor/src/components/messages/Toolbar.js create mode 100644 devtools/client/netmonitor/src/components/messages/cbor.js create mode 100644 devtools/client/netmonitor/src/components/messages/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/msgpack.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/HandshakeProtocol.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/IHubProtocol.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/JSONHubProtocol.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/TextMessageFormat.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/Utils.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/index.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/signalr/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/socket-io/binary.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/socket-io/component-emitter.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/socket-io/index.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/socket-io/is-buffer.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/socket-io/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/sockjs/index.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/sockjs/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/stomp/byte.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/stomp/frame.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/stomp/index.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/stomp/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/stomp/parser.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/wamp/arrayParser.js create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/wamp/moz.build create mode 100644 devtools/client/netmonitor/src/components/messages/parsers/wamp/serializers.js create mode 100644 devtools/client/netmonitor/src/components/moz.build create mode 100644 devtools/client/netmonitor/src/components/new-request/HTTPCustomRequestPanel.js create mode 100644 devtools/client/netmonitor/src/components/new-request/InputMap.js create mode 100644 devtools/client/netmonitor/src/components/new-request/moz.build create mode 100644 devtools/client/netmonitor/src/components/previews/FontPreview.js create mode 100644 devtools/client/netmonitor/src/components/previews/HtmlPreview.js create mode 100644 devtools/client/netmonitor/src/components/previews/ImagePreview.js create mode 100644 devtools/client/netmonitor/src/components/previews/SourcePreview.js create mode 100644 devtools/client/netmonitor/src/components/previews/UrlPreview.js create mode 100644 devtools/client/netmonitor/src/components/previews/moz.build create mode 100644 devtools/client/netmonitor/src/components/request-blocking/RequestBlockingPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-blocking/moz.build create mode 100644 devtools/client/netmonitor/src/components/request-details/CachePanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/CookiesPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/HeadersPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/NetworkDetailsBar.js create mode 100644 devtools/client/netmonitor/src/components/request-details/PropertiesView.js create mode 100644 devtools/client/netmonitor/src/components/request-details/RequestPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/ResponsePanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/SecurityPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/StackTracePanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/TimingsPanel.js create mode 100644 devtools/client/netmonitor/src/components/request-details/moz.build create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestList.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnContentSize.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnCookies.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnDomain.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnFile.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnInitiator.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnMethod.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnPriority.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnProtocol.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnRemoteIP.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnResponseHeader.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnScheme.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnSetCookies.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnStatus.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnTime.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnTransferredSize.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnType.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnUrl.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListColumnWaterfall.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListContent.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListEmptyNotice.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListHeader.js create mode 100644 devtools/client/netmonitor/src/components/request-list/RequestListItem.js create mode 100644 devtools/client/netmonitor/src/components/request-list/moz.build create mode 100644 devtools/client/netmonitor/src/components/search/SearchPanel.js create mode 100644 devtools/client/netmonitor/src/components/search/StatusBar.js create mode 100644 devtools/client/netmonitor/src/components/search/Toolbar.js create mode 100644 devtools/client/netmonitor/src/components/search/moz.build create mode 100644 devtools/client/netmonitor/src/components/search/search-provider.js create mode 100644 devtools/client/netmonitor/src/connector/firefox-data-provider.js create mode 100644 devtools/client/netmonitor/src/connector/har-metadata-collector.js create mode 100644 devtools/client/netmonitor/src/connector/index.js create mode 100644 devtools/client/netmonitor/src/connector/moz.build create mode 100644 devtools/client/netmonitor/src/constants.js create mode 100644 devtools/client/netmonitor/src/create-store.js create mode 100644 devtools/client/netmonitor/src/har/README.md create mode 100644 devtools/client/netmonitor/src/har/har-automation.js create mode 100644 devtools/client/netmonitor/src/har/har-builder-utils.js create mode 100644 devtools/client/netmonitor/src/har/har-builder.js create mode 100644 devtools/client/netmonitor/src/har/har-collector.js create mode 100644 devtools/client/netmonitor/src/har/har-exporter.js create mode 100644 devtools/client/netmonitor/src/har/har-importer.js create mode 100644 devtools/client/netmonitor/src/har/har-menu-utils.js create mode 100644 devtools/client/netmonitor/src/har/har-utils.js create mode 100644 devtools/client/netmonitor/src/har/moz.build create mode 100644 devtools/client/netmonitor/src/har/test/browser-harautomation.ini create mode 100644 devtools/client/netmonitor/src/har/test/browser.ini create mode 100644 devtools/client/netmonitor/src/har/test/browser_harautomation_simple.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_copy_all_as_har.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_import.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_import_no-mime.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_multipage.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_post_data.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_post_data_on_get.js create mode 100644 devtools/client/netmonitor/src/har/test/browser_net_har_throttle_upload.js create mode 100644 devtools/client/netmonitor/src/har/test/head.js create mode 100644 devtools/client/netmonitor/src/har/test/html_har_import-test-page.html create mode 100644 devtools/client/netmonitor/src/har/test/html_har_multipage_iframe.html create mode 100644 devtools/client/netmonitor/src/har/test/html_har_multipage_page.html create mode 100644 devtools/client/netmonitor/src/har/test/html_har_post-data-test-page.html create mode 100644 devtools/client/netmonitor/src/har/test/sjs_cache-test-server.sjs create mode 100644 devtools/client/netmonitor/src/har/test/sjs_cookies-test-server.sjs create mode 100644 devtools/client/netmonitor/src/middleware/batching.js create mode 100644 devtools/client/netmonitor/src/middleware/event-telemetry.js create mode 100644 devtools/client/netmonitor/src/middleware/moz.build create mode 100644 devtools/client/netmonitor/src/middleware/prefs.js create mode 100644 devtools/client/netmonitor/src/middleware/request-blocking.js create mode 100644 devtools/client/netmonitor/src/middleware/throttling.js create mode 100644 devtools/client/netmonitor/src/moz.build create mode 100644 devtools/client/netmonitor/src/reducers/batching.js create mode 100644 devtools/client/netmonitor/src/reducers/filters.js create mode 100644 devtools/client/netmonitor/src/reducers/index.js create mode 100644 devtools/client/netmonitor/src/reducers/messages.js create mode 100644 devtools/client/netmonitor/src/reducers/moz.build create mode 100644 devtools/client/netmonitor/src/reducers/request-blocking.js create mode 100644 devtools/client/netmonitor/src/reducers/requests.js create mode 100644 devtools/client/netmonitor/src/reducers/search.js create mode 100644 devtools/client/netmonitor/src/reducers/sort.js create mode 100644 devtools/client/netmonitor/src/reducers/timing-markers.js create mode 100644 devtools/client/netmonitor/src/reducers/ui.js create mode 100644 devtools/client/netmonitor/src/selectors/index.js create mode 100644 devtools/client/netmonitor/src/selectors/messages.js create mode 100644 devtools/client/netmonitor/src/selectors/moz.build create mode 100644 devtools/client/netmonitor/src/selectors/requests.js create mode 100644 devtools/client/netmonitor/src/selectors/search.js create mode 100644 devtools/client/netmonitor/src/selectors/timing-markers.js create mode 100644 devtools/client/netmonitor/src/selectors/ui.js create mode 100644 devtools/client/netmonitor/src/utils/context-menu-utils.js create mode 100644 devtools/client/netmonitor/src/utils/doc-utils.js create mode 100644 devtools/client/netmonitor/src/utils/filter-autocomplete-provider.js create mode 100644 devtools/client/netmonitor/src/utils/filter-predicates.js create mode 100644 devtools/client/netmonitor/src/utils/filter-text-utils.js create mode 100644 devtools/client/netmonitor/src/utils/firefox/moz.build create mode 100644 devtools/client/netmonitor/src/utils/firefox/open-request-in-tab.js create mode 100644 devtools/client/netmonitor/src/utils/format-utils.js create mode 100644 devtools/client/netmonitor/src/utils/headers-provider.js create mode 100644 devtools/client/netmonitor/src/utils/l10n.js create mode 100644 devtools/client/netmonitor/src/utils/moz.build create mode 100644 devtools/client/netmonitor/src/utils/open-request-in-tab.js create mode 100644 devtools/client/netmonitor/src/utils/powershell.js create mode 100644 devtools/client/netmonitor/src/utils/prefs.js create mode 100644 devtools/client/netmonitor/src/utils/request-blocking.js create mode 100644 devtools/client/netmonitor/src/utils/request-utils.js create mode 100644 devtools/client/netmonitor/src/utils/sort-predicates.js create mode 100644 devtools/client/netmonitor/src/utils/sort-utils.js create mode 100644 devtools/client/netmonitor/src/utils/tooltips.js create mode 100644 devtools/client/netmonitor/src/widgets/HeadersPanelContextMenu.js create mode 100644 devtools/client/netmonitor/src/widgets/PropertiesViewContextMenu.js create mode 100644 devtools/client/netmonitor/src/widgets/RequestBlockingContextMenu.js create mode 100644 devtools/client/netmonitor/src/widgets/RequestListContextMenu.js create mode 100644 devtools/client/netmonitor/src/widgets/RequestListHeaderContextMenu.js create mode 100644 devtools/client/netmonitor/src/widgets/WaterfallBackground.js create mode 100644 devtools/client/netmonitor/src/widgets/moz.build create mode 100644 devtools/client/netmonitor/src/workers/moz.build create mode 100644 devtools/client/netmonitor/src/workers/search/index.js create mode 100644 devtools/client/netmonitor/src/workers/search/moz.build create mode 100644 devtools/client/netmonitor/src/workers/search/search.js create mode 100644 devtools/client/netmonitor/src/workers/search/worker.js create mode 100644 devtools/client/netmonitor/test/.eslintrc.js create mode 100644 devtools/client/netmonitor/test/OstrichLicense.txt create mode 100644 devtools/client/netmonitor/test/browser.ini create mode 100644 devtools/client/netmonitor/test/browser_http3.ini create mode 100644 devtools/client/netmonitor/test/browser_net-ws-filter-freetext.js create mode 100644 devtools/client/netmonitor/test/browser_net_accessibility-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_accessibility-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_api-calls.js create mode 100644 devtools/client/netmonitor/test/browser_net_autoscroll.js create mode 100644 devtools/client/netmonitor/test/browser_net_background_update.js create mode 100644 devtools/client/netmonitor/test/browser_net_basic-search.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-context.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-csp.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-draganddrop.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-extensions.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-pattern.js create mode 100644 devtools/client/netmonitor/test/browser_net_block-serviceworker.js create mode 100644 devtools/client/netmonitor/test/browser_net_block.js create mode 100644 devtools/client/netmonitor/test/browser_net_brotli.js create mode 100644 devtools/client/netmonitor/test/browser_net_cache_details.js create mode 100644 devtools/client/netmonitor/test/browser_net_cached-status.js create mode 100644 devtools/client/netmonitor/test/browser_net_cause_redirect.js create mode 100644 devtools/client/netmonitor/test/browser_net_cause_source_map.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-03.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-04.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-05.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-06.js create mode 100644 devtools/client/netmonitor/test/browser_net_charts-07.js create mode 100644 devtools/client/netmonitor/test/browser_net_clear.js create mode 100644 devtools/client/netmonitor/test/browser_net_column-resize-fit.js create mode 100644 devtools/client/netmonitor/test/browser_net_column_headers_tooltips.js create mode 100644 devtools/client/netmonitor/test/browser_net_column_slow-request-indicator.js create mode 100644 devtools/client/netmonitor/test/browser_net_columns_last_column.js create mode 100644 devtools/client/netmonitor/test/browser_net_columns_pref.js create mode 100644 devtools/client/netmonitor/test/browser_net_columns_reset.js create mode 100644 devtools/client/netmonitor/test/browser_net_columns_showhide.js create mode 100644 devtools/client/netmonitor/test/browser_net_columns_time.js create mode 100644 devtools/client/netmonitor/test/browser_net_complex-params.js create mode 100644 devtools/client/netmonitor/test/browser_net_content-type.js create mode 100644 devtools/client/netmonitor/test/browser_net_cookies_sorted.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_as_curl.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_as_fetch.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_as_powershell.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_headers.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_image_as_data_uri.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_params.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_response.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_svg_image_as_data_uri.js create mode 100644 devtools/client/netmonitor/test/browser_net_copy_url.js create mode 100644 devtools/client/netmonitor/test/browser_net_cors_requests.js create mode 100644 devtools/client/netmonitor/test/browser_net_curl-utils.js create mode 100644 devtools/client/netmonitor/test/browser_net_cyrillic-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_cyrillic-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_decode-params.js create mode 100644 devtools/client/netmonitor/test/browser_net_decode-url.js create mode 100644 devtools/client/netmonitor/test/browser_net_details_copy.js create mode 100644 devtools/client/netmonitor/test/browser_net_domain-not-found.js create mode 100644 devtools/client/netmonitor/test/browser_net_edit_resend_cancel.js create mode 100644 devtools/client/netmonitor/test/browser_net_edit_resend_caret.js create mode 100644 devtools/client/netmonitor/test/browser_net_edit_resend_with_filtering.js create mode 100644 devtools/client/netmonitor/test/browser_net_edit_resend_xhr.js create mode 100644 devtools/client/netmonitor/test/browser_net_error-boundary-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-03.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-04.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-autocomplete.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-flags.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-sts-search.js create mode 100644 devtools/client/netmonitor/test/browser_net_filter-value-preserved.js create mode 100644 devtools/client/netmonitor/test/browser_net_fission_switch_target.js create mode 100644 devtools/client/netmonitor/test/browser_net_fonts.js create mode 100644 devtools/client/netmonitor/test/browser_net_footer-summary.js create mode 100644 devtools/client/netmonitor/test/browser_net_frame.js create mode 100644 devtools/client/netmonitor/test/browser_net_header-docs.js create mode 100644 devtools/client/netmonitor/test/browser_net_header-ref-policy.js create mode 100644 devtools/client/netmonitor/test/browser_net_header-request-priority.js create mode 100644 devtools/client/netmonitor/test/browser_net_headers-alignment.js create mode 100644 devtools/client/netmonitor/test/browser_net_headers-link_clickable.js create mode 100644 devtools/client/netmonitor/test/browser_net_headers-resize.js create mode 100644 devtools/client/netmonitor/test/browser_net_headers_filter.js create mode 100644 devtools/client/netmonitor/test/browser_net_headers_sorted.js create mode 100644 devtools/client/netmonitor/test/browser_net_html-preview.js create mode 100644 devtools/client/netmonitor/test/browser_net_http3_request_details.js create mode 100644 devtools/client/netmonitor/test/browser_net_image-tooltip.js create mode 100644 devtools/client/netmonitor/test/browser_net_image_cache.js create mode 100644 devtools/client/netmonitor/test/browser_net_initiator.js create mode 100644 devtools/client/netmonitor/test/browser_net_internal-stylesheet.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-b64.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-empty.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-long.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-malformed.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-nogrip.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-null.js create mode 100644 devtools/client/netmonitor/test/browser_net_json-xssi-protection.js create mode 100644 devtools/client/netmonitor/test/browser_net_json_custom_mime.js create mode 100644 devtools/client/netmonitor/test/browser_net_json_text_mime.js create mode 100644 devtools/client/netmonitor/test/browser_net_jsonp.js create mode 100644 devtools/client/netmonitor/test/browser_net_large-response.js create mode 100644 devtools/client/netmonitor/test/browser_net_leak_on_tab_close.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_clear_button.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_content-length.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_context_menu.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_persisted_content.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_send_request.js create mode 100644 devtools/client/netmonitor/test/browser_net_new_request_panel_sync_url_params.js create mode 100644 devtools/client/netmonitor/test/browser_net_open_in_debugger.js create mode 100644 devtools/client/netmonitor/test/browser_net_open_in_style_editor.js create mode 100644 devtools/client/netmonitor/test/browser_net_open_request_in_tab.js create mode 100644 devtools/client/netmonitor/test/browser_net_pane-collapse.js create mode 100644 devtools/client/netmonitor/test/browser_net_pane-network-details.js create mode 100644 devtools/client/netmonitor/test/browser_net_pane-toggle.js create mode 100644 devtools/client/netmonitor/test/browser_net_params_sorted.js create mode 100644 devtools/client/netmonitor/test/browser_net_pause.js create mode 100644 devtools/client/netmonitor/test/browser_net_persistent_logs.js create mode 100644 devtools/client/netmonitor/test/browser_net_post-data-json-payloads.js create mode 100644 devtools/client/netmonitor/test/browser_net_post-data-raw-payloads-with-upload-stream-headers.js create mode 100644 devtools/client/netmonitor/test/browser_net_post-data-raw-payloads.js create mode 100644 devtools/client/netmonitor/test/browser_net_post-data.js create mode 100644 devtools/client/netmonitor/test/browser_net_prefs-and-l10n.js create mode 100644 devtools/client/netmonitor/test/browser_net_prefs-reload.js create mode 100644 devtools/client/netmonitor/test/browser_net_raw_headers.js create mode 100644 devtools/client/netmonitor/test/browser_net_reload-button.js create mode 100644 devtools/client/netmonitor/test/browser_net_reload-markers.js create mode 100644 devtools/client/netmonitor/test/browser_net_req-resp-bodies.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend_cors.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend_csp.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend_headers.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend_hidden_headers.js create mode 100644 devtools/client/netmonitor/test/browser_net_resend_xhr.js create mode 100644 devtools/client/netmonitor/test/browser_net_response_CORS_blocked.js create mode 100644 devtools/client/netmonitor/test/browser_net_response_node-expanded.js create mode 100644 devtools/client/netmonitor/test/browser_net_search-results.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-details.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-error.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-icon-click.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-redirect.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-state.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-tab-deselect.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-tab-visibility.js create mode 100644 devtools/client/netmonitor/test/browser_net_security-warnings.js create mode 100644 devtools/client/netmonitor/test/browser_net_send-beacon-other-tab.js create mode 100644 devtools/client/netmonitor/test/browser_net_send-beacon.js create mode 100644 devtools/client/netmonitor/test/browser_net_server_timings.js create mode 100644 devtools/client/netmonitor/test/browser_net_service-worker-status.js create mode 100644 devtools/client/netmonitor/test/browser_net_set-cookie-same-site.js create mode 100644 devtools/client/netmonitor/test/browser_net_simple-request-data.js create mode 100644 devtools/client/netmonitor/test/browser_net_simple-request-details.js create mode 100644 devtools/client/netmonitor/test/browser_net_simple-request.js create mode 100644 devtools/client/netmonitor/test/browser_net_sort-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_sort-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_sort-reset.js create mode 100644 devtools/client/netmonitor/test/browser_net_sse-basic.js create mode 100644 devtools/client/netmonitor/test/browser_net_stacktraces-visibility.js create mode 100644 devtools/client/netmonitor/test/browser_net_statistics-01.js create mode 100644 devtools/client/netmonitor/test/browser_net_statistics-02.js create mode 100644 devtools/client/netmonitor/test/browser_net_statistics-edge-case.js create mode 100644 devtools/client/netmonitor/test/browser_net_status-bar-transferred-size.js create mode 100644 devtools/client/netmonitor/test/browser_net_status-bar.js create mode 100644 devtools/client/netmonitor/test/browser_net_status-codes.js create mode 100644 devtools/client/netmonitor/test/browser_net_streaming-response.js create mode 100644 devtools/client/netmonitor/test/browser_net_tabbar_focus.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_edit_resend.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_filters_changed.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_persist_toggle_changed.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_select_ws_frame.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_sidepanel_changed.js create mode 100644 devtools/client/netmonitor/test/browser_net_telemetry_throttle_changed.js create mode 100644 devtools/client/netmonitor/test/browser_net_throttle.js create mode 100644 devtools/client/netmonitor/test/browser_net_throttling_profiles.js create mode 100644 devtools/client/netmonitor/test/browser_net_timeline_ticks.js create mode 100644 devtools/client/netmonitor/test/browser_net_timing-division.js create mode 100644 devtools/client/netmonitor/test/browser_net_tracking-resources.js create mode 100644 devtools/client/netmonitor/test/browser_net_truncate-post-data.js create mode 100644 devtools/client/netmonitor/test/browser_net_truncate.js create mode 100644 devtools/client/netmonitor/test/browser_net_url-preview.js create mode 100644 devtools/client/netmonitor/test/browser_net_use_as_fetch.js create mode 100644 devtools/client/netmonitor/test/browser_net_view-source-debugger.js create mode 100644 devtools/client/netmonitor/test/browser_net_waterfall-click.js create mode 100644 devtools/client/netmonitor/test/browser_net_websocket_stacks.js create mode 100644 devtools/client/netmonitor/test/browser_net_worker_stacks.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-basic.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-clear.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-connection-closed.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-early-connection.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-filter-dropdown.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-filter-regex.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-json-action-cable-payload.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-json-payload.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-json-stomp-payload.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-keep-future-frames.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-limit-frames.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-limit-payload.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-messages-navigation.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-sockjs-stomp-payload.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-sse-persist-columns.js create mode 100644 devtools/client/netmonitor/test/browser_net_ws-stomp-payload.js create mode 100644 devtools/client/netmonitor/test/dropmarker.svg create mode 100644 devtools/client/netmonitor/test/file_ws_backend_wsh.py create mode 100644 devtools/client/netmonitor/test/head.js create mode 100644 devtools/client/netmonitor/test/html_api-calls-test-page.html create mode 100644 devtools/client/netmonitor/test/html_brotli-test-page.html create mode 100644 devtools/client/netmonitor/test/html_cache-test-page.html create mode 100644 devtools/client/netmonitor/test/html_cause-test-page.html create mode 100644 devtools/client/netmonitor/test/html_content-type-without-cache-test-page.html create mode 100644 devtools/client/netmonitor/test/html_copy-as-curl.html create mode 100644 devtools/client/netmonitor/test/html_cors-test-page.html create mode 100644 devtools/client/netmonitor/test/html_csp-frame-test-page.html create mode 100644 devtools/client/netmonitor/test/html_csp-resend-test-page.html create mode 100644 devtools/client/netmonitor/test/html_csp-test-page.html create mode 100644 devtools/client/netmonitor/test/html_curl-utils.html create mode 100644 devtools/client/netmonitor/test/html_custom-get-page.html create mode 100644 devtools/client/netmonitor/test/html_cyrillic-test-page.html create mode 100644 devtools/client/netmonitor/test/html_filter-test-page.html create mode 100644 devtools/client/netmonitor/test/html_fonts-test-page.html create mode 100644 devtools/client/netmonitor/test/html_frame-subdocument.html create mode 100644 devtools/client/netmonitor/test/html_frame-test-page.html create mode 100644 devtools/client/netmonitor/test/html_header-test-page.html create mode 100644 devtools/client/netmonitor/test/html_image-cache.html create mode 100644 devtools/client/netmonitor/test/html_image-tooltip-test-page.html create mode 100644 devtools/client/netmonitor/test/html_infinite-get-page.html create mode 100644 devtools/client/netmonitor/test/html_internal-stylesheet.html create mode 100644 devtools/client/netmonitor/test/html_json-b64.html create mode 100644 devtools/client/netmonitor/test/html_json-basic.html create mode 100644 devtools/client/netmonitor/test/html_json-custom-mime-test-page.html create mode 100644 devtools/client/netmonitor/test/html_json-empty.html create mode 100644 devtools/client/netmonitor/test/html_json-long-test-page.html create mode 100644 devtools/client/netmonitor/test/html_json-malformed-test-page.html create mode 100644 devtools/client/netmonitor/test/html_json-text-mime-test-page.html create mode 100644 devtools/client/netmonitor/test/html_json-xssi-protection.html create mode 100644 devtools/client/netmonitor/test/html_jsonp-test-page.html create mode 100644 devtools/client/netmonitor/test/html_maps-test-page.html create mode 100644 devtools/client/netmonitor/test/html_navigate-test-page.html create mode 100644 devtools/client/netmonitor/test/html_open-request-in-tab.html create mode 100644 devtools/client/netmonitor/test/html_params-test-page.html create mode 100644 devtools/client/netmonitor/test/html_pause-test-page.html create mode 100644 devtools/client/netmonitor/test/html_post-array-data-test-page.html create mode 100644 devtools/client/netmonitor/test/html_post-data-test-page.html create mode 100644 devtools/client/netmonitor/test/html_post-json-test-page.html create mode 100644 devtools/client/netmonitor/test/html_post-raw-test-page.html create mode 100644 devtools/client/netmonitor/test/html_post-raw-with-headers-test-page.html create mode 100644 devtools/client/netmonitor/test/html_send-beacon.html create mode 100644 devtools/client/netmonitor/test/html_simple-test-page.html create mode 100644 devtools/client/netmonitor/test/html_single-get-page.html create mode 100644 devtools/client/netmonitor/test/html_slow-requests-test-page.html create mode 100644 devtools/client/netmonitor/test/html_sorting-test-page.html create mode 100644 devtools/client/netmonitor/test/html_sse-test-page.html create mode 100644 devtools/client/netmonitor/test/html_statistics-edge-case-page.html create mode 100644 devtools/client/netmonitor/test/html_statistics-test-page.html create mode 100644 devtools/client/netmonitor/test/html_status-codes-test-page.html create mode 100644 devtools/client/netmonitor/test/html_tracking-protection.html create mode 100644 devtools/client/netmonitor/test/html_websocket-test-page.html create mode 100644 devtools/client/netmonitor/test/html_worker-test-page.html create mode 100644 devtools/client/netmonitor/test/html_ws-early-connection-page.html create mode 100644 devtools/client/netmonitor/test/html_ws-sse-test-page.html create mode 100644 devtools/client/netmonitor/test/html_ws-test-page.html create mode 100644 devtools/client/netmonitor/test/js_websocket-worker-test.js create mode 100644 devtools/client/netmonitor/test/js_worker-test.js create mode 100644 devtools/client/netmonitor/test/js_worker-test2.js create mode 100644 devtools/client/netmonitor/test/node/jest.config.js create mode 100644 devtools/client/netmonitor/test/node/package.json create mode 100644 devtools/client/netmonitor/test/node/reducers/sort.spec.js create mode 100644 devtools/client/netmonitor/test/node/yarn.lock create mode 100644 devtools/client/netmonitor/test/ostrich-black.ttf create mode 100644 devtools/client/netmonitor/test/ostrich-regular.ttf create mode 100644 devtools/client/netmonitor/test/service-workers/status-codes-service-worker.js create mode 100644 devtools/client/netmonitor/test/service-workers/status-codes.html create mode 100644 devtools/client/netmonitor/test/sjs_content-type-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_cors-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_hsts-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_https-redirect-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_json-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_long-polling-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_method-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_search-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_set-cookie-same-site.sjs create mode 100644 devtools/client/netmonitor/test/sjs_simple-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_simple-unsorted-cookies-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_slow-script-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_slow-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_sorting-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_sse-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_status-codes-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_timings-test-server.sjs create mode 100644 devtools/client/netmonitor/test/sjs_truncate-test-server.sjs create mode 100644 devtools/client/netmonitor/test/test-image.png create mode 100644 devtools/client/netmonitor/test/xhr_bundle.js create mode 100644 devtools/client/netmonitor/test/xhr_bundle.js.map create mode 100644 devtools/client/netmonitor/test/xhr_original.js create mode 100644 devtools/client/netmonitor/test/xpcshell/.eslintrc.js create mode 100644 devtools/client/netmonitor/test/xpcshell/test_doc-utils.js create mode 100644 devtools/client/netmonitor/test/xpcshell/test_request-utils-fetchNetworkUpdatePacket.js create mode 100644 devtools/client/netmonitor/test/xpcshell/test_request-utils-js-getFormattedProtocol.js create mode 100644 devtools/client/netmonitor/test/xpcshell/test_request-utils-parseJSON.js create mode 100644 devtools/client/netmonitor/test/xpcshell/xpcshell.ini (limited to 'devtools/client/netmonitor') diff --git a/devtools/client/netmonitor/docs/architecture.md b/devtools/client/netmonitor/docs/architecture.md new file mode 100644 index 0000000000..e625168982 --- /dev/null +++ b/devtools/client/netmonitor/docs/architecture.md @@ -0,0 +1,30 @@ +# Network Monitor + +The Network Monitor (netmonitor) shows you all the network requests Firefox makes (for example, when a page is loaded or when an XMLHttpRequest is performed) , how long each request takes, and details of each request. You can edit the method, query, header and resend the request as well. Read [more](https://firefox-source-docs.mozilla.org/devtools-user/network_monitor/) to learn all the features and how to use the tool. + +## UI + +The Network Monitor UI is built using [React](http://searchfox.org/mozilla-central/source/devtools/docs/frontend/react.md) components (in `src/components/`). + +* **MonitorPanel** in `MonitorPanel.js` is the root element. +* Three major container components are + - **Toolbar** Panel related functions. + - **RequestList** Show each request information. + - **NetworkDetailsBar** Show detailed information per request. + - **StatusBar** Show statistics while loading. +* `src/assets` Styles that affect the Network Monitor panel. + +We prefer stateless component (define by function) instead of stateful component (define by class) unless the component has to maintain its internal state. + +## State + +![](https://hacks.mozilla.org/files/2017/06/image8.png) + +Besides the UI, the Network Monitor manages the app state via [Redux](http://searchfox.org/mozilla-central/source/devtools/docs/frontend/redux.md). The following locations define the app state: + +* `src/constants.js` constants used across the tool including action and event names. +* `src/actions/` for all actions that change the state. +* `src/reducers/` for all reducers that change the state. +* `src/selectors/` functions that return a formatted version of parts of the app state. + +We use [reselect](https://github.com/reactjs/reselect) library to perform state calculations efficiently. diff --git a/devtools/client/netmonitor/index.html b/devtools/client/netmonitor/index.html new file mode 100644 index 0000000000..2ccd9973f7 --- /dev/null +++ b/devtools/client/netmonitor/index.html @@ -0,0 +1,17 @@ + + + + + + + + +
+ + + diff --git a/devtools/client/netmonitor/initializer.js b/devtools/client/netmonitor/initializer.js new file mode 100644 index 0000000000..c6a8a246f5 --- /dev/null +++ b/devtools/client/netmonitor/initializer.js @@ -0,0 +1,109 @@ +/* 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/. */ +/* exported initialize */ + +"use strict"; + +/** + * This script is the entry point of Network monitor panel. + * See README.md for more information. + */ +const { BrowserLoader } = ChromeUtils.import( + "resource://devtools/shared/loader/browser-loader.js" +); + +const require = (window.windowRequire = BrowserLoader({ + baseURI: "resource://devtools/client/netmonitor/", + window, +}).require); + +const { + NetMonitorAPI, +} = require("resource://devtools/client/netmonitor/src/api.js"); +const { + NetMonitorApp, +} = require("resource://devtools/client/netmonitor/src/app.js"); +const EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +// Inject EventEmitter into global window. +EventEmitter.decorate(window); + +/** + * This is the initialization point for the Network monitor. + * + * @param {Object} api Allows reusing existing API object. + */ +function initialize(api) { + const app = new NetMonitorApp(api); + + // Inject to global window for testing + window.Netmonitor = app; + window.api = api; + window.store = app.api.store; + window.connector = app.api.connector; + window.actions = app.api.actions; + + return app; +} + +/** + * The following code is used to open Network monitor in a tab. + * Like the Launchpad, but without Launchpad. + * + * For example: + * chrome://devtools/content/netmonitor/index.html?type=process + * loads the netmonitor for the parent process, exactly like the + * one in the browser toolbox + * + * It's also possible to connect to a tab. + * 1) go in about:debugging + * 2) In menu Tabs, click on a Debug button for particular tab + * + * This will open an about:devtools-toolbox url, from which you can + * take type and id query parameters and reuse them for the chrome url + * of the netmonitor + * + * chrome://devtools/content/netmonitor/index.html?type=tab&id=1234 URLs + * where 1234 is the tab id, you can retrieve from about:debugging#tabs links. + * Simply copy the id from about:devtools-toolbox?type=tab&id=1234 URLs. + */ + +// URL constructor doesn't support chrome: scheme +const href = window.location.href.replace(/chrome:/, "http://"); +const url = new window.URL(href); + +// If query parameters are given in a chrome tab, the inspector +// is running in standalone. +if (window.location.protocol === "chrome:" && url.search.length > 1) { + const { + commandsFromURL, + } = require("resource://devtools/client/framework/commands-from-url.js"); + + (async function () { + try { + const commands = await commandsFromURL(url); + const target = await commands.descriptorFront.getTarget(); + // Create a fake toolbox object + const toolbox = { + target, + viewSourceInDebugger() { + throw new Error( + "toolbox.viewSourceInDebugger is not implement from a tab" + ); + }, + commands, + }; + + const api = new NetMonitorAPI(); + await api.connect(toolbox); + const app = window.initialize(api); + app.bootstrap({ + toolbox, + document: window.document, + }); + } catch (err) { + window.alert("Unable to start the network monitor:" + err); + } + })(); +} diff --git a/devtools/client/netmonitor/moz.build b/devtools/client/netmonitor/moz.build new file mode 100644 index 0000000000..949c84c0ce --- /dev/null +++ b/devtools/client/netmonitor/moz.build @@ -0,0 +1,19 @@ +# 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 += ["src"] + +DevToolsModules("initializer.js", "panel.js") + +XPCSHELL_TESTS_MANIFESTS += ["test/xpcshell/xpcshell.ini"] + +BROWSER_CHROME_MANIFESTS += [ + "test/browser.ini", + "test/browser_http3.ini", +] + +with Files("**"): + BUG_COMPONENT = ("DevTools", "Netmonitor") + +SPHINX_TREES["/devtools/netmonitor"] = "docs" diff --git a/devtools/client/netmonitor/panel.js b/devtools/client/netmonitor/panel.js new file mode 100644 index 0000000000..827f84eee9 --- /dev/null +++ b/devtools/client/netmonitor/panel.js @@ -0,0 +1,37 @@ +/* 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"; + +function NetMonitorPanel(iframeWindow, toolbox, commands) { + this.panelWin = iframeWindow; + this.toolbox = toolbox; + this.commands = commands; +} + +NetMonitorPanel.prototype = { + async open() { + // Reuse an existing Network monitor API object if available. + // It could have been created for WE API before Net panel opens. + const api = await this.toolbox.getNetMonitorAPI(); + const app = this.panelWin.initialize(api); + + // Connect the application object to the UI. + await app.bootstrap({ + toolbox: this.toolbox, + document: this.panelWin.document, + win: this.panelWin, + }); + + // Ready to go! + return this; + }, + + destroy() { + this.panelWin.Netmonitor.destroy(); + this.emit("destroyed"); + }, +}; + +exports.NetMonitorPanel = NetMonitorPanel; diff --git a/devtools/client/netmonitor/src/actions/batching.js b/devtools/client/netmonitor/src/actions/batching.js new file mode 100644 index 0000000000..f3b84f950d --- /dev/null +++ b/devtools/client/netmonitor/src/actions/batching.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 { + BATCH_ACTIONS, + BATCH_ENABLE, + BATCH_RESET, + BATCH_FLUSH, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +/** + * Process multiple actions at once as part of one dispatch, and produce only one + * state update at the end. This action is not processed by any reducer, but by a + * special store enhancer. + */ +function batchActions(actions) { + return { + type: BATCH_ACTIONS, + actions, + }; +} + +function batchEnable(enabled) { + return { + type: BATCH_ENABLE, + enabled, + }; +} + +function batchReset() { + return { + type: BATCH_RESET, + }; +} + +function batchFlush() { + return { + type: BATCH_FLUSH, + }; +} + +module.exports = { + batchActions, + batchEnable, + batchReset, + batchFlush, +}; diff --git a/devtools/client/netmonitor/src/actions/filters.js b/devtools/client/netmonitor/src/actions/filters.js new file mode 100644 index 0000000000..5aa5a99c10 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/filters.js @@ -0,0 +1,58 @@ +/* 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 { + ENABLE_REQUEST_FILTER_TYPE_ONLY, + TOGGLE_REQUEST_FILTER_TYPE, + SET_REQUEST_FILTER_TEXT, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +/** + * Toggle an existing filter type state. + * If type 'all' is specified, all the other filter types are set to false. + * Available filter types are defined in filters reducer. + * + * @param {string} filter - A filter type is going to be updated + */ +function toggleRequestFilterType(filter) { + return { + type: TOGGLE_REQUEST_FILTER_TYPE, + filter, + }; +} + +/** + * Enable filter type exclusively. + * Except filter type is set to true, all the other filter types are set + * to false. + * Available filter types are defined in filters reducer. + * + * @param {string} filter - A filter type is going to be updated + */ +function enableRequestFilterTypeOnly(filter) { + return { + type: ENABLE_REQUEST_FILTER_TYPE_ONLY, + filter, + }; +} + +/** + * Set filter text in toolbar. + * + * @param {string} text - A filter text is going to be set + */ +function setRequestFilterText(text) { + return { + type: SET_REQUEST_FILTER_TEXT, + text, + }; +} + +module.exports = { + enableRequestFilterTypeOnly, + toggleRequestFilterType, + setRequestFilterText, +}; diff --git a/devtools/client/netmonitor/src/actions/http-custom-request.js b/devtools/client/netmonitor/src/actions/http-custom-request.js new file mode 100644 index 0000000000..e045107410 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/http-custom-request.js @@ -0,0 +1,128 @@ +/* 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 { + OPEN_ACTION_BAR, + SELECT_ACTION_BAR_TAB, + PANELS, + RIGHT_CLICK_REQUEST, + PRESELECT_REQUEST, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +const { + selectRequest, +} = require("resource://devtools/client/netmonitor/src/actions/selection.js"); + +const { + openNetworkDetails, +} = require("resource://devtools/client/netmonitor/src/actions/ui.js"); + +const { + getRequestById, + getRequestByChannelId, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +const { + fetchNetworkUpdatePacket, +} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js"); + +/** + * Open the entire HTTP Custom Request panel + * @returns {Function} + */ +function openHTTPCustomRequest(isOpen) { + return ({ dispatch, getState }) => { + dispatch({ type: OPEN_ACTION_BAR, open: isOpen }); + + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.HTTP_CUSTOM_REQUEST, + }); + }; +} + +/** + * Toggle visibility of New Custom Request panel in network panel + */ +function toggleHTTPCustomRequestPanel() { + return ({ dispatch, getState }) => { + const state = getState(); + + const shouldClose = + state.ui.networkActionOpen && + state.ui.selectedActionBarTabId === PANELS.HTTP_CUSTOM_REQUEST; + dispatch({ type: OPEN_ACTION_BAR, open: !shouldClose }); + + // reset the right clicked request + dispatch({ type: RIGHT_CLICK_REQUEST, id: null }); + + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.HTTP_CUSTOM_REQUEST, + }); + }; +} + +/** + * Send a new HTTP request using the data in the custom request form. + */ +function sendHTTPCustomRequest(request) { + return async ({ dispatch, getState, connector, commands }) => { + if (!request) { + return; + } + + // Fetch request headers and post data from the backend, if needed. + // This is only needed if we are resending a request without editing. + + if (request.requestHeadersAvailable || request.requestPostDataAvailable) { + await fetchNetworkUpdatePacket(connector.requestData, request, [ + "requestHeaders", + "requestPostData", + ]); + + // Get the request again, to get all the updated data + request = getRequestById(getState(), request.id); + } + + // Send a new HTTP request using the data in the custom request form + const data = { + cause: request.cause || {}, + url: request.url, + method: request.method, + httpVersion: request.httpVersion, + }; + + if (request.requestHeaders) { + data.headers = request.requestHeaders.headers; + } + + if (request.requestPostData) { + data.body = request.requestPostData.postData?.text; + } + + const { channelId } = await commands.networkCommand.sendHTTPRequest(data); + + const newRequest = getRequestByChannelId(getState(), channelId); + // If the new custom request is available already select the request, else + // preselect the request. + if (newRequest) { + await dispatch(selectRequest(newRequest.id)); + } else { + await dispatch({ + type: PRESELECT_REQUEST, + id: channelId, + }); + } + dispatch(openNetworkDetails(true)); + }; +} + +module.exports = { + openHTTPCustomRequest, + toggleHTTPCustomRequestPanel, + sendHTTPCustomRequest, +}; diff --git a/devtools/client/netmonitor/src/actions/index.js b/devtools/client/netmonitor/src/actions/index.js new file mode 100644 index 0000000000..6e28281ab7 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/index.js @@ -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/. */ + +"use strict"; + +const batching = require("resource://devtools/client/netmonitor/src/actions/batching.js"); +const filters = require("resource://devtools/client/netmonitor/src/actions/filters.js"); +const httpCustomRequest = require("resource://devtools/client/netmonitor/src/actions/http-custom-request.js"); +const requests = require("resource://devtools/client/netmonitor/src/actions/requests.js"); +const selection = require("resource://devtools/client/netmonitor/src/actions/selection.js"); +const sort = require("resource://devtools/client/netmonitor/src/actions/sort.js"); +const timingMarkers = require("resource://devtools/client/netmonitor/src/actions/timing-markers.js"); +const ui = require("resource://devtools/client/netmonitor/src/actions/ui.js"); +const messages = require("resource://devtools/client/netmonitor/src/actions/messages.js"); +const search = require("resource://devtools/client/netmonitor/src/actions/search.js"); +const requestBlocking = require("resource://devtools/client/netmonitor/src/actions/request-blocking.js"); + +Object.assign( + exports, + batching, + filters, + httpCustomRequest, + requests, + search, + selection, + sort, + timingMarkers, + ui, + messages, + requestBlocking +); diff --git a/devtools/client/netmonitor/src/actions/messages.js b/devtools/client/netmonitor/src/actions/messages.js new file mode 100644 index 0000000000..a8f49e9735 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/messages.js @@ -0,0 +1,188 @@ +/* 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 { + MSG_ADD, + MSG_SELECT, + MSG_OPEN_DETAILS, + MSG_CLEAR, + MSG_TOGGLE_FILTER_TYPE, + MSG_TOGGLE_CONTROL, + MSG_SET_FILTER_TEXT, + MSG_TOGGLE_COLUMN, + MSG_RESET_COLUMNS, + MSG_CLOSE_CONNECTION, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +const { + getDisplayedMessages, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); +const PAGE_SIZE_ITEM_COUNT_RATIO = 5; + +/** + * Add message into state. + */ +function addMessage(httpChannelId, data, batch) { + return { + type: MSG_ADD, + httpChannelId, + data, + meta: { batch }, + }; +} + +/** + * Select message. + */ +function selectMessage(message) { + return { + type: MSG_SELECT, + open: true, + message, + }; +} + +/** + * Open message details panel. + * + * @param {boolean} open - expected message details panel open state + */ +function openMessageDetails(open) { + return { + type: MSG_OPEN_DETAILS, + open, + }; +} + +/** + * Clear all messages from the MessageListContent + * component belonging to the current channelId + */ +function clearMessages() { + return { + type: MSG_CLEAR, + }; +} + +/** + * Show filtered messages from the MessageListContent + * component belonging to the current channelId + */ +function toggleMessageFilterType(filter) { + return { + type: MSG_TOGGLE_FILTER_TYPE, + filter, + }; +} + +/** + * Show control frames from the MessageListContent + * component belonging to the current channelId + */ +function toggleControlFrames() { + return { + type: MSG_TOGGLE_CONTROL, + }; +} + +/** + * Set filter text in toolbar. + * + */ +function setMessageFilterText(text) { + return { + type: MSG_SET_FILTER_TEXT, + text, + }; +} + +/** + * Resets all Messages columns to their default state. + * + */ +function resetMessageColumns() { + return { + type: MSG_RESET_COLUMNS, + }; +} + +/** + * Toggles a Message column + * + * @param {string} column - The column that is going to be toggled + */ +function toggleMessageColumn(column) { + return { + type: MSG_TOGGLE_COLUMN, + column, + }; +} + +/** + * Sets current connection status to closed + * + * @param {number} httpChannelId - Unique id identifying the channel + * @param {boolean} wasClean - False if connection terminated due to error + * @param {number} code - Error code + * @param {string} reason + */ +function closeConnection(httpChannelId, wasClean, code, reason) { + return { + type: MSG_CLOSE_CONNECTION, + httpChannelId, + wasClean, + code, + reason, + }; +} + +/** + * Move the selection up to down according to the "delta" parameter. Possible values: + * - Number: positive or negative, move up or down by specified distance + * - "PAGE_UP" | "PAGE_DOWN" (String): page up or page down + * - +Infinity | -Infinity: move to the start or end of the list + */ +function selectMessageDelta(delta) { + return ({ dispatch, getState }) => { + const state = getState(); + const messages = getDisplayedMessages(state); + + if (messages.length === 0) { + return; + } + + const selIndex = messages.findIndex( + r => r === state.messages.selectedMessage + ); + + if (delta === "PAGE_DOWN") { + delta = Math.ceil(messages.length / PAGE_SIZE_ITEM_COUNT_RATIO); + } else if (delta === "PAGE_UP") { + delta = -Math.ceil(messages.length / PAGE_SIZE_ITEM_COUNT_RATIO); + } + + const newIndex = Math.min( + Math.max(0, selIndex + delta), + messages.length - 1 + ); + const newItem = messages[newIndex]; + dispatch(selectMessage(newItem)); + }; +} + +module.exports = { + addMessage, + clearMessages, + closeConnection, + openMessageDetails, + resetMessageColumns, + selectMessage, + selectMessageDelta, + setMessageFilterText, + toggleControlFrames, + toggleMessageColumn, + toggleMessageFilterType, +}; diff --git a/devtools/client/netmonitor/src/actions/moz.build b/devtools/client/netmonitor/src/actions/moz.build new file mode 100644 index 0000000000..fc74e8cc56 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/moz.build @@ -0,0 +1,18 @@ +# 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( + "batching.js", + "filters.js", + "http-custom-request.js", + "index.js", + "messages.js", + "request-blocking.js", + "requests.js", + "search.js", + "selection.js", + "sort.js", + "timing-markers.js", + "ui.js", +) diff --git a/devtools/client/netmonitor/src/actions/request-blocking.js b/devtools/client/netmonitor/src/actions/request-blocking.js new file mode 100644 index 0000000000..502999c79f --- /dev/null +++ b/devtools/client/netmonitor/src/actions/request-blocking.js @@ -0,0 +1,155 @@ +/* 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 { + ADD_BLOCKED_URL, + TOGGLE_BLOCKING_ENABLED, + TOGGLE_BLOCKED_URL, + UPDATE_BLOCKED_URL, + REMOVE_BLOCKED_URL, + REMOVE_ALL_BLOCKED_URLS, + ENABLE_ALL_BLOCKED_URLS, + DISABLE_ALL_BLOCKED_URLS, + DISABLE_MATCHING_URLS, + SYNCED_BLOCKED_URLS, + OPEN_ACTION_BAR, + SELECT_ACTION_BAR_TAB, + PANELS, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +function toggleRequestBlockingPanel() { + return async ({ dispatch, getState }) => { + const state = getState(); + if ( + state.ui.networkActionOpen && + state.ui.selectedActionBarTabId === PANELS.BLOCKING + ) { + dispatch(closeRequestBlocking()); + } else { + dispatch(await openRequestBlocking()); + } + }; +} + +function toggleBlockingEnabled(enabled) { + return { + type: TOGGLE_BLOCKING_ENABLED, + enabled, + }; +} + +function removeBlockedUrl(url) { + return { + type: REMOVE_BLOCKED_URL, + url, + }; +} + +function removeAllBlockedUrls() { + return { type: REMOVE_ALL_BLOCKED_URLS }; +} + +function enableAllBlockedUrls() { + return { type: ENABLE_ALL_BLOCKED_URLS }; +} + +function disableAllBlockedUrls() { + return { type: DISABLE_ALL_BLOCKED_URLS }; +} + +function addBlockedUrl(url) { + return { + type: ADD_BLOCKED_URL, + url, + }; +} + +function toggleBlockedUrl(url) { + return { + type: TOGGLE_BLOCKED_URL, + url, + }; +} + +function updateBlockedUrl(oldUrl, newUrl) { + return { + type: UPDATE_BLOCKED_URL, + oldUrl, + newUrl, + }; +} + +async function openRequestBlocking() { + return async ({ dispatch, getState, commands }) => { + const state = getState(); + if (!state.requestBlocking.blockingSynced) { + const blockedUrls = state.requestBlocking.blockedUrls; + const responses = await commands.networkCommand.getBlockedUrls(); + const urls = responses.flat(); + if (urls.length !== blockedUrls.length) { + urls.forEach(url => dispatch(addBlockedUrl(url))); + } + dispatch({ type: SYNCED_BLOCKED_URLS, synced: true }); + } + + dispatch({ type: OPEN_ACTION_BAR, open: true }); + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.BLOCKING, + }); + }; +} + +function closeRequestBlocking() { + return ({ dispatch }) => { + dispatch({ type: OPEN_ACTION_BAR, open: false }); + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.BLOCKING, + }); + }; +} + +function openRequestBlockingAndAddUrl(url) { + return async ({ dispatch, getState }) => { + const showBlockingPanel = Services.prefs.getBoolPref( + "devtools.netmonitor.features.requestBlocking" + ); + + if (showBlockingPanel) { + dispatch(await openRequestBlocking()); + } + dispatch({ type: ADD_BLOCKED_URL, url }); + }; +} + +function openRequestBlockingAndDisableUrls(url) { + return async ({ dispatch, getState }) => { + const showBlockingPanel = Services.prefs.getBoolPref( + "devtools.netmonitor.features.requestBlocking" + ); + + if (showBlockingPanel) { + dispatch(await openRequestBlocking()); + } + + dispatch({ type: DISABLE_MATCHING_URLS, url }); + }; +} + +module.exports = { + toggleRequestBlockingPanel, + addBlockedUrl, + toggleBlockingEnabled, + toggleBlockedUrl, + removeBlockedUrl, + removeAllBlockedUrls, + enableAllBlockedUrls, + disableAllBlockedUrls, + updateBlockedUrl, + openRequestBlockingAndAddUrl, + openRequestBlockingAndDisableUrls, +}; diff --git a/devtools/client/netmonitor/src/actions/requests.js b/devtools/client/netmonitor/src/actions/requests.js new file mode 100644 index 0000000000..838f2509a9 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/requests.js @@ -0,0 +1,183 @@ +/* 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 { + ADD_REQUEST, + CLEAR_REQUESTS, + CLONE_REQUEST, + CLONE_SELECTED_REQUEST, + REMOVE_SELECTED_CUSTOM_REQUEST, + RIGHT_CLICK_REQUEST, + SEND_CUSTOM_REQUEST, + SET_EVENT_STREAM_FLAG, + SET_RECORDING_STATE, + UPDATE_REQUEST, +} = require("resource://devtools/client/netmonitor/src/constants.js"); +const { + getSelectedRequest, + getRequestById, + getRecordingState, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); +const { + fetchNetworkUpdatePacket, +} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js"); + +function addRequest(id, data, batch) { + return { + type: ADD_REQUEST, + id, + data, + meta: { batch }, + }; +} + +function updateRequest(id, data, batch) { + return { + type: UPDATE_REQUEST, + id, + data, + meta: { batch }, + }; +} + +function setEventStreamFlag(id, batch) { + return { + type: SET_EVENT_STREAM_FLAG, + id, + meta: { batch }, + }; +} + +/** + * Clone request by id. Used when cloning a request + * through the "Edit and Resend" option present in the context menu. + */ +function cloneRequest(id) { + return { + id, + type: CLONE_REQUEST, + }; +} + +/** + * Right click a request without selecting it. + */ +function rightClickRequest(id) { + return { + id, + type: RIGHT_CLICK_REQUEST, + }; +} + +/** + * Clone the currently selected request, set the "isCustom" attribute. + * Used by the "Edit and Resend" feature. + */ +function cloneSelectedRequest() { + return { + type: CLONE_SELECTED_REQUEST, + }; +} + +/** + * Send a new HTTP request using the data in the custom request form. + */ +function sendCustomRequest(requestId = null) { + return async ({ dispatch, getState, connector, commands }) => { + let request; + if (requestId) { + request = getRequestById(getState(), requestId); + } else { + request = getSelectedRequest(getState()); + } + + if (!request) { + return; + } + + // Fetch request headers and post data from the backend. + await fetchNetworkUpdatePacket(connector.requestData, request, [ + "requestHeaders", + "requestPostData", + ]); + + // Reload the request from the store to get the headers. + request = getRequestById(getState(), request.id); + + // Send a new HTTP request using the data in the custom request form + const data = { + cause: request.cause, + url: request.url, + method: request.method, + httpVersion: request.httpVersion, + }; + + if (request.requestHeaders) { + data.headers = request.requestHeaders.headers; + } + + if (request.requestPostData) { + data.body = request.requestPostData.postData.text; + } + + const { channelId } = await commands.networkCommand.sendHTTPRequest(data); + + dispatch({ + type: SEND_CUSTOM_REQUEST, + id: channelId, + }); + }; +} + +/** + * Remove a request from the list. Supports removing only cloned requests with a + * "isCustom" attribute. Other requests never need to be removed. + */ +function removeSelectedCustomRequest() { + return { + type: REMOVE_SELECTED_CUSTOM_REQUEST, + }; +} +/** + * Clear all requests + */ +function clearRequests() { + return ({ dispatch, connector }) => { + dispatch({ type: CLEAR_REQUESTS }); + connector.clear(); + }; +} + +/** + * Toggle monitoring + */ +function toggleRecording() { + return async ({ dispatch, getState, connector }) => { + const recording = !getRecordingState(getState()); + if (recording) { + await connector.resume(); + } else { + connector.pause(); + } + dispatch({ + type: SET_RECORDING_STATE, + recording, + }); + }; +} + +module.exports = { + addRequest, + clearRequests, + cloneRequest, + cloneSelectedRequest, + rightClickRequest, + removeSelectedCustomRequest, + sendCustomRequest, + setEventStreamFlag, + toggleRecording, + updateRequest, +}; diff --git a/devtools/client/netmonitor/src/actions/search.js b/devtools/client/netmonitor/src/actions/search.js new file mode 100644 index 0000000000..97b123d361 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/search.js @@ -0,0 +1,316 @@ +/* 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 { + ADD_SEARCH_QUERY, + ADD_SEARCH_RESULT, + CLEAR_SEARCH_RESULTS, + ADD_ONGOING_SEARCH, + OPEN_ACTION_BAR, + UPDATE_SEARCH_STATUS, + SEARCH_STATUS, + SET_TARGET_SEARCH_RESULT, + SELECT_ACTION_BAR_TAB, + TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH, + PANELS, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +const { + getDisplayedRequests, + getOngoingSearch, + getSearchStatus, + getRequestById, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +const { + selectRequest, +} = require("resource://devtools/client/netmonitor/src/actions/selection.js"); +const { + selectDetailsPanelTab, +} = require("resource://devtools/client/netmonitor/src/actions/ui.js"); +const { + fetchNetworkUpdatePacket, +} = require("resource://devtools/client/netmonitor/src/utils/request-utils.js"); +const { + searchInResource, +} = require("resource://devtools/client/netmonitor/src/workers/search/index.js"); + +/** + * Search through all resources. This is the main action exported + * from this module and consumed by Network panel UI. + */ +function search(connector, query) { + let canceled = false; + + // Instantiate an `ongoingSearch` function/object. It's responsible + // for triggering set of asynchronous steps like fetching + // data from the backend and performing search over it. + // This `ongoingSearch` is stored in the Search reducer, so it can + // be canceled if needed (e.g. when new search is executed). + const newOngoingSearch = async ({ dispatch, getState }) => { + const state = getState(); + + dispatch(stopOngoingSearch()); + + await dispatch(addOngoingSearch(newOngoingSearch)); + await dispatch(clearSearchResults()); + await dispatch(addSearchQuery(query)); + + dispatch(updateSearchStatus(SEARCH_STATUS.FETCHING)); + + // Loop over all displayed resources (in the sorted order), + // fetch all the details data and run search worker that + // search through the resource structure. + const requests = getDisplayedRequests(state); + for (const request of requests) { + if (canceled) { + return; + } + + // Fetch all data for the resource. + await loadResource(connector, request); + if (canceled) { + return; + } + + // The state changed, so make sure to get fresh new reference + // to the updated resource object. + const updatedResource = getRequestById(getState(), request.id); + await dispatch(searchResource(updatedResource, query)); + } + + dispatch(updateSearchStatus(SEARCH_STATUS.DONE)); + }; + + // Implement support for canceling (used e.g. when a new search + // is executed or the user stops the searching manually). + newOngoingSearch.cancel = () => { + canceled = true; + }; + + newOngoingSearch.isCanceled = () => { + return canceled; + }; + + return newOngoingSearch; +} + +/** + * Fetch all data related to the specified resource from the backend. + */ +async function loadResource(connector, resource) { + const updateTypes = [ + "responseHeaders", + "requestHeaders", + "responseCookies", + "requestCookies", + "requestPostData", + "responseContent", + "responseCache", + "stackTrace", + "securityInfo", + ]; + + return fetchNetworkUpdatePacket(connector.requestData, resource, updateTypes); +} + +/** + * Search through all data within the specified resource. + */ +function searchResource(resource, query) { + return async ({ dispatch, getState }) => { + const state = getState(); + const ongoingSearch = getOngoingSearch(state); + + const modifiers = { + caseSensitive: state.search.caseSensitive, + }; + + // Run search in a worker and wait for the results. The return + // value is an array with search occurrences. + const result = await searchInResource(resource, query, modifiers); + + if (!result.length || ongoingSearch.isCanceled()) { + return; + } + + dispatch(addSearchResult(resource, result)); + }; +} + +/** + * Add search query to the reducer. + */ +function addSearchResult(resource, result) { + return { + type: ADD_SEARCH_RESULT, + resource, + result, + }; +} + +/** + * Add search query to the reducer. + */ +function addSearchQuery(query) { + return { + type: ADD_SEARCH_QUERY, + query, + }; +} + +/** + * Clear all search results. + */ +function clearSearchResults() { + return { + type: CLEAR_SEARCH_RESULTS, + }; +} + +/** + * Used to clear and cancel an ongoing search. + * @returns {Function} + */ +function clearSearchResultAndCancel() { + return ({ dispatch, getState }) => { + dispatch(stopOngoingSearch()); + dispatch(clearSearchResults()); + }; +} + +/** + * Update status of the current search. + */ +function updateSearchStatus(status) { + return { + type: UPDATE_SEARCH_STATUS, + status, + }; +} + +/** + * Close the entire search panel. + */ +function closeSearch() { + return ({ dispatch, getState }) => { + dispatch(stopOngoingSearch()); + dispatch({ type: OPEN_ACTION_BAR, open: false }); + }; +} + +/** + * Open the entire search panel + * @returns {Function} + */ +function openSearch() { + return ({ dispatch, getState }) => { + dispatch({ type: OPEN_ACTION_BAR, open: true }); + + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.SEARCH, + }); + }; +} + +/** + * Toggles case sensitive search + * @returns {Function} + */ +function toggleCaseSensitiveSearch() { + return ({ dispatch, getState }) => { + dispatch({ type: TOGGLE_SEARCH_CASE_SENSITIVE_SEARCH }); + }; +} + +/** + * Toggle visibility of search panel in network panel + */ +function toggleSearchPanel() { + return ({ dispatch, getState }) => { + const state = getState(); + + state.ui.networkActionOpen && + state.ui.selectedActionBarTabId === PANELS.SEARCH + ? dispatch({ type: OPEN_ACTION_BAR, open: false }) + : dispatch({ type: OPEN_ACTION_BAR, open: true }); + + dispatch({ + type: SELECT_ACTION_BAR_TAB, + id: PANELS.SEARCH, + }); + }; +} + +/** + * Append new search object into the reducer. The search object + * is cancellable and so, it implements `cancel` method. + */ +function addOngoingSearch(ongoingSearch) { + return { + type: ADD_ONGOING_SEARCH, + ongoingSearch, + }; +} + +/** + * Cancel the current ongoing search. + */ +function stopOngoingSearch() { + return ({ dispatch, getState }) => { + const state = getState(); + const ongoingSearch = getOngoingSearch(state); + const status = getSearchStatus(state); + + if (ongoingSearch && status !== SEARCH_STATUS.DONE) { + ongoingSearch.cancel(); + dispatch(updateSearchStatus(SEARCH_STATUS.CANCELED)); + } + }; +} + +/** + * This action is fired when the user selects a search result + * within the Search panel. It opens the details side bar and + * selects the right side panel to show the context of the + * clicked search result. + */ +function navigate(searchResult) { + return ({ dispatch, getState }) => { + // Store target search result in Search reducer. It's used + // for search result navigation within the side panels. + dispatch(setTargetSearchResult(searchResult)); + + // Preselect the right side panel. + dispatch(selectDetailsPanelTab(searchResult.panel)); + + // Select related request in the UI (it also opens the + // right side bar automatically). + dispatch(selectRequest(searchResult.parentResource.id)); + }; +} + +function setTargetSearchResult(searchResult) { + return { + type: SET_TARGET_SEARCH_RESULT, + searchResult, + }; +} + +module.exports = { + search, + closeSearch, + openSearch, + clearSearchResults, + addSearchQuery, + toggleSearchPanel, + navigate, + setTargetSearchResult, + toggleCaseSensitiveSearch, + clearSearchResultAndCancel, + stopOngoingSearch, +}; diff --git a/devtools/client/netmonitor/src/actions/selection.js b/devtools/client/netmonitor/src/actions/selection.js new file mode 100644 index 0000000000..4603fcb61c --- /dev/null +++ b/devtools/client/netmonitor/src/actions/selection.js @@ -0,0 +1,80 @@ +/* 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 { + SELECT_REQUEST, +} = require("resource://devtools/client/netmonitor/src/constants.js"); +const { + getDisplayedRequests, + getSortedRequests, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +const PAGE_SIZE_ITEM_COUNT_RATIO = 5; + +/** + * Select request with a given id. + */ +function selectRequest(id, request) { + return { + type: SELECT_REQUEST, + id, + request, + }; +} + +/** + * Select request with a given index (sorted order) + */ +function selectRequestByIndex(index) { + return ({ dispatch, getState }) => { + const requests = getSortedRequests(getState()); + let itemId; + if (index >= 0 && index < requests.length) { + itemId = requests[index].id; + } + dispatch(selectRequest(itemId)); + }; +} + +/** + * Move the selection up to down according to the "delta" parameter. Possible values: + * - Number: positive or negative, move up or down by specified distance + * - "PAGE_UP" | "PAGE_DOWN" (String): page up or page down + * - +Infinity | -Infinity: move to the start or end of the list + */ +function selectDelta(delta) { + return ({ dispatch, getState }) => { + const state = getState(); + const requests = getDisplayedRequests(state); + + if (!requests.length) { + return; + } + + const selIndex = requests.findIndex( + r => r.id === state.requests.selectedId + ); + + if (delta === "PAGE_DOWN") { + delta = Math.ceil(requests.length / PAGE_SIZE_ITEM_COUNT_RATIO); + } else if (delta === "PAGE_UP") { + delta = -Math.ceil(requests.length / PAGE_SIZE_ITEM_COUNT_RATIO); + } + + const newIndex = Math.min( + Math.max(0, selIndex + delta), + requests.length - 1 + ); + const newItem = requests[newIndex]; + dispatch(selectRequest(newItem.id, newItem)); + }; +} + +module.exports = { + selectRequest, + selectRequestByIndex, + selectDelta, +}; diff --git a/devtools/client/netmonitor/src/actions/sort.js b/devtools/client/netmonitor/src/actions/sort.js new file mode 100644 index 0000000000..06c3f92c54 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/sort.js @@ -0,0 +1,20 @@ +/* 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 { + SORT_BY, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +function sortBy(sortType) { + return { + type: SORT_BY, + sortType, + }; +} + +module.exports = { + sortBy, +}; diff --git a/devtools/client/netmonitor/src/actions/timing-markers.js b/devtools/client/netmonitor/src/actions/timing-markers.js new file mode 100644 index 0000000000..cce53e8100 --- /dev/null +++ b/devtools/client/netmonitor/src/actions/timing-markers.js @@ -0,0 +1,22 @@ +/* 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 { + ADD_TIMING_MARKER, + CLEAR_TIMING_MARKERS, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +exports.addTimingMarker = marker => { + return { + type: ADD_TIMING_MARKER, + marker, + }; +}; + +exports.clearTimingMarkers = () => { + return { + type: CLEAR_TIMING_MARKERS, + }; +}; diff --git a/devtools/client/netmonitor/src/actions/ui.js b/devtools/client/netmonitor/src/actions/ui.js new file mode 100644 index 0000000000..4be087c5df --- /dev/null +++ b/devtools/client/netmonitor/src/actions/ui.js @@ -0,0 +1,257 @@ +/* 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 { + ACTIVITY_TYPE, + OPEN_NETWORK_DETAILS, + RESIZE_NETWORK_DETAILS, + ENABLE_PERSISTENT_LOGS, + DISABLE_BROWSER_CACHE, + OPEN_STATISTICS, + RESET_COLUMNS, + SELECT_DETAILS_PANEL_TAB, + SELECT_ACTION_BAR_TAB, + TOGGLE_COLUMN, + WATERFALL_RESIZE, + SET_COLUMNS_WIDTH, + SET_HEADERS_URL_PREVIEW_EXPANDED, + OPEN_ACTION_BAR, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +const { + getDisplayedRequests, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +const DEVTOOLS_DISABLE_CACHE_PREF = "devtools.cache.disabled"; + +/** + * Change network details panel. + * + * @param {boolean} open - expected network details panel open state + */ +function openNetworkDetails(open) { + return ({ dispatch, getState }) => { + const visibleRequestItems = getDisplayedRequests(getState()); + const defaultSelectedId = visibleRequestItems.length + ? visibleRequestItems[0].id + : null; + + return dispatch({ + type: OPEN_NETWORK_DETAILS, + open, + defaultSelectedId, + }); + }; +} + +/** + * Change network action bar open state. + * + * @param {boolean} open - expected network action bar open state + */ +function openNetworkActionBar(open) { + return { + type: OPEN_ACTION_BAR, + open, + }; +} + +/** + * Change network details panel size. + * + * @param {integer} width + * @param {integer} height + */ +function resizeNetworkDetails(width, height) { + return { + type: RESIZE_NETWORK_DETAILS, + width, + height, + }; +} + +/** + * Change persistent logs state. + * + * @param {boolean} enabled - expected persistent logs enabled state + */ +function enablePersistentLogs(enabled, skipTelemetry = false) { + return { + type: ENABLE_PERSISTENT_LOGS, + enabled, + skipTelemetry, + }; +} + +/** + * Change browser cache state. + * + * @param {boolean} disabled - expected browser cache in disable state + */ +function disableBrowserCache(disabled) { + return { + type: DISABLE_BROWSER_CACHE, + disabled, + }; +} + +/** + * Change performance statistics panel open state. + * + * @param {Object} connector - connector object to the backend + * @param {boolean} visible - expected performance statistics panel open state + */ +function openStatistics(connector, open) { + if (open) { + connector.triggerActivity(ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED); + } else if (Services.prefs.getBoolPref(DEVTOOLS_DISABLE_CACHE_PREF)) { + // Opening the Statistics panel reconfigures the page and enables + // the browser cache (using ACTIVITY_TYPE.RELOAD.WITH_CACHE_ENABLED). + // So, make sure to disable the cache again when the user returns back + // from the Statistics panel (if DEVTOOLS_DISABLE_CACHE_PREF == true). + // See also bug 1430359. + connector.triggerActivity(ACTIVITY_TYPE.DISABLE_CACHE); + } + return { + type: OPEN_STATISTICS, + open, + }; +} + +/** + * Resets all columns to their default state. + * + */ +function resetColumns() { + return { + type: RESET_COLUMNS, + }; +} + +/** + * Waterfall width has changed (likely on window resize). Update the UI. + */ +function resizeWaterfall(width) { + return { + type: WATERFALL_RESIZE, + width, + }; +} + +/** + * Change the selected tab for network details panel. + * + * @param {string} id - tab id to be selected + */ +function selectDetailsPanelTab(id) { + return { + type: SELECT_DETAILS_PANEL_TAB, + id, + }; +} + +/** + * Change the selected tab for network action bar. + * + * @param {string} id - tab id to be selected + */ +function selectActionBarTab(id) { + return { + type: SELECT_ACTION_BAR_TAB, + id, + }; +} + +/** + * Toggles a column + * + * @param {string} column - The column that is going to be toggled + */ +function toggleColumn(column) { + return { + type: TOGGLE_COLUMN, + column, + }; +} + +/** + * Set width of multiple columns + * + * @param {array} widths - array of pairs {name, width} + */ +function setColumnsWidth(widths) { + return { + type: SET_COLUMNS_WIDTH, + widths, + }; +} + +/** + * Toggle network details panel. + */ +function toggleNetworkDetails() { + return ({ dispatch, getState }) => + dispatch(openNetworkDetails(!getState().ui.networkDetailsOpen)); +} + +/** + * Toggle network action panel. + */ +function toggleNetworkActionBar() { + return ({ dispatch, getState }) => + dispatch(openNetworkActionBar(!getState().ui.networkActionOpen)); +} + +/** + * Toggle persistent logs status. + */ +function togglePersistentLogs() { + return ({ dispatch, getState }) => + dispatch(enablePersistentLogs(!getState().ui.persistentLogsEnabled)); +} + +/** + * Toggle browser cache status. + */ +function toggleBrowserCache() { + return ({ dispatch, getState }) => + dispatch(disableBrowserCache(!getState().ui.browserCacheDisabled)); +} + +/** + * Toggle performance statistics panel. + */ +function toggleStatistics(connector) { + return ({ dispatch, getState }) => + dispatch(openStatistics(connector, !getState().ui.statisticsOpen)); +} + +function setHeadersUrlPreviewExpanded(expanded) { + return { + type: SET_HEADERS_URL_PREVIEW_EXPANDED, + expanded, + }; +} + +module.exports = { + openNetworkDetails, + openNetworkActionBar, + resizeNetworkDetails, + enablePersistentLogs, + disableBrowserCache, + openStatistics, + resetColumns, + resizeWaterfall, + selectDetailsPanelTab, + selectActionBarTab, + toggleColumn, + setColumnsWidth, + toggleNetworkDetails, + toggleNetworkActionBar, + togglePersistentLogs, + toggleBrowserCache, + toggleStatistics, + setHeadersUrlPreviewExpanded, +}; diff --git a/devtools/client/netmonitor/src/api.js b/devtools/client/netmonitor/src/api.js new file mode 100644 index 0000000000..8d760de788 --- /dev/null +++ b/devtools/client/netmonitor/src/api.js @@ -0,0 +1,216 @@ +/* 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 EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +const { + bindActionCreators, +} = require("resource://devtools/client/shared/vendor/redux.js"); +const { + Connector, +} = require("resource://devtools/client/netmonitor/src/connector/index.js"); +const { + configureStore, +} = require("resource://devtools/client/netmonitor/src/create-store.js"); +const { + EVENTS, +} = require("resource://devtools/client/netmonitor/src/constants.js"); +const Actions = require("resource://devtools/client/netmonitor/src/actions/index.js"); + +const { + getDisplayedRequestById, + getSortedRequests, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +/** + * API object for NetMonitor panel (like a facade). This object can be + * consumed by other panels, WebExtension API, etc. + * + * This object doesn't depend on the panel UI and can be created + * and used even if the Network panel UI doesn't exist. + */ +function NetMonitorAPI() { + EventEmitter.decorate(this); + + // Connector to the backend. + this.connector = new Connector(); + + // List of listeners for `devtools.network.onRequestFinished` WebExt API + this._requestFinishedListeners = new Set(); + + // Bind event handlers + this.onPayloadReady = this.onPayloadReady.bind(this); +} + +NetMonitorAPI.prototype = { + async connect(toolbox) { + // Bail out if already connected. + if (this.toolbox) { + return; + } + + this.toolbox = toolbox; + + // Configure store/state object. + this.store = configureStore( + this.connector, + this.toolbox.commands, + this.toolbox.telemetry + ); + this.actions = bindActionCreators(Actions, this.store.dispatch); + + // Register listener for new requests (utilized by WebExtension API). + this.on(EVENTS.PAYLOAD_READY, this.onPayloadReady); + + // Initialize connection to the backend. Pass `this` as the owner, + // so this object can receive all emitted events. + const connection = { + toolbox, + owner: this, + }; + + await this.connector.connect(connection, this.actions, this.store.getState); + }, + + /** + * Clean up (unmount from DOM, remove listeners, disconnect). + */ + destroy() { + this.off(EVENTS.PAYLOAD_READY, this.onPayloadReady); + + this.connector.disconnect(); + + if (this.harExportConnector) { + this.harExportConnector.disconnect(); + } + }, + + // HAR + + /** + * Support for `devtools.network.getHAR` (get collected data as HAR) + */ + async getHar() { + const { + HarExporter, + } = require("resource://devtools/client/netmonitor/src/har/har-exporter.js"); + const state = this.store.getState(); + + const options = { + connector: this.connector, + items: getSortedRequests(state), + }; + + return HarExporter.getHar(options); + }, + + /** + * Support for `devtools.network.onRequestFinished`. A hook for + * every finished HTTP request used by WebExtensions API. + */ + async onPayloadReady(resource) { + if (!this._requestFinishedListeners.size) { + return; + } + + const { + HarExporter, + } = require("resource://devtools/client/netmonitor/src/har/har-exporter.js"); + + const connector = await this.getHarExportConnector(); + const request = getDisplayedRequestById( + this.store.getState(), + resource.actor + ); + if (!request) { + console.error("HAR: request not found " + resource.actor); + return; + } + + const options = { + connector, + includeResponseBodies: false, + items: [request], + }; + + const har = await HarExporter.getHar(options); + + // There is page so remove the page reference. + const harEntry = har.log.entries[0]; + delete harEntry.pageref; + + this._requestFinishedListeners.forEach(listener => + listener({ + harEntry, + requestId: resource.actor, + }) + ); + }, + + /** + * Support for `Request.getContent` WebExt API (lazy loading response body) + */ + async fetchResponseContent(requestId) { + return this.connector.requestData(requestId, "responseContent"); + }, + + /** + * Add listener for `onRequestFinished` events. + * + * @param {Object} listener + * The listener to be called it's expected to be + * a function that takes ({harEntry, requestId}) + * as first argument. + */ + addRequestFinishedListener(listener) { + this._requestFinishedListeners.add(listener); + }, + + removeRequestFinishedListener(listener) { + this._requestFinishedListeners.delete(listener); + }, + + hasRequestFinishedListeners() { + return this._requestFinishedListeners.size > 0; + }, + + /** + * Separate connector for HAR export. + */ + async getHarExportConnector() { + if (this.harExportConnector) { + // Wait for the connector to be ready to avoid exceptions if this method is called + // twice during its initialization. + await this.harExportConnectorReady; + return this.harExportConnector; + } + + const connection = { + toolbox: this.toolbox, + }; + + this.harExportConnector = new Connector(); + this.harExportConnectorReady = this.harExportConnector.connect(connection); + + await this.harExportConnectorReady; + return this.harExportConnector; + }, + + /** + * Resends a given network request + * @param {String} requestId + * Id of the network request + */ + resendRequest(requestId) { + // Flush queued requests. + this.store.dispatch(Actions.batchFlush()); + // Send custom request with same url, headers and body as the request + // with the given requestId. + this.store.dispatch(Actions.sendCustomRequest(requestId)); + }, +}; + +exports.NetMonitorAPI = NetMonitorAPI; diff --git a/devtools/client/netmonitor/src/app.js b/devtools/client/netmonitor/src/app.js new file mode 100644 index 0000000000..d7cf642d48 --- /dev/null +++ b/devtools/client/netmonitor/src/app.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 { + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + render, + unmountComponentAtNode, +} = require("resource://devtools/client/shared/vendor/react-dom.js"); +const Provider = createFactory( + require("resource://devtools/client/shared/vendor/react-redux.js").Provider +); +const App = createFactory( + require("resource://devtools/client/netmonitor/src/components/App.js") +); +const { + EVENTS, +} = require("resource://devtools/client/netmonitor/src/constants.js"); + +const { + getDisplayedRequestById, +} = require("resource://devtools/client/netmonitor/src/selectors/index.js"); + +const SearchDispatcher = require("resource://devtools/client/netmonitor/src/workers/search/index.js"); + +/** + * Global App object for Network panel. This object depends + * on the UI and can't be created independently. + * + * This object can be consumed by other panels (e.g. Console + * is using inspectRequest), by the Launchpad (bootstrap), etc. + * + * @param {Object} api An existing API object to be reused. + */ +function NetMonitorApp(api) { + this.api = api; +} + +NetMonitorApp.prototype = { + async bootstrap({ toolbox, document, win }) { + // Get the root element for mounting. + this.mount = document.querySelector("#mount"); + + const openLink = link => { + const parentDoc = toolbox.doc; + const iframe = parentDoc.getElementById( + "toolbox-panel-iframe-netmonitor" + ); + const { top } = iframe.ownerDocument.defaultView; + top.openWebLinkIn(link, "tab"); + }; + + const openSplitConsole = err => { + toolbox.openSplitConsole().then(() => { + toolbox.target.logErrorInPage(err, "har"); + }); + }; + + const { actions, connector, store } = this.api; + + const sourceMapURLService = toolbox.sourceMapURLService; + const app = App({ + actions, + connector, + openLink, + openSplitConsole, + sourceMapURLService, + toolboxDoc: toolbox.doc, + }); + + // Render the root Application component. + render(Provider({ store }, app), this.mount); + }, + + /** + * Clean up (unmount from DOM, remove listeners, disconnect). + */ + destroy() { + unmountComponentAtNode(this.mount); + + SearchDispatcher.stop(); + + // Make sure to destroy the API object. It's usually destroyed + // in the Toolbox destroy method, but we need it here for case + // where the Network panel is initialized without the toolbox + // and running in a tab (see initialize.js for details). + this.api.destroy(); + }, + + /** + * Selects the specified request in the waterfall and opens the details view. + * This is a firefox toolbox specific API, which providing an ability to inspect + * a network request directly from other internal toolbox panel. + * + * @param {string} requestId The actor ID of the request to inspect. + * @return {object} A promise resolved once the task finishes. + */ + async inspectRequest(requestId) { + const { actions, store } = this.api; + + // Look for the request in the existing ones or wait for it to appear, + // if the network monitor is still loading. + return new Promise(resolve => { + let request = null; + const inspector = () => { + request = getDisplayedRequestById(store.getState(), requestId); + if (!request) { + // Reset filters so that the request is visible. + actions.toggleRequestFilterType("all"); + request = getDisplayedRequestById(store.getState(), requestId); + } + + // If the request was found, select it. Otherwise this function will be + // called again once new requests arrive. + if (request) { + this.api.off(EVENTS.REQUEST_ADDED, inspector); + actions.selectRequest(request.id); + resolve(); + } + }; + + inspector(); + + if (!request) { + this.api.on(EVENTS.REQUEST_ADDED, inspector); + } + }); + }, +}; + +exports.NetMonitorApp = NetMonitorApp; diff --git a/devtools/client/netmonitor/src/assets/icons/arrow-up.svg b/devtools/client/netmonitor/src/assets/icons/arrow-up.svg new file mode 100644 index 0000000000..ed45876011 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/icons/arrow-up.svg @@ -0,0 +1,6 @@ + + + + diff --git a/devtools/client/netmonitor/src/assets/icons/play.svg b/devtools/client/netmonitor/src/assets/icons/play.svg new file mode 100644 index 0000000000..a47acd4613 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/icons/play.svg @@ -0,0 +1,8 @@ + + + + + + diff --git a/devtools/client/netmonitor/src/assets/icons/shield.svg b/devtools/client/netmonitor/src/assets/icons/shield.svg new file mode 100644 index 0000000000..dd7676d59f --- /dev/null +++ b/devtools/client/netmonitor/src/assets/icons/shield.svg @@ -0,0 +1,6 @@ + + + + diff --git a/devtools/client/netmonitor/src/assets/icons/turtle.svg b/devtools/client/netmonitor/src/assets/icons/turtle.svg new file mode 100644 index 0000000000..1f308649f3 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/icons/turtle.svg @@ -0,0 +1,6 @@ + + + + diff --git a/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css b/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css new file mode 100644 index 0000000000..9549985326 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/CustomRequestPanel.css @@ -0,0 +1,181 @@ +/* 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/. */ + +.network-monitor .custom-method-and-url .custom-method-value-label { + grid-column: 1 / 1; + grid-row: 1 / 1; +} + +.network-monitor .custom-method-and-url .custom-url-value { + grid-column: 2 / 2; + grid-row: 2 / 2; + margin-inline-start: 12px; +} + +.network-monitor .custom-method-and-url .custom-method-value { + grid-column: 1 / 1; + grid-row: 2 / 2; +} + +.network-monitor .custom-method-and-url .custom-url-value-label { + grid-column: 2 / 2; + grid-row: 1 / 1 ; + margin-inline-start: 12px; +} + +.network-monitor .tabpanel-summary-container.custom-method-and-url { + display: grid; + grid-template-columns: auto 1fr; +} + +.network-monitor .custom-method-and-url input { + font-weight: 400; + margin-top: 4px; + min-width: 9ch; + padding: 2px 3px; +} + +.network-monitor .custom-request-panel textarea { + font-weight: 400; + margin-top: 4px; + padding: 8px; + direction: ltr; +} + +.network-monitor .custom-request-panel { + display: flex; + flex-direction: column; + height: 100%; +} + +.network-monitor .custom-request-panel .custom-request-panel-content { + flex: 1 1 auto; + height: auto; + overflow: auto; +} + +.network-monitor .custom-request-panel-content > div:not(.custom-request) { + margin-bottom: 12px; + padding-inline: 16px; +} + +.network-monitor .custom-request { + display: block; + padding: 0; +} + +.network-monitor .custom-request .custom-request-button-container { + display: flex; + flex-wrap: wrap-reverse; + gap: 8px; + margin-block: 16px 12px; + margin-inline: 16px; +} + +.network-monitor .custom-request-panel .custom-request-label { + font-weight: 400; + white-space: nowrap; +} + +.network-monitor .custom-request button { + height: 24px; + margin-bottom: 4px; + padding-inline: 8px; + width: auto; +} + +.network-monitor .custom-request button:focus { + box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff, + 0 0 0 4px rgba(10,132,255,0.3) +} + +.network-monitor .custom-request #custom-request-send-button { + background-color: var(--blue-60); + color: white; +} + +.network-monitor .custom-request #custom-request-send-button:active { + background-color: var(--blue-80); +} + +.network-monitor .custom-request #custom-request-send-button:hover { + background-color: var(--blue-70); +} + +.network-monitor .custom-request #custom-request-close-button { + margin-inline-end: 4px; +} + +.network-monitor .custom-header { + border-style: solid; + border-width: 0; + flex: none; + height: calc(var(--theme-toolbar-height) + 1px); + padding: 4px 16px; +} + +:root.theme-dark .network-details-bar .custom-request-panel { + background-color: var(--grey-85); +} + +:root.theme-dark .network-monitor #custom-request-close-button { + background-color: var(--toolbarbutton-background); + border: 1px solid var(--theme-splitter-color); +} + +:root.theme-dark .network-monitor #custom-request-close-button:hover:active { + background-color: var(--theme-selection-background-hover); +} + +:root.theme-dark .network-monitor #custom-request-close-button:focus { + background-color: var(--theme-selection-focus-background); +} + +:root.theme-dark .network-monitor .custom-request-label.custom-header { + background-color: var(--grey-80); + border-bottom: 1px solid var(--theme-splitter-color); +} + +:root.theme-dark .network-details-bar .custom-request-panel input, +:root.theme-dark .network-details-bar .custom-request-panel textarea { + background-color: var(--grey-70); + border: 1px solid var(--grey-85); + color: white; +} + +:root.theme-dark .network-monitor .custom-request-label { + color: var(--grey-40); +} + +:root.theme-light .network-details-bar .custom-request-label.custom-header { + background-color: var(--grey-10); + border-bottom: 1px solid var(--grey-25); +} + +:root.theme-light .network-monitor #custom-request-close-button { + background-color: var(--grey-20); + border: var(--theme-splitter-color); +} + +:root.theme-light .network-monitor #custom-request-close-button:hover:active { + background-color: var(--theme-selection-background-hover); +} + +:root.theme-light .network-monitor #custom-request-close-button:focus { + outline: 2px solid var(--blue-50); + outline-offset: -2px; + box-shadow: 0 0 0 2px rgba(10, 132, 255, 0.3); + border-radius: 2px; +} + +:root.theme-light .network-details-bar .custom-request-panel input, +:root.theme-light .network-details-bar .custom-request-panel textarea { + background-color: white; + border: 1px solid var(--grey-25); + color: var(--grey-90); +} + +:root.theme-light .network-monitor .custom-request-label { + color: var(--grey-60); +} diff --git a/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css b/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css new file mode 100644 index 0000000000..cd0f269bc6 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css @@ -0,0 +1,379 @@ +/* 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/. */ + +.network-monitor .tabpanel-summary-container:is(.http-custom-section, .http-custom-method-and-url, .http-custom-input ) { + padding-inline-start: 0; + margin: 0; +} + +.network-monitor .tabpanel-summary-container.http-custom-method-and-url { + display: grid; + grid-template-columns: auto 1fr; + width: 100%; +} + +.network-monitor .http-custom-method-and-url .http-custom-method-value { + grid-column: 1 / 1; + grid-row: 1 / 1; + align-self: start; + margin-inline-start: 10px; + padding-top: 4px; + font-size: 11px; + line-height: 13px; +} + +.auto-growing-textarea { + display: grid; + width: 100%; +} + +.auto-growing-textarea:focus-within::after { + content: attr(data-replicated-value) " "; + white-space: pre-wrap; + visibility: hidden; + word-wrap: break-word; +} + +.auto-growing-textarea > textarea { + resize: none; + overflow: hidden; + /* Force the content in a single line */ + text-overflow: ellipsis; + white-space: nowrap; +} + +/* When editing a textarea, restore the multiline display */ +.auto-growing-textarea > textarea:focus { + text-overflow: unset; + white-space: unset; +} + +.auto-growing-textarea > textarea, +.auto-growing-textarea:focus-within::after { + grid-area: 1 / 1 / 2 / 2; + border: 0; + font-weight: normal; + min-width: 9ch; + padding: 4px; + padding-inline-start: 7px; + /* Adding this to have maximo 5 lines */ + max-height: 70px; + overflow-y: auto; +} + +.network-monitor .http-custom-method-and-url .http-custom-method-value, +.tabpanel-summary-container.http-custom-section .tabpanel-summary-input { + border: 0; +} + +.tabpanel-summary-container .http-custom-section .tabpanel-summary-input-value { + font-weight: normal; + min-width: 9ch; + padding: 4px; + padding-inline-start: 7px; +} + +.network-monitor .http-custom-method-and-url input ::placeholder { + color: var(--grey-50); + font-size: 11px; + line-height: 13px; + margin-inline-end: 8px; +} + +.network-monitor .tabpanel-summary-container .http-custom-request-label { + padding: 6px 13px; + font-size: 12px; + line-height: 14px; +} + +.network-monitor .http-custom-request-panel textarea { + color: var(--grey-50); + font-weight: normal; + font-size: 11px; + line-height: 13px; + direction: ltr; +} + +.network-monitor .http-custom-request-panel { + display: flex; + flex-direction: column; + height: 100%; +} + +.network-monitor .http-custom-request-panel .http-custom-request-panel-content { + flex: 1 1 auto; + height: auto; + overflow: auto; +} + +.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) { + position: relative; + display: flex; + flex-wrap: nowrap; + align-items: flex-start; + width: 100%; + overflow: hidden; + padding: 0px 13px; + padding-inline-end: 0; +} + +.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .tabpanel-summary-input-name { + width: 25%; + align-self: stretch; + min-width: min-content; +} + +.network-monitor .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .tabpanel-summary-input-value { + width: 75%; + align-self: stretch; +} + +.map-add-new-inputs { + padding-bottom: 2px; +} + +#http-custom-postdata-value.tabpanel-summary-input { + padding-inline-start: 14px; +} + +.http-custom-delete-button { + opacity: 0; + flex: none; + width: 20px; + height: 20px; + margin: 0; + padding: 2px; + border: none; + outline: none; + background-color: transparent; + position: absolute; + right: 0; +} + +.tabpanel-summary-container.http-custom-input .http-custom-delete-button::-moz-focus-inner { + border: none; +} + +.tabpanel-summary-container.http-custom-input:hover .http-custom-delete-button { + opacity: 1; +} + +.tabpanel-summary-container.http-custom-input .http-custom-delete-button::before { + content: ""; + display: block; + width: 16px; + height: 16px; + border-radius: 2px; + background: url("chrome://devtools/skin/images/close.svg") no-repeat center; + background-size: 12px; + -moz-context-properties: fill; + fill: var(--theme-icon-color); +} + +.tabpanel-summary-container.http-custom-input .http-custom-delete-button:hover::before { + fill: var(--theme-selection-color); + background-color: var(--theme-selection-background); +} + +.network-monitor .http-custom-request-button-container { + display: flex; + justify-content: end; + flex-wrap: wrap-reverse; + gap: 8px; + padding: 10px 16px; + border-block-start: 1px solid var(--theme-splitter-color); +} + +.network-monitor .http-custom-request-panel .http-custom-request-label { + font-weight: 400; + white-space: nowrap; +} + +.network-monitor .http-custom-request-button-container button { + height: 24px; + padding-inline: 8px; + width: auto; +} + +.network-monitor .http-custom-request-button-container button:focus { + box-shadow: 0 0 0 1px #0a84ff inset, 0 0 0 1px #0a84ff, + 0 0 0 4px rgba(10,132,255,0.3) +} + +.network-monitor .http-custom-request-button-container #http-custom-request-send-button { + background-color: var(--blue-60); + color: white; +} + +.network-monitor .http-custom-request-button-container #http-custom-request-send-button:active { + background-color: var(--blue-80); +} + +.network-monitor .http-custom-request-button-container #http-custom-request-send-button:hover { + background-color: var(--blue-70); +} + +.network-monitor .http-custom-header { + border-style: solid; + border-width: 0; + flex: none; + height: calc(var(--theme-toolbar-height) + 1px); + padding: 4px 16px; +} + +/* Dark theme */ +:root.theme-dark .network-details-bar .http-custom-request-panel { + background-color: var(--grey-85); +} + +:root.theme-dark .network-monitor .tabpanel-summary-container:is(.http-custom-method-and-url, .http-custom-section), +:root.theme-dark .network-monitor .tabpanel-summary-container .http-custom-request-label { + border-bottom: 1px solid var(--grey-60); +} + +:root.theme-dark .network-monitor .http-custom-method-and-url :is(.http-custom-method-value, .http-custom-url-value), +:root.theme-dark .network-monitor .tabpanel-summary-container .tabpanel-summary-input, +:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name, +:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value { + background-color: var(--grey-85); + color: white; +} + +:root.theme-dark .network-monitor .http-custom-method-and-url .http-custom-url-value, +:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) #http-custom-input-value { + border-inline-start: 1px solid var(--grey-60); +} + +:root.theme-dark .network-monitor .http-custom-method-and-url .http-custom-url-value:focus { + outline: 2px solid var(--blue-50); + width: calc(100% - 8px); +} + +:root.theme-dark .network-monitor .tabpanel-summary-container .tabpanel-summary-input:focus { + outline: 2px solid var(--blue-50); + margin-inline-start: 2px; + width: calc(100% - 5px); +} + +:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name:focus { + outline: 2px solid var(--blue-50); + margin-inline-end: 1px; +} + +:root.theme-dark .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value:focus { + outline: 2px solid var(--blue-50); + width: calc(100% - 20px); +} + +:root.theme-dark .http-custom-input-and-map-form .map-add-new-inputs .tabpanel-summary-input-value, +:root.theme-dark #http-custom-query .http-custom-input-and-map-form .tabpanel-summary-input-value:focus { + margin-inline-end: 1px; +} + +:root.theme-dark .network-monitor #http-custom-request-clear-button { + background-color: var(--toolbarbutton-background); + border: 1px solid var(--theme-splitter-color); +} + +:root.theme-dark .network-monitor #http-custom-request-clear-button:hover:active { + background-color: var(--theme-selection-background-hover); +} + +:root.theme-dark .network-monitor #http-custom-request-clear-button:focus { + background-color: var(--theme-selection-focus-background); +} + +:root.theme-dark .network-monitor .http-custom-request-label.http-custom-header { + background-color: var(--grey-80); + border-bottom: 1px solid var(--theme-splitter-color); +} + +:root.theme-dark .network-details-bar .http-custom-request-panel input, +:root.theme-dark .network-details-bar .http-custom-request-panel textarea { + background-color: var(--grey-70); + border: 1px solid var(--grey-85); + color: white; +} + +:root.theme-dark .network-monitor .http-custom-request-label { + color: var(--grey-40); +} + +/* Light theme */ +:root.theme-light .network-monitor .tabpanel-summary-container:is(.http-custom-method-and-url, .http-custom-section), +:root.theme-light .network-monitor .tabpanel-summary-container .http-custom-request-label { + border-bottom: 1px solid var(--grey-30); +} + +:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-method-value { + background-color: white; +} + +:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-url-value, +:root.theme-light .tabpanel-summary-container .tabpanel-summary-input-value { + border-inline-start: 1px solid var(--grey-30); +} + +:root.theme-light .network-monitor .http-custom-method-and-url .http-custom-url-value:focus { + outline: 2px solid var(--blue-50); + width: calc(100% - 8px); +} + +:root.theme-light .network-monitor .tabpanel-summary-container .tabpanel-summary-input:focus { + outline: 2px solid var(--blue-50); + margin-inline-start: 2px; + width: calc(100% - 5px); +} + +:root.theme-light .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-name:focus { + outline: 2px solid var(--blue-50); + margin-inline-end: 1px; +} + +:root.theme-light .http-custom-input-and-map-form :is(.http-custom-input, .map-add-new-inputs) .http-custom-input-value:focus { + outline: 2px solid var(--blue-50); + width: calc(100% - 20px); +} + +:root.theme-light .http-custom-input-and-map-form .map-add-new-inputs .tabpanel-summary-input-value:focus, +:root.theme-light #http-custom-query .http-custom-input-and-map-form .tabpanel-summary-input-value:focus { + margin-inline-end: 3px; +} + +:root.theme-light .network-monitor .tabpanel-summary-container .http-custom-request-label { + background-color: var(--grey-10); + color: var(--grey-90); +} + +:root.theme-light .network-details-bar .http-custom-request-label.http-custom-header { + background-color: var(--grey-10); + border-bottom: 1px solid var(--grey-25); +} + +:root.theme-light .network-monitor #http-custom-request-clear-button { + background-color: var(--grey-25); + border: var(--theme-splitter-color); +} + +:root.theme-light .network-monitor #http-custom-request-clear-button:hover:active { + background-color: var(--theme-selection-background-hover); +} + +:root.theme-light .network-monitor #http-custom-request-clear-button:focus { + outline: 2px solid var(--blue-50); + outline-offset: -2px; + box-shadow: 0 0 0 2px rgba(10, 132, 255, 0.3); + border-radius: 2px; +} + +:root.theme-light .network-details-bar .http-custom-request-panel input, +:root.theme-light .network-details-bar .http-custom-request-panel textarea { + background-color: white; + border: 1px solid var(--grey-25); + color: var(--grey-90); +} + +:root.theme-light .network-monitor .http-custom-request-label { + color: var(--grey-60); +} diff --git a/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css b/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css new file mode 100644 index 0000000000..f62ec166e1 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/HeadersPanel.css @@ -0,0 +1,210 @@ +/* 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/. */ + +/* Headers tabpanel */ + +.network-monitor .headers-panel-container { + height: 100%; + overflow: hidden; + position: relative; +} + +.network-monitor .headers-panel-container .treeTable { + overflow: hidden; +} + +.network-monitor .headers-panel-container .panel-container { + position: absolute; + top: calc(var(--theme-toolbar-height) + 1px); + bottom: 0; + right: 0; + left: 0; + height: auto; +} + +.network-monitor .headers-panel-container .devtools-button { + padding: 0; +} +.network-monitor .headers-panel-container .devtools-dropdown-button { + padding: 0; +} + +.network-monitor .headers-panel-container .devtools-button:is(#block-button, #edit-resend-button) { + height: 19px; + padding: 0 2px; +} + +.network-monitor .headers-panel-container .devtools-button:not(:hover) { + background-color: transparent; +} + +.network-monitor .headers-overview { + border-bottom: 1px solid var(--theme-splitter-color); +} + +.network-monitor .headers-overview .summary { + padding: 6px 16px 2px; +} + +.network-monitor .headers-summary, +.network-monitor .response-summary { + display: flex; + align-items: center; +} + +.network-monitor .raw-headers-toggle { + display: flex; + flex-direction: row; + flex-wrap: nowrap; + justify-content: flex-end; + align-items: center; + cursor: pointer; +} + +.network-monitor .raw-headers-toggle .headers-summary-label { + color: var(--theme-toolbar-color); +} + +.network-monitor .raw-headers-toggle-input > input { + display: inline-block; + width: 2em; + vertical-align: bottom; + font-size: 12px; +} + +.network-monitor .properties-view .tree-container .treeTable .treeValueCell .devtools-checkbox-toggle { + margin-block: 2px; +} + +.network-monitor .properties-view .raw-headers-container .raw-headers { + display: block; + overflow: hidden; + width: 100%; + padding: 2px 12px; + white-space: pre; + overflow-wrap: normal; + overflow-x: auto; + border: none; +} + +.network-monitor .accordion-item .treeTable .objectBox-string { + color: var(--theme-body-color); +} + +.network-monitor .accordion-item .treeTable tr.treeRow.selected .objectBox-string { + color: var(--theme-selection-color); +} + +.network-monitor .properties-view .raw-headers-container td { + display: block; +} + +.network-monitor .properties-view .raw-headers-container textarea { + width: 100%; + font-family: var(--monospace-font-family); + font-size: var(--theme-body-font-size); + resize: none; +} + +.theme-light .network-monitor .properties-view textarea { + background-color: white; + border: 1px solid var(--grey-25); + color: var(--grey-90); +} + +.theme-dark .network-monitor .properties-view textarea { + background-color: var(--grey-70); + border: 1px solid var(--grey-85); + color: white; +} + +.network-monitor .properties-view .raw-headers .tabpanel-summary-label { + padding: 0 0 4px; +} + +.headers-summary .textbox-input { + margin-inline-end: 2px; +} + +.network-monitor .headers-summary .status-text { + width: auto !important; + margin-inline-start: 4px; +} + +.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow { + padding: 1px 0 2px; +} +.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeLabelCell { + float: left; + margin-right: -33px; + margin-left: 5px; + padding: 0; + +} +.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeValueCell { + display: inline; + word-break: break-all; + box-decoration-break: clone; + padding-left: 39px; + padding-right: 20px; +} + +.network-monitor .headers-panel-container .accordion .properties-view tr.treeRow .treeValueCell div { + display: inline; +} + +/* Cookies */ + +.network-monitor .cookies-panel-container .accordion .properties-view tr.treeRow .treeLabelCell { + padding-inline-start: 0; +} + +/* Summary tabpanel */ + +.network-monitor .tabpanel-summary-container { + flex-wrap: wrap; + padding-inline-start: 4px; + margin-bottom: 5px; +} + +.network-monitor .tabpanel-summary-container .tracking-resource { + margin-inline: -2px 2px; + vertical-align: text-bottom; + fill: var(--theme-icon-color); +} + +.network-monitor .tabpanel-summary-label { + display: inline-block; + padding-inline-end: 3px; + min-width: 90px; + color: var(--theme-icon-dimmed-color); +} + +.network-monitor .tabpanel-summary-value { + color: inherit; + padding-inline-start: 3px; + unicode-bidi: plaintext; +} + +.network-monitor .tabpanel-summary-value strong { + margin-right: 3px; +} + +.theme-dark .network-monitor .tabpanel-summary-value { + color: var(--theme-selection-color); +} + +.network-monitor .tracking-protection { + color: var(--theme-icon-dimmed-color); + max-width: 200px; +} + +.network-monitor .tracking-protection .learn-more-link:not(:hover)::before { + color: var(--theme-icon-dimmed-color); +} + +.network-monitor .headers-summary-label, +.network-monitor .tree-container .objectBox { + white-space: nowrap; +} diff --git a/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css b/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css new file mode 100644 index 0000000000..a2d46ed522 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/NetworkActionBar.css @@ -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/. */ + + .network-monitor .network-action-bar { + width: 100%; + } + + .network-monitor .network-action-bar .tabs-menu-item { + width: 50%; + } diff --git a/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css b/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css new file mode 100644 index 0000000000..0f17d4cc64 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/NetworkDetailsBar.css @@ -0,0 +1,574 @@ +/* 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/. */ + +/* Network details panel */ + +.network-monitor .network-details-bar { + width: 100%; + height: 100%; + overflow: hidden; +} + +.network-monitor .panel-container { + height: 100%; + display: flex; + flex-direction: column; + overflow-x: hidden; + overflow-y: auto; +} + +.network-monitor .panel-container .tree-container .objectBox { + white-space: normal; + word-wrap: break-word; + unicode-bidi: plaintext; +} + +.network-monitor .properties-view { + display: flex; + flex-direction: column; + flex-grow: 1; + height: 100%; + overflow: auto; +} + +.network-monitor .properties-view .searchbox-section { + flex: 0 1 auto; +} + +.network-monitor .properties-view .devtools-searchbox { + padding: 0; +} + +.network-monitor .properties-view .devtools-searchbox input { + margin: 1px 3px; +} + +/* Empty notices in tab panels */ + +.network-monitor .empty-notice { + color: var(--theme-text-color-inactive); + padding: 3px 8px; + text-align: center; + display: flex; + align-items: center; + justify-content: center; + height: 100%; + font-size: 24px; +} + +/* Accordions in the tab panels */ + +.network-monitor .accordion-content .treeIcon { + margin-left: 16px; +} + +.network-monitor .accordion { + display: flex; + flex-direction: column; + flex-grow: 1; +} + +.network-monitor .accordion-item:last-child { + position: relative; + height: 100%; +} + +.network-monitor .accordion-item:last-child .accordion-header { + position: relative; +} + +.network-monitor .accordion-item:last-child .accordion-content { + position: relative; + top: 0; + bottom: 0; + left: 0; + right: 0; + overflow: inherit; +} + + +/* Text inputs in tab panels */ + +.network-monitor .textbox-input { + text-overflow: ellipsis; + border: none; + background: none; + color: inherit; + width: 100%; +} + +.network-monitor .textbox-input:focus { + outline: 0; + box-shadow: var(--theme-focus-box-shadow-textbox); +} + +/* Tree table in tab panels */ + +.network-monitor .tree-container, .tree-container .treeTable { + position: relative; + height: 100%; + width: 100%; + overflow: auto; + flex: 1; +} + +.network-monitor .tree-container .treeTable, +.network-monitor .tree-container .treeTable tbody { + display: flex; + flex-direction: column; +} + +.network-monitor .tree-container .treeTable tbody { + height: 100%; +} + +.network-monitor .tree-container .treeTable tr { + display: block; + position: relative; +} + +/* Make right td fill available horizontal space */ +.network-monitor .tree-container .treeTable td:last-child { + width: 100%; +} + +.network-monitor .tree-container .treeTable .tree-section, +.network-monitor .properties-view .raw-headers-container { + width: 100%; + background-color: var(--theme-toolbar-background); +} + +.network-monitor .tree-container .treeTable tr.tree-section:not(:first-child) td:not([class=""]) { + border-top: 1px solid var(--theme-splitter-color); +} + +.network-monitor .tree-container .treeTable tr.tree-section:not(:last-child) td:not([class=""]) { + border-bottom: 1px solid var(--theme-splitter-color); +} + +.network-monitor .tree-container .treeTable .tree-section > * { + vertical-align: middle; +} + +.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeLabelCell > .treeLabel, +.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeLabelCell > .treeLabel:hover, +.network-monitor .tree-container .treeTable .treeRow.tree-section > .treeValueCell:not(:hover) * { + color: var(--theme-toolbar-color); +} + +/* Force the twisty icon to gray even if the treeRow has the selected class */ +.network-monitor .tree-container .treeTable .treeRow.tree-section .theme-twisty { + fill: var(--theme-icon-dimmed-color); +} + +/* Make the twisties rotate to the right in code-only sections on RTL. */ +.network-monitor .tab-panel.panel-with-code tr:not(.tree-section).hasChildren .theme-twisty:not(.open):dir(rtl) { + transform: rotate(-90deg); +} + +.network-monitor .tree-container .treeTable .treeValueCell { + /* FIXME: Make value cell can be reduced to shorter width */ + max-width: 0; + padding-inline-end: 5px; +} + +.network-monitor .tree-container .treeTable .treeRow.hasChildren > .treeLabelCell > .treeLabel:hover { + text-decoration: none; +} + +.network-monitor .tab-panel.panel-with-code .tree-container .treeTable tr:not(.tree-section):dir(rtl) { + direction: ltr; + text-align: left; +} + +/* Source editor in tab panels */ + +/* If there is a source editor shows up in the last row of TreeView, + * it should occupy the available vertical space. + */ +.network-monitor .editor-row-container, +.network-monitor .tree-container .treeTable tr:last-child td[colspan="2"] { + display: block; + height: 100%; + flex: 1; + overflow-x: auto; +} + +.network-monitor .responseTextContainer { + overflow-x: auto; + width: 100%; + height: 100%; + padding-left: 5px; +} + +/* If there is a source editor shows up in the last row of TreeView, + * its height should not collapse into zero + */ +.network-monitor .tree-container .treeTable tr:last-child.editor-row-container { + overflow: visible; +} + +.network-monitor .source-editor-mount { + width: 100%; + height: 100%; +} + +.network-monitor .headers-summary-label, +.network-monitor .tree-container .objectBox { + white-space: nowrap; +} + +/* Params and Response error messages */ + +.network-monitor .request-error-header, +.network-monitor .response-error-header { + margin: 0; + padding: 4px 8px; + border-bottom: 1px solid var(--theme-splitter-color); + background-color: var(--red-60); + color: white; + line-height: 16px; +} + +.theme-dark .network-monitor .request-error-header, +.theme-dark .network-monitor .response-error-header { + background-color: var(--red-70); +} + +/* Response tabpanel */ + +.network-monitor .response-image-box { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + overflow-y: auto; + padding: 10px; +} + +.network-monitor .response-image { + background: #fff; + border: 1px dashed GrayText; + margin-bottom: 10px; + max-width: 300px; + max-height: 100px; +} + +.network-monitor #response-panel .response-font-box { + overflow-y: auto; + padding: 10px; + display: flex; + flex-direction: column; + justify-content: center; +} + +.network-monitor .response-font { + margin-bottom: 10px; + width: 100%; + height: 100%; + object-fit: contain; +} + +.network-monitor .tree-container .treeTable tr.response-preview-container { + flex: 1; + min-height: 0; +} + +.network-monitor .tree-container .treeTable tr.response-preview-container td { + display: block; + height: 100%; +} + +.network-monitor .html-preview { + height: 100%; +} + +.network-monitor .html-preview iframe { + background-color: #fff; + border: none; + height: 100%; + width: 100%; +} + +/* The editor container should only become a flex item when inside a container + * with other flex items. In this case, the HTML preview is a flex item and we + * can grow the editor. Otherwise, there may be overflow and + * .editor-row-container will become 0px tall. */ +.network-monitor .contains-html-preview .editor-row-container { + flex: 1; + min-height: 0; +} + +/* Request and response data */ + +.network-monitor #response-panel .panel-container { + overflow-y: hidden; +} + +.network-monitor .data-header { + background: var(--theme-toolbar-background); + border-bottom: 1px solid var(--theme-splitter-color); + color: var(--theme-toolbar-color); + font-size: inherit; + font-weight: normal; + line-height: 16px; + margin: 0; + padding: 2px 4px; + width: 100%; + align-items: center; + display: flex; + user-select: none; +} + +.network-monitor .data-label { + display: block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: inherit; + line-height: 20px; + color: var(--theme-toolbar-color); +} + +.network-monitor .raw-data-toggle { + flex: none; + display: flex; + align-items: center; + justify-content: flex-end; + max-width: 50%; + margin-inline-start: auto; + padding-inline-start: 4px; +} + +.network-monitor .raw-data-toggle-label { + white-space: nowrap; + color: var(--theme-toolbar-color); +} + +.network-monitor .raw-data-toggle-input > input { + display: inline-block; + width: 2em; + vertical-align: bottom; + font-size: 12px; +} + +.network-monitor #response-panel .notificationbox .notification[data-key="CORS-error"].notification[data-type="info"] { + background-color: var(--theme-body-alternate-emphasized-background); +} + +.network-monitor #response-panel .notification[data-key="CORS-error"] .notificationInner .messageText { + white-space: normal; + padding-top: 8px; + padding-bottom: 8px; +} + +/* Timings tabpanel */ + +.network-monitor .timings-container { + display: flex; +} + +.network-monitor .timings-overview { + display: flex; + border-bottom: 1px solid var(--theme-splitter-color); + padding: 4px; +} + +.network-monitor .timings-overview-item { + display: inline-flex; +} + +.network-monitor .timings-overview-item:not(:first-of-type)::before { + content: ""; + display: inline-flex; + margin-inline: 10px; + width: 1px; + background: var(--theme-splitter-color); +} + +.network-monitor .timings-label { + width: 10em; +} + +.network-monitor .requests-list-timings-container { + display: flex; + flex: 1; + align-items: center; +} + +.network-monitor .requests-list-timings-offset { + transition: width 0.2s ease-out; +} + +.network-monitor .requests-list-timings-box { + border: none; + min-width: 1px; + transition: width 0.2s ease-out; +} + +.network-monitor .label-separator { + margin-block: 5px; + margin-inline-start: 4px; + font-weight: 600; + color: var(--theme-comment); +} + +.theme-light .network-monitor .requests-list-timings-box { + --timing-server-color-1: rgba(104, 195, 179, 0.8); /* teal */ + --timing-server-color-2: rgba(123, 102, 167, 0.8); /* purple */ + --timing-server-color-3: rgba(233, 236, 130, 0.8); /* yellow */ + --timing-server-color-total: rgba(186, 90, 140, 0.8); /* pink */ +} + +.theme-dark .network-monitor .requests-list-timings-box { + --timing-server-color-1: rgba(74, 228, 201, 0.8); /* teal */ + --timing-server-color-2: rgba(156, 119, 233, 0.8); /* purple */ + --timing-server-color-3: rgba(234, 239, 73, 0.8); /* yellow */ + --timing-server-color-total: rgba(186, 74, 133, 0.8); /* pink */ +} + +.network-monitor .server-timings-color-1 { + background: var(--timing-server-color-1); +} + +.network-monitor .server-timings-color-2 { + background: var(--timing-server-color-2); +} + +.network-monitor .server-timings-color-3 { + background: var(--timing-server-color-3); +} + +.network-monitor .server-timings-color-total { + background: var(--timing-server-color-total); +} + + +/* Stack trace panel */ + +.network-monitor .stack-trace { + font-family: var(--monospace-font-family); + /* The markup contains extra whitespace to improve formatting of clipboard text. + Make sure this whitespace doesn't affect the HTML rendering */ + white-space: normal; + padding: 5px; + direction: ltr; +} + +.network-monitor .stack-trace .frame-link-source { + /* Makes the file name truncated (and ellipsis shown) on the left side */ + direction: rtl; + unicode-bidi: embed; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: end; +} + +.network-monitor .stack-trace .frame-link-function-display-name { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-inline-end: 1ch; +} + +/* Security tabpanel */ + +/* Overwrite tree-view cell colon `:` for security panel and tree section */ +.network-monitor .security-panel .treeTable .treeLabelCell::after, +.network-monitor .treeTable .tree-section .treeLabelCell::after { + content: ""; +} + +/* Layout additional warning icon in tree value cell */ +.network-monitor .security-info-value { + display: flex; +} + +.network-monitor .security-warning-icon { + width: 12px; + height: 12px; + vertical-align: -1px; + margin-inline-start: 5px; + background-image: url(chrome://devtools/skin/images/alert-small.svg); + background-size: cover; + -moz-context-properties: fill; + fill: var(--yellow-60); +} + +/* Custom request panel */ + +.network-monitor .custom-request-panel, .http-custom-request-panel { + height: 100%; + background-color: var(--theme-sidebar-background); +} + +.theme-dark .network-monitor .custom-request-panel, .http-custom-request-panel { + color: var(--theme-selection-color); +} + +.network-monitor .custom-request-label { + font-weight: 600; +} + +.network-monitor .custom-request-panel, .http-custom-request-panel textarea { + resize: none; + font: message-box; + font-size: var(--theme-body-font-size); +} + +.network-monitor .custom-header, +.network-monitor .custom-method-and-url, +.network-monitor .custom-request, +.network-monitor .custom-section, +.network-monitor .http-custom-header, +.network-monitor .http-custom-method-and-url, +.network-monitor .http-custom-request, +.network-monitor .http-custom-section { + display: flex; +} + +.network-monitor .custom-header, +.network-monitor .http-custom-header { + flex-grow: 1; + font-size: 1.1em; + padding-top: 4px; +} + +.network-monitor .custom-section { + flex-direction: column; + margin-top: 0.5em; +} + +.network-monitor .http-custom-section { + flex-direction: column; +} + +.network-monitor .custom-method-value { + width: 4.5em; +} + +.network-monitor .http-custom-method-value{ + width: 6.0em; +} + +.network-monitor .custom-url-value, +.network-monitor .http-custom-url-value { + flex-grow: 1; + margin-inline-start: 6px; +} + +.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"] { + background-color: var(--theme-body-alternate-emphasized-background); +} + +.network-monitor #response-panel .notification[data-key="xssi-string-removed-info-box"] .notificationInner .messageText { + white-space: normal; + padding-top: 8px; + padding-bottom: 8px; +} + +#timings-panel .learn-more-link { + width: -moz-max-content; +} diff --git a/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css b/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css new file mode 100644 index 0000000000..3675dd5f22 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/RequestBlockingPanel.css @@ -0,0 +1,184 @@ +/* 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/. */ + +.request-blocking-panel { + position: relative; + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; +} + +/* Override the devtools-checkbox style to improve hit area and alignment */ +.request-blocking-panel .devtools-checkbox-label { + display: inline-flex; + align-items: center; + gap: 4px; + margin: 0; + padding: 2px 4px; + /* checkbox can be 13px, 14px or 16px depending on the platform */ + line-height: 16px; + user-select: none; + cursor: default; +} + +.request-blocking-panel .devtools-checkbox-label > input { + flex: none; + margin: 0; +} + +.request-blocking-label { + flex: 1 1 auto; + display: block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.request-blocking-editable-label { + cursor: text +} + +/* The "Enable Blocking Requests" bar */ +.request-blocking-enable-bar { + flex: none; + background: var(--theme-tab-toolbar-background); + height: calc(var(--theme-toolbar-height) + 1px); + padding-block: 2px; + padding-inline: 16px 4px; + align-items: center; + overflow: hidden; + white-space: nowrap; + border-bottom: 1px solid var(--theme-splitter-color); +} + +.request-blocking-enable-form { + flex-grow: 1; +} + +.request-blocking-contents { + flex: 0 1 auto; + overflow-y: auto; + border-bottom: 1px solid var(--theme-splitter-color); +} + +/* Blocked request list */ +.request-blocking-list { + margin: 0; + padding: 4px 0; +} + +.request-blocking-list.disabled { + background-color: var(--theme-toolbar-hover); + opacity: 0.6; +} + +.request-blocking-list li { + display: flex; + align-items: center; + min-height: 20px; + padding-inline: 16px 8px; +} + +.request-blocking-list li.request-blocking-edit-item { + padding: 0; + /* Text input is 24px but we want it to occupy the same space as our 20px rows */ + margin-block: -2px; +} + +.request-blocking-list li.request-blocking-edit-item form { + width: 100%; +} + +.request-blocking-list .devtools-checkbox-label { + flex: 1 1 auto; + /* Can't seem to make the flex-shrink reduce the element's width when the + content is a long URL, even if the URL container has text-overflow: ellipsis. + DevTools shows that "the item was clamped to its minimum size" and the shrink + part is thus ignored. So we're reserving 20px for the delete button. */ + max-width: calc(100% - 20px); +} + +.request-blocking-remove-button { + /* Visually hide but stay focusable in keyboard navigation */ + opacity: 0; + flex: none; + width: 20px; + height: 20px; + margin: 0; + padding: 2px; + border: none; + outline: none; + background-color: transparent; +} + +.request-blocking-remove-button::-moz-focus-inner { + border: none; +} + +.request-blocking-list li:hover .request-blocking-remove-button { + opacity: 1; +} + +.request-blocking-remove-button::before { + content: ""; + display: block; + width: 16px; + height: 16px; + border-radius: 2px; + background: url("chrome://devtools/skin/images/close.svg") no-repeat center; + background-size: 12px; + -moz-context-properties: fill; + fill: var(--theme-icon-color); +} + +.request-blocking-remove-button:hover::before { + fill: var(--theme-selection-color); + background-color: var(--theme-selection-background); +} + +/* Footer content, progressively pushed by pattern rows in the main list and + * remaining "fixed" at the bottom when there is enough content to scroll, + * thanks to the magic of flexbox */ +.request-blocking-footer { + position: relative; + flex: none; +} + +/* Draw a border 1px below the form, so that it disappears out of view when + * there are many pattern rows in the main container and the footer is pushed + * to the bottom */ +.request-blocking-footer::after { + content: ""; + position: absolute; + left: 0; + right: 0; + top: 100%; + border-bottom: 1px solid var(--theme-splitter-color); +} + +/* Text input for the addition and edition forms */ +.request-blocking-add-form input, +.request-blocking-edit-item input { + width: calc(100% - 1px); + height: 24px; + padding-block: 4px; + padding-inline: 20px 8px; + background: none; +} + +.request-blocking-list-empty-notice { + margin: 0; + flex: 1; + overflow-x: hidden; +} + +.request-blocking-notice-element { + padding-top: 12px; + padding-inline: 12px; +} + +.request-blocking-notice-element::before { + content:"• "; +} diff --git a/devtools/client/netmonitor/src/assets/styles/RequestList.css b/devtools/client/netmonitor/src/assets/styles/RequestList.css new file mode 100644 index 0000000000..3d1b77fdef --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/RequestList.css @@ -0,0 +1,653 @@ +/* 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/. */ + +/* Request list empty panel */ + +.request-list-empty-notice { + margin: 0; + flex: 1; + overflow-x: hidden; +} + +.empty-notice-element { + padding-top: 12px; + padding-inline: 12px; + font-size: 1.2rem; +} + +.notice-perf-message { + margin-top: 2px; + align-items: center; +} + +.requests-list-perf-notice-button { + min-width: 30px; + min-height: 26px; + margin: 0 5px; + vertical-align: middle; +} + +.requests-list-perf-notice-button::before { + background-image: url(chrome://devtools/skin/images/profiler-stopwatch.svg); +} + +.requests-list-slow-button { + width: 12px; + height: 12px; + position: absolute; + right: 0; + transform: translateY(-50%); + top: 50%; + cursor: pointer; + background-image: linear-gradient(to right,transparent, var(--theme-body-background) 43%); + padding-inline-end: 30px; + padding-inline-start: 5px; +} + +.request-list-item:not(.selected).odd .requests-list-slow-button { + background-image: linear-gradient(to right,transparent, var(--table-zebra-inline-icons-background) 43%); +} + +.request-list-item:not(.selected):hover .requests-list-slow-button, +.request-list-item:not(.selected).odd:hover .requests-list-slow-button { + background-image: linear-gradient(to right,transparent, var(--table-selection-inline-icons-background-hover) 43%); +} + +.request-list-item.selected .requests-list-slow-button { + background-image: linear-gradient(to right,transparent, var(--theme-selection-background) 43%); +} + +.requests-list-slow-button::before { + content: ""; + width: 12px; + height: 16px; + display: inline-block; + background-image: url(chrome://devtools/content/netmonitor/src/assets/icons/turtle.svg); + background-repeat: no-repeat; + background-position-x: right; + padding-inline-end: 14px; + fill: var(--grey-40); + -moz-context-properties: fill; +} + +.request-list-item.selected .requests-list-slow-button::before { + fill: currentColor; +} + +.requests-list-reload-notice-button { + font-size: inherit; + min-height: 26px; + margin: 0 5px; +} + +/* Requests list table */ + +.request-list-container { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + overflow: hidden; + color: var(--theme-body-color); +} + +.requests-list-scroll { + overflow-x: hidden; + overflow-y: auto; + width: 100% !important; +} + +.requests-list-scroll table { + /* Disable overflow-anchor for only child in the scrollable element */ + overflow-anchor: none; +} + +.requests-list-anchor { + overflow-anchor: auto; + opacity: 0; + height: 1px; +} + +.requests-list-table, +.message-list-table { + /* Reset default browser style of */ + border-spacing: 0; + width: 100%; + /* The layout must be fixed for resizing of columns to work. + The layout is based on the first row. + Set the width of those cells, and the rest of the table follows. */ + table-layout: fixed; +} + +.requests-list-table { + /* Clip column resizers when they are higher than the table. */ + overflow: hidden; +} + +.requests-list-column, +.message-list-column { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + vertical-align: middle; + /* Reset default browser style of
*/ + padding: 0; + /* Prevent text selection because it's often invisible (blue on blue), + * it conflicts easily with existing click and double-click actions, + * and we already have several Copy and Export options. */ + user-select: none; +} + +.requests-list-column { + position: relative; +} + +.requests-list-column > * { + display: inline-block; +} + +/* Requests list headers */ + +.requests-list-headers-group, +.message-list-headers-group { + position: sticky; + top: 0; + left: 0; + width: 100%; + z-index: 1; +} + +.requests-list-headers, +.message-list-headers { + padding: 0; + color: var(--theme-body-color); + background-color: var(--theme-toolbar-background); +} + +.requests-list-headers th, +.message-list-headers th { + height: calc(var(--theme-toolbar-height) + 1px); + border-bottom: 1px solid var(--theme-splitter-color); +} + +.requests-list-headers th { + /* Allow column-resizers to be visible beyond the headers. */ + overflow: visible; +} + +.requests-list-headers th:not(:first-child), +.message-list-headers th:not(:first-child) { + border-inline-start: 1px solid var(--theme-splitter-color); +} + +.requests-list-header-button, +.message-list-header-button { + width: 100%; + min-height: var(--theme-toolbar-height); + border-width: 0; + padding-block: 1px; + padding-inline-start: 5px; + padding-inline-end: 4px; + text-align: start; + color: inherit; + background-color: transparent; +} + +.requests-list-header-button::-moz-focus-inner, +.message-list-header-button::-moz-focus-inner { + border: 0; + padding: 0; +} + +.requests-list-header-button:hover { + background-color: rgba(0, 0, 0, 0.1); +} + +.requests-list-header-button > .button-text, +.message-list-header-button > .button-text { + display: inline-block; + vertical-align: middle; + width: 100%; + overflow: hidden; + text-overflow: ellipsis; +} + +.requests-list-header-button > .button-icon, +.message-list-header-button > .button-icon { + /* display icon only when column sorted otherwise display:none */ + display: none; + width: 7px; + height: 4px; + margin-inline: 3px 6px; + vertical-align: middle; +} + +.requests-list-header-button[data-sorted] > .button-icon { + /* display icon only when column sorted */ + display: inline-block; +} + +.requests-list-header-button[data-sorted] > .button-text { + /* when sorted - adjust width to fit the icon inside the button */ + width: calc(100% - 11px); +} + +.requests-list-header-button[data-sorted=ascending] > .button-icon { + background-image: url("chrome://devtools/skin/images/sort-ascending-arrow.svg"); +} + +.requests-list-header-button[data-sorted=descending] > .button-icon { + background-image: url("chrome://devtools/skin/images/sort-descending-arrow.svg"); +} + +.requests-list-header-button[data-sorted], +.requests-list-header-button[data-sorted]:hover { + background-color: var(--theme-selection-background); + color: var(--theme-selection-color); +} + +.requests-list-header-button[data-sorted], +.requests-list-column[data-active] + .requests-list-column .requests-list-header-button { + border-image: linear-gradient(var(--theme-splitter-color), var(--theme-splitter-color)) 1 1; +} + +/* Requests list headers column-resizer */ + +.requests-list-headers .column-resizer { + z-index: 1000; + cursor: ew-resize; + margin-inline-start: -3px; + width: 7px; + min-height: 23px; + position: absolute; + background-color: transparent; + /* Extend column-resizers beyond table header to allow resizing on + * column borders as well.*/ + height: 100vh; +} + +/** + * Make sure headers are not processing any mouse + * events. This is good for performance during dragging. + */ +.requests-list-headers.dragging { + pointer-events: none; +} + +/* Requests list column */ + +/* Status column */ + +.requests-list-status { + /* Don't ellipsize status codes */ + text-overflow: initial; +} + +.requests-list-status-code.status-code-blocked { + /* Improve the icon's vertical alignment by matching the row height. */ + display: inline-flex; + vertical-align: top; + align-items: center; + justify-content: center; + height: 24px; +} + +.requests-security-icon-group { + display: inline-flex; + vertical-align: top; + align-items: center; + height: 24px; + /* Icons are drawn as backgrounds on a 16x16 element but are often smaller + * (e.g. 12x12). Shift them a few pixels to align with the header text. */ + margin-inline-start: -3px; + margin-inline-end: 2px; +} + +.requests-security-state-icon { + display: inline-block; + height: 16px; + background-position: center; + background-repeat: no-repeat; + -moz-context-properties: fill, stroke; + fill: var(--theme-icon-dimmed-color); + stroke: var(--theme-icon-color); +} + +.security-state-secure { + background-image: url(chrome://devtools/skin/images/security-state-secure.svg); + width: 16px; +} + +.security-state-weak { + /* Shift icon to the right (in both LTR and RTL directions) to align the + * padlock shape with other padlock icons. */ + position: relative; + width: 16px; + left: 2px; + background-image: url(chrome://devtools/skin/images/security-state-weak.svg); + stroke: var(--theme-icon-warning-color); +} + +.security-state-insecure { + background-image: url(chrome://devtools/skin/images/security-state-insecure.svg); + width: 16px; + stroke: var(--theme-icon-error-color); +} + +.security-state-broken { + background-image: url(chrome://devtools/skin/images/error-small.svg); + width: 16px; + fill: var(--theme-icon-error-color); +} + +.tracking-resource { + display: inline-block; + width: 16px; + height: 16px; + background-image: url(chrome://devtools/content/netmonitor/src/assets/icons/shield.svg); + background-repeat: no-repeat; + -moz-context-properties: fill; + fill: var(--theme-icon-dimmed-color); +} + +.request-list-item.selected .status-code-blocked, +.request-list-item.selected .requests-security-state-icon, +.request-list-item.selected .tracking-resource { + fill: currentColor; + stroke: currentColor; + color: var(--theme-selection-color); +} + +.theme-dark .request-list-item.selected .status-code-blocked, +.theme-dark .request-list-item.selected .requests-security-state-icon, +.theme-dark .request-list-item.selected .tracking-resource { + color: rgba(255, 255, 255, 0.75); +} + +.request-list-item .requests-list-column, +.message-list-item .message-list-column { + padding-inline-start: 5px; + /* Column text should not touch the next column's border. + We could use a 5px space to be symmetrical, but we're using + text-overflow:ellipsis which makes that padding look wider in most cases, + and a smaller padding saves space for content. */ + padding-inline-end: 4px; +} + +.request-list-item .requests-list-column:not(:first-child), +.message-list-item .message-list-column:not(:first-child) { + border-inline-start: 1px solid var(--table-splitter-color); +} + +.request-list-item:hover .requests-list-column, +.request-list-item.selected .requests-list-column, +.message-list-item:hover .message-list-column, +.message-list-item.selected .message-list-column { + border-inline-start-color: transparent; +} + +.request-list-item .requests-list-waterfall { + padding-inline-start: 0; +} + +.requests-list-cause-stack { + display: inline-block; + background-color: var(--theme-text-color-alt); + color: var(--theme-body-background); + font-size: 8px; + font-weight: bold; + line-height: 10px; + border-radius: 3px; + padding: 0 2px; + margin: 0; + margin-inline-end: 3px; +} + +/* Waterfall column */ + +.requests-list-waterfall { + background-repeat: repeat-y; + background-position: left center; + overflow: visible; + /* Background created on a in js. */ + /* @see devtools/client/netmonitor/src/widgets/WaterfallBackground.js */ + background-image: -moz-element(#waterfall-background); +} + +.requests-list-waterfall:dir(rtl) { + background-position: right center; +} + +.requests-list-waterfall > .requests-list-header-button { + padding: 0; +} + +.requests-list-waterfall > .requests-list-header-button > .button-text { + width: auto; +} + +.requests-list-waterfall-label-wrapper:not(.requests-list-waterfall-visible) { + padding-inline-start: 16px; +} + +.requests-list-timings-division { + display: inline-block; + padding-inline-start: 4px; + font-size: 75%; + pointer-events: none; + text-align: start; +} + +:root[platform="win"] .requests-list-timings-division { + padding-top: 1px; + font-size: 90%; +} + +.requests-list-timings-division:not(:first-child) { + border-inline-start: 1px dashed; +} + +.requests-list-timings-division:dir(ltr) { + transform-origin: left center; +} + +.requests-list-timings-division:dir(rtl) { + transform-origin: right center; +} + +.theme-dark .requests-list-timings-division { + border-inline-start-color: #5a6169 !important; +} + +.theme-light .requests-list-timings-division { + border-inline-start-color: #585959 !important; +} + +.requests-list-timings-division[data-division-scale=second], +.requests-list-timings-division[data-division-scale=minute] { + font-weight: 600; +} + +.requests-list-timings { + display: flex; + align-items: center; +} + +.requests-list-timings:dir(ltr) { + transform-origin: left center; +} + +.requests-list-timings:dir(rtl) { + transform-origin: right center; +} + +.requests-list-timings-box { + display: inline-block; + height: 12px; +} + +.requests-list-timings-box.filler { + background-color: var(--theme-splitter-color); +} + +.requests-list-timings-box.blocked { + background-color: var(--timing-blocked-color); +} + +.requests-list-timings-box.dns { + background-color: var(--timing-dns-color); +} + +.requests-list-timings-box.connect { + background-color: var(--timing-connect-color); +} + +.requests-list-timings-box.ssl { + background-color: var(--timing-ssl-color); +} + +.requests-list-timings-box.send { + background-color: var(--timing-send-color); +} + +.requests-list-timings-box.wait { + background-color: var(--timing-wait-color); +} + +.requests-list-timings-box.receive { + background-color: var(--timing-receive-color); +} + +.requests-list-timings-total { + display: inline-block; + padding-inline-start: 4px; + font-size: 80%; + font-weight: 600; + white-space: nowrap; + text-align: left; +} + +.requests-list-timings-total:dir(ltr) { + transform-origin: left center; +} + +.requests-list-timings-total:dir(rtl) { + transform-origin: right center; +} + +/* Request list item */ + +.request-list-item, +.message-list-item { + height: 24px; + line-height: 24px; +} + +.request-list-item:not(.selected).odd, +.message-list-item:not(.selected).odd { + background-color: var(--table-zebra-background); +} + +.request-list-item:not(.selected):hover, +.message-list-item:not(.selected):hover { + background-color: var(--table-selection-background-hover); +} + +/* + * Dim requests served from cache + */ +.request-list-item:not(.selected, :hover).fromCache { + --table-icon-opacity: 0.7; + color: var(--theme-text-color-alt); +} + +/* + * Apply partial opacity to specific icons and icon-like elements + * (e.g. for cached requests) + */ +.requests-security-icon-group, +.requests-list-status-code:not([data-code^="3"]) { + opacity: var(--table-icon-opacity, 1); +} + +/* + * Showing blocked requests in red should always have priority + * except when the request is selected. + */ +.request-list-item:not(.selected).blocked { + color: var(--timing-blocked-color) !important; +} + +/* + * Put after .request-list-item.blocked to avoid specificity conflict. + * Bug 1530914 - Highlighted Security Value is difficult to read. + */ +.request-list-item.selected, +.message-list-item.selected { + background-color: var(--theme-selection-background); + color: var(--theme-selection-color); + /* Rows have tabindex=0 and get a default outline when clicked, but we already + * have a visible selection style so hiding the outline should be okay. */ + outline: none; +} + +.theme-light { + --network-initiator-line-color: var(--theme-highlight-blue); + --network-initiator-color: var(--theme-highlight-purple); +} + +.theme-dark { + --network-initiator-line-color: hsl(210, 40%, 60%); + --network-initiator-color: var(--blue-40); +} + +.requests-list-initiator .requests-list-initiator-lastframe { + text-decoration: underline; + text-decoration-skip-ink: none; +} + +.requests-list-initiator-lastframe { + display: unset; +} + +.request-list-item .requests-list-initiator-filename, +.request-list-item .requests-list-initiator-line { + cursor: pointer; + text-decoration: inherit; +} + +.request-list-item:not(.selected) .requests-list-initiator-filename { + color: var(--network-initiator-color); +} + +.request-list-item:not(selected) .requests-list-initiator-line { + color: var(--network-initiator-line-color); +} + +.request-list-item.selected .requests-list-initiator-filename, +.request-list-item.selected .requests-list-initiator-line { + color: inherit; +} + +.request-list-item .requests-list-initiator-cause { + display: unset; + white-space: pre; +} + +/* Responsive web design support */ + +@media (max-width: 700px) { + .requests-list-status-code { + width: auto; + } + + .requests-list-size { + /* Given a fix max-width to display all columns in RWD mode */ + max-width: 7%; + } + + .requests-list-waterfall { + display: none; + } +} diff --git a/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css b/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css new file mode 100644 index 0000000000..a0767097c3 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/StatisticsPanel.css @@ -0,0 +1,171 @@ +/* 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/. */ + +/* Statistics panel */ + +@import "chrome://devtools/skin/chart.css"; + +.statistics-panel { + display: flex; + height: 100vh; + overflow: auto; +} + +.statistics-panel .back-button { + height: -moz-fit-content; + position: absolute; + padding: 7px 5px; + margin: 0px; + top: 8px; + inset-inline-start: 8px; +} + +.theme-light .statistics-panel .back-button { + background-color: var(--grey-20); +} + +.statistics-panel .splitter { + border-color: var(--theme-splitter-color); + cursor: default; + pointer-events: none; + height: 100%; +} + +.statistics-panel .charts-container { + display: flex; + width: 100%; +} + +.statistics-panel .charts, +.statistics-panel .pie-table-chart-container { + width: 100%; + height: 100%; + margin-bottom: 1rem; +} + +.statistics-panel .learn-more-link { + font-weight: 400; +} + +.statistics-panel .table-chart-title { + display: flex; + align-items: center; +} + +.pie-table-chart-container { + display: flex; + justify-content: center; + align-items: center; +} + +.statistics-panel .pie-chart-container { + margin-inline-start: 3vw; + margin-inline-end: 1vw; +} + +.statistics-panel .table-chart-container { + min-width: 240px; + margin-inline-start: 1vw; + margin-inline-end: 3vw; +} + +tr[data-statistic-name] td:first-of-type { + border-inline-start: 15px solid var(--stat-color); +} + +path[data-statistic-name] { + fill: var(--stat-color); +} + +[data-statistic-name=html] { + --stat-color: var(--theme-highlight-bluegrey); +} + +[data-statistic-name=css] { + --stat-color: var(--theme-highlight-blue); +} + +[data-statistic-name=js] { + --stat-color: var(--theme-highlight-lightorange); +} + +[data-statistic-name=xhr] { + --stat-color: var(--theme-highlight-orange); +} + +[data-statistic-name=fonts] { + --stat-color: var(--theme-highlight-purple); +} + +[data-statistic-name=images] { + --stat-color: var(--theme-highlight-pink); +} + +[data-statistic-name=media] { + --stat-color: var(--theme-highlight-green); +} + +/* + * Align cell text to the center by default. + */ +.table-chart-row-label { + text-align: center; +} + +.table-chart-row-label[name=count] { + width: 3em; + text-align: end; +} + +.table-chart-row-label[name=label] { + width: 7em; + text-align: start; +} + +.table-chart-row-label[name=size] { + width: 7em; + text-align: start; +} + +.table-chart-row-label[name=time] { + width: 7em; + text-align: start; +} + +.table-chart-totals { + display: flex; + flex-direction: column; +} + +/* Responsive web design support */ + +@media (max-width: 700px) { + .statistics-panel .charts-container { + flex-direction: column; + /* Minus 4em for statistics back button width */ + width: calc(100% - 4em); + } + + .statistics-panel .splitter { + width: 100%; + height: 1px; + } + + .statistics-panel .table-chart-title { + margin-top: 3rem; + } + + .statistics-panel .charts, + .statistics-panel .pie-table-chart-container{ + margin-bottom: 2rem; + } +} + +.offscreen{ + position: absolute!important; + font-size: 0px; + overflow: hidden; + clip: rect(1px,1px,1px,1px); + clip-path: polygon(0 0,0 0,0 0,0 0); +} diff --git a/devtools/client/netmonitor/src/assets/styles/StatusBar.css b/devtools/client/netmonitor/src/assets/styles/StatusBar.css new file mode 100644 index 0000000000..ff53a0d866 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/StatusBar.css @@ -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/. */ + +/* Status bar */ + +.devtools-status-bar-label { + flex: 0; +} + +.status-bar-label { + display: inline-flex; + margin-inline-end: 10px; + /* Status bar has just one line so, don't wrap labels */ + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.status-bar-label:not(:first-of-type)::before { + content: ""; + display: inline-block; + margin-inline-end: 10px; + margin-top: 4px; + margin-bottom: 4px; + width: 1px; + background: var(--theme-splitter-color); +} + +.status-bar-label.dom-content-loaded { + color: var(--theme-highlight-blue); +} + +.status-bar-label.load { + color: var(--theme-highlight-red); +} + +.requests-list-network-summary-button { + display: inline-flex; + align-items: center; + cursor: pointer; + height: 20px; + background: none; + box-shadow: none; + border-color: transparent; + padding-inline-end: 0; + margin-top: 3px; + margin-bottom: 3px; + margin-inline-end: 1em; +} + +.requests-list-network-summary-button > .summary-info-icon { + background: url(chrome://devtools/skin/images/profiler-stopwatch.svg) no-repeat; + -moz-context-properties: fill; + fill: var(--theme-toolbar-color); + width: 16px; + height: 16px; + opacity: 0.8; +} + +.requests-list-network-summary-button:hover > .summary-info-icon { + opacity: 1; +} diff --git a/devtools/client/netmonitor/src/assets/styles/StatusCode.css b/devtools/client/netmonitor/src/assets/styles/StatusCode.css new file mode 100644 index 0000000000..5b69d6f72b --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/StatusCode.css @@ -0,0 +1,100 @@ +/* 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/. */ + +.status-code { + /* non-standard codes may be shorter than 3 characters but should match + width of standard codes */ + min-width: calc(3ch + 4px); + padding: 0 2px; + border-radius: 3px; + text-align: center; + font-family: var(--monospace-font-family); + /* prevent status code from having full line height width from .request-list-item */ + line-height: normal; +} + +.status-code[data-code^="1"] { + background-color: var(--status-code-color-1xx); +} + +.status-code[data-code^="2"] { + background-color: var(--status-code-color-2xx); +} + +.status-code[data-code^="3"] { + background-color: var(--status-code-color-3xx); +} + +.status-code[data-code^="4"] { + background-color: var(--status-code-color-4xx); +} + +.status-code[data-code^="5"] { + background-color: var(--status-code-color-5xx); +} + +/* Non-standard status codes are styled like 5XX */ +.status-code[data-code^="0"], +.status-code[data-code^="6"], +.status-code[data-code^="7"], +.status-code[data-code^="8"], +.status-code[data-code^="9"] { + background-color: var(--status-code-color-5xx); +} + +.status-code:not([data-code^="3"], .status-code-blocked) { + color: var(--theme-body-background); +} + +.status-code-blocked { + color: var(--theme-icon-error-color); +} + +.status-code-blocked-icon { + height: 12px; + width: 12px; + background-image: url("chrome://devtools/skin/images/blocked.svg"); + -moz-context-properties: fill; + fill: currentColor; +} + + +/* Status codes for the headers side panel */ + +.headers-overview .summary .status .status-code { + display: inline; + background-color: transparent; + color: inherit; + padding: 0 2px 0 0; + font-weight: bold; +} + +.headers-overview .summary .status[data-code^="1"] { + color: var(--status-code-color-1xx); +} + +.headers-overview .summary .status[data-code^="2"] { + color: var(--status-code-color-2xx); +} + +.headers-overview .summary .status[data-code^="3"] { + color: inherit; +} + +.headers-overview .summary .status[data-code^="4"] { + color: var(--status-code-color-4xx); +} + +.headers-overview .summary .status[data-code^="5"] { + color: var(--status-code-color-5xx); +} + +/* Non-standard status codes are styled like 5XX */ +.headers-overview .summary .status[data-code^="0"], +.headers-overview .summary .status[data-code^="6"], +.headers-overview .summary .status[data-code^="7"], +.headers-overview .summary .status[data-code^="8"], +.headers-overview .summary .status[data-code^="9"] { + color: var(--status-code-color-5xx); +} diff --git a/devtools/client/netmonitor/src/assets/styles/Toolbar.css b/devtools/client/netmonitor/src/assets/styles/Toolbar.css new file mode 100644 index 0000000000..ed37aa4046 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/Toolbar.css @@ -0,0 +1,102 @@ +/* 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/. */ + +/* Toolbar */ + +.devtools-toolbar { + display: flex; + align-items: center; +} + +#netmonitor-toolbar-container > .devtools-toolbar { + /* @TODO: Remove this in bug 1535956 */ + min-height: var(--primary-toolbar-height); +} + +.requests-list-filter-buttons { + white-space: nowrap; + margin: 0 7px; +} + +.devtools-button.devtools-pause-icon::before, +.devtools-button.devtools-play-icon::before { + margin-bottom: 1px; +} + +.devtools-button.devtools-pause-icon::before { + background-image: url("chrome://devtools/skin/images/pause.svg"); +} + +.devtools-button.devtools-play-icon::before { + background-image: url("chrome://devtools/content/netmonitor/src/assets/icons/play.svg"); +} + +/* New HTTP Custom Request button */ +.devtools-button.devtools-http-custom-request-icon::before { + background-image: url("chrome://devtools/skin/images/add.svg"); + background-size: 13px; +} + +/* Search button */ +.devtools-button.devtools-search-icon::before { + background-image: url("chrome://devtools/skin/images/search.svg"); + background-size: 13px; +} + +/* Request blocking button */ +.devtools-button.requests-list-blocking-button::before { + background-image: url("chrome://devtools/skin/images/blocked.svg"); +} + +.devtools-button.netmonitor-settings-menu-button::before { + background-image: url("chrome://devtools/skin/images/settings.svg"); +} + +.devtools-button.requests-list-blocking-button:empty::before { + fill: var(--theme-body-color); +} + +.devtools-button.requests-list-blocking-button.checked:empty::before { + fill: var(--theme-icon-checked-color); +} + +.devtools-button.requests-list-blocking-button.requests-list-blocking-button-enabled:empty::before { + fill: var(--timing-blocked-color); +} + +/* Throttling Button */ + +#network-throttling-menu { + margin-inline-start: 10px; + margin-inline-end: 10px; +} + +.devtools-toolbar .devtools-checkbox { + position: relative; + vertical-align: middle; + bottom: 1px; +} + +#devtools-cache-checkbox { + vertical-align: unset; + bottom: -1px; +} + +.devtools-toolbar .devtools-checkbox-label { + margin-inline-start: 2px; + margin-inline-end: 2px; + white-space: nowrap; +} + +.devtools-toolbar .devtools-checkbox-label.devtools-cache-checkbox { + margin-inline-end: 7px; +} + +/* Hide filter input learn more link if there is not enough + horizontal space. */ +@media (max-width: 590px) { + .network-monitor .devtools-searchbox .learn-more-link { + display: none; + } +} diff --git a/devtools/client/netmonitor/src/assets/styles/UrlPreview.css b/devtools/client/netmonitor/src/assets/styles/UrlPreview.css new file mode 100644 index 0000000000..9cf41fb7c9 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/UrlPreview.css @@ -0,0 +1,100 @@ +/* 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/. */ + +/* Url Preview */ + +.url-preview { + border-bottom: 1px solid var(--theme-splitter-color); + padding: 6px 3px; +} + +.url-preview .properties-view, +.url-preview .tree-container, +.url-preview .treeTable { + overflow: hidden; + outline: none; +} + +.url-preview .properties-view { + margin-right: 10px; +} + +.url-preview tbody:focus { + outline: none; +} +.url-preview td.splitter { + /* This makes sure that the column spans the width of the + side bar so the contained horizontal splitter is visible */ + width: 100vw !important; +} + +.url-preview .horizontal-splitter { + border-bottom: 1px solid var(--theme-splitter-color); + margin: 6px 0 6px 16px; +} + +.url-preview .treeValueCell .url { + display: inline; + white-space: normal; +} + +.url-preview .treeTable .treeRow .treeIcon { + margin-inline: 0 1px; +} + +.url-preview .tree-container .treeTable tr { + margin-bottom: 3px; +} + +.url-preview .treeTable .treeRow:not(.selected):hover { + background-color: transparent !important; +} + +.url-preview .treeTable tr.treeRow:first-child .treeLabelCell::after { + content: ""; +} +.url-preview .treeTable .treeLabelCell { + --tree-label-cell-indent: 0 !important; +} +/* Indent the array params */ +.url-preview .treeTable .treeRow[aria-level="4"] .treeLabelCell { + text-indent: 15px; +} + +.url-preview .treeTable .treeLabel[data-level="1"] { + text-transform: capitalize; +} + +/* Collapsed url */ +.url-preview tr.treeRow:first-child .treeLabelCell { + font-weight: bold; + color: var(--theme-icon-dimmed-color); +} + +.url-preview tr.treeRow .treeLabelCell { + float: left; + margin-right: -15px; + padding: 0 2px 0 0; + +} +.url-preview tr.treeRow .treeValueCell { + display: inline; + word-break: break-all; + max-width: none; + box-decoration-break: clone; + margin-left: 14px; +} + +.url-preview .treeTable .treeValueCell { + color: var(--theme-body-color); +} + +.url-preview .url-scheme, +.url-preview .url-chars { + color: var(--theme-icon-dimmed-color); +} + +.url-preview .url-params-name { + color: var(--theme-highlight-blue); +} diff --git a/devtools/client/netmonitor/src/assets/styles/messages.css b/devtools/client/netmonitor/src/assets/styles/messages.css new file mode 100644 index 0000000000..b115d7cf34 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/messages.css @@ -0,0 +1,165 @@ +/* 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/. */ + +/* Scroll to bottom */ + +#messages-view .uncontrolled { + flex-direction: column; +} + +#messages-view .message-list-scroll-anchor { + /* anchor nodes are required to have non-zero area */ + min-height: 1px; + margin: 0; + padding: 0; + border: none; +} + +/* Empty notice */ + +#messages-view .message-list-empty-notice { + width: 100%; +} + +/* Frame type icon in the Time column */ + +#messages-view .message-list-type-icon { + display: inline-block; + /* align bottom of image 4px below the text baseline + this tends to give a better result than "middle" */ + vertical-align: -4px; + -moz-context-properties: fill; + fill: currentColor; +} + +#messages-view .message-list-type-icon-sent { + color: var(--green-70); +} + +#messages-view .theme-dark .message-list-type-icon-sent { + color: var(--green-50); +} + +#messages-view .message-list-type-icon-received { + color: var(--red-60); + transform: scaleY(-1); +} + +#messages-view .theme-dark .message-list-type-icon-received { + color: var(--red-40); +} + +#messages-view .message-list-item.selected .message-list-type-icon { + color: inherit; +} + +#messages-view .msg-connection-closed-message { + text-align: center; +} + +/* Use lining numbers so that seconds and milliseconds align */ + +#messages-view .message-list-time { + font-variant-numeric: tabular-nums; +} + +/* Styles related to the data items in the MessagePayload component */ + +#messages-view .message-payload { + width: 100%; + display: flex; + flex-direction: column; +} + +#messages-view .message-rawData-payload { + display: block; + width: 100%; + height: 100%; + overflow: auto; + white-space: pre; + padding: 4px 8px; + padding-inline-start: 20px; + border: none; + font-family: var(--monospace-font-family); + font-size: var(--theme-code-font-size); + line-height: calc(15/11); + direction: ltr; + text-align: left; + resize: none; + color: var(--theme-body-color); + background-color: var(--theme-sidebar-background); +} + +/* Styles related to JSONPreview */ + +#messages-view .treeTable .objectBox { + white-space: normal; + overflow-wrap: break-word; +} + +/* Styles related to truncated data */ + +.theme-light #messages-view .truncated-data-message { + background: var(--grey-20); +} + +.theme-dark #messages-view .truncated-data-message { + background: var(--grey-70); +} + +.truncated-data-message { + border-bottom: 1px solid var(--theme-splitter-color); + padding: 4px 8px; + font-size: 12px; +} + +/* Styles related to truncated messages */ + +.theme-light #messages-view .truncated-messages-header { + background: var(--grey-20); +} + +.theme-dark #messages-view .truncated-messages-header { + background: var(--grey-70); +} + +.theme-dark #messages-view .truncated-messages-warning-icon { + fill: var(--grey-40); +} + +#messages-view .truncated-messages-cell { + padding: 0; /* reset td default padding */ +} + +#messages-view .truncated-messages-header { + border-bottom: 1px solid var(--theme-splitter-color); + padding: 2px 8px; + display: flex; + justify-content: space-between; + align-items: center; +} + +#messages-view .truncated-messages-container, +#messages-view .truncated-messages-checkbox-label { + display: flex; + align-items: center; +} + +#messages-view .truncated-messages-warning-icon { + width: 16px; + height: 16px; + margin-inline-end: 5px; + background-image: url(chrome://devtools/skin/images/info.svg); + background-repeat: no-repeat; + -moz-context-properties: fill; + fill: inherit; +} + +#messages-view .truncation-checkbox { + margin-inline-end: 5px; +} + +#messages-view .truncated-message { + font-variant-numeric: tabular-nums; +} diff --git a/devtools/client/netmonitor/src/assets/styles/netmonitor.css b/devtools/client/netmonitor/src/assets/styles/netmonitor.css new file mode 100644 index 0000000000..6b821065ed --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/netmonitor.css @@ -0,0 +1,84 @@ +/* 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/. */ + +@import "chrome://devtools/content/shared/components/SidebarToggle.css"; +@import "chrome://devtools/content/shared/components/splitter/SplitBox.css"; +@import "chrome://devtools/content/shared/components/tree/TreeView.css"; +@import "chrome://devtools/content/shared/components/Accordion.css"; +@import "chrome://devtools/content/shared/components/tabs/Tabs.css"; +@import "chrome://devtools/skin/components-frame.css"; +@import "chrome://devtools/content/shared/sourceeditor/codemirror/lib/codemirror.css"; +@import "chrome://devtools/content/shared/sourceeditor/codemirror/addon/dialog/dialog.css"; +@import "chrome://devtools/content/shared/sourceeditor/codemirror/mozilla.css"; +@import "chrome://devtools/content/shared/components/MdnLink.css"; +@import "chrome://devtools/content/shared/components/NotificationBox.css"; +@import "chrome://devtools/content/shared/components/AppErrorBoundary.css"; + +/* Network panel components & styles */ +@import "chrome://devtools/content/netmonitor/src/assets/styles/variables.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/Toolbar.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/StatusBar.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/RequestList.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/NetworkActionBar.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/RequestBlockingPanel.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/NetworkDetailsBar.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/StatisticsPanel.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/CustomRequestPanel.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/HTTPCustomRequestPanel.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/StatusCode.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/messages.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/search.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/UrlPreview.css"; +@import "chrome://devtools/content/netmonitor/src/assets/styles/HeadersPanel.css"; + +/* General */ + +* { + box-sizing: border-box; +} + +html, +body, +#mount, +.launchpad-root, +.network-monitor, +.monitor-panel { + flex: initial; + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; +} + +.split-box { + overflow: hidden; +} + +/* Drag and drop HAR files */ + +.network-monitor > div { + height: 100%; +} + +.network-monitor .dropHarFiles { + display: none; + align-items: center; + justify-content: center; + position: absolute; + text-align: center; + inset: 25px; + z-index: 100; + font-size: 3.5rem; + color: gray; + border: 4px dashed gray; + pointer-events: none; +} + +.network-monitor > div[dragging="true"] .dropHarFiles { + display: flex; +} + +.network-monitor > div[dragging="true"] { + filter: opacity(50%); +} diff --git a/devtools/client/netmonitor/src/assets/styles/search.css b/devtools/client/netmonitor/src/assets/styles/search.css new file mode 100644 index 0000000000..cc80183eb4 --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/search.css @@ -0,0 +1,155 @@ +/* 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/. */ + +.search-panel { + display: flex; + flex-direction: column; + overflow: hidden; + height: 100%; +} + +.search-panel .search-panel-content { + width: 100%; + height: 100%; + overflow: auto; + outline: 0 !important; +} + +.search-panel .treeTable { + width: 100%; + color: var(--theme-body-color); + outline: 0 !important; +} + +/* Custom tree styles for the Search results panel*/ +.search-panel .treeTable .treeLabelCell::after { + content: ""; +} + +/* Color for resource label */ +.search-panel .resourceCell { + color: var(--theme-text-color-inactive); +} + +.search-panel .treeTable tbody { + outline: 0 !important; +} + +.search-panel .treeTable .resultLabel { + font-weight: bold; +} + +.search-panel .treeTable .treeLabelCell { + text-overflow: ellipsis; + max-width: 0; + overflow: hidden; + white-space: nowrap; +} + +/* Icon for close button */ +#devtools-network-search-close::before { + background-image: url("chrome://devtools/skin/images/close.svg"); +} + +/* Case Sensitive button */ +#devtools-network-search-caseSensitive::before { + background-image: url("chrome://devtools/skin/images/case-match.svg"); +} + + +#devtools-network-search-close > button { + margin: 0 !important; + border-radius: 0 !important; + position: relative; + min-width: 26px; +} + +button.case-sensitive-btn { + padding: 2px; + margin: 0 3px; + border: none; + background: none; + width: 20px; + height: 20px; + border-radius: 2px; +} + +/* Color for query matches */ +.search-panel .resultCell .query-match { + background-color: var(--theme-contrast-background); + color: var(--theme-contrast-color); + border-bottom: 1px solid var(--theme-contrast-border); +} + +.search-modifiers { + display: flex; + align-items: center; +} + +.search-modifiers * { + user-select: none; +} + +.pipe-divider { + flex: none; + align-self: stretch; + width: 1px; + vertical-align: middle; + margin: 4px; + background-color: var(--theme-splitter-color); +} + +.search-type-name { + margin: 0 4px; + border: none; + background: transparent; + color: var(--theme-comment); +} + +.search-modifiers button { + margin: 0 3px; + border: none; + background: none; + width: 25px; + height: 20px; + border-radius: 2px; +} + +.search-panel .devtools-toolbar { + max-height: 26px; +} + +.search-panel .status-bar-label { + min-height: 24px; + white-space: nowrap; + text-overflow: ellipsis; + display: block; + overflow: hidden; + min-width: 150px; +} + +.search-panel .img.loader { + background-image: url(chrome://devtools/content/debugger/images/loader.svg); + background-repeat: no-repeat; + background-position: center; + background-size: contain; + width: 16px; + height: 16px; + margin-inline-start: 10px; + animation: search-loader-rotate 0.5s linear infinite; + -moz-context-properties: fill; + fill: var(--theme-selection-background); + display: inline-block; + top: 4px; + position: relative; +} + +@keyframes search-loader-rotate { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} diff --git a/devtools/client/netmonitor/src/assets/styles/variables.css b/devtools/client/netmonitor/src/assets/styles/variables.css new file mode 100644 index 0000000000..cad71e267c --- /dev/null +++ b/devtools/client/netmonitor/src/assets/styles/variables.css @@ -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/. */ + +:root { + --primary-toolbar-height: 29px; + /* HTTP status codes */ + --status-code-color-1xx: var(--theme-highlight-blue); + --status-code-color-2xx: var(--theme-highlight-green); + --status-code-color-3xx: transparent; + --status-code-color-4xx: var(--theme-highlight-pink); + --status-code-color-5xx: var(--theme-highlight-red); +} + +:root.theme-dark { + --table-splitter-color: var(--grey-70); + --table-zebra-background: rgba(255,255,255,0.05); + --table-zebra-inline-icons-background: rgb(49, 47, 47); + --table-selection-background-hover: rgba(53, 59, 72, 1); + --table-selection-inline-icons-background-hover: rgba(53, 59, 72, 1); + + --timing-blocked-color: var(--red-20); + --timing-dns-color: rgba(223, 128, 255, 0.8); /* pink */ + --timing-ssl-color: rgba(217, 102, 41, 0.8); /* orange */ + --timing-connect-color: rgba(217, 102, 41, 0.8); /* orange */ + --timing-send-color: rgba(70, 175, 227, 0.8); /* light blue */ + --timing-wait-color: rgba(94, 136, 176, 0.8); /* blue grey */ + --timing-receive-color: rgba(112, 191, 83, 0.8); /* green */ +} + +:root.theme-light { + --table-splitter-color: var(--grey-20); + --table-zebra-background: rgba(247, 247, 247, 0.8); + --table-zebra-inline-icons-background: rgba(247, 247, 247); + --table-selection-background-hover: rgba(209, 232, 255, 0.8); + --table-selection-inline-icons-background-hover: rgba(209, 232, 255); + + --timing-blocked-color: var(--red-70); + --timing-dns-color: rgba(223, 128, 255, 0.8); /* pink */ + --timing-ssl-color: rgba(217, 102, 41, 0.8); /* orange */ + --timing-connect-color: rgba(217, 102, 41, 0.8); /* orange */ + --timing-send-color: rgba(0, 136, 204, 0.8); /* blue */ + --timing-wait-color: rgba(95, 136, 176, 0.8); /* blue grey */ + --timing-receive-color: rgba(44, 187, 15, 0.8); /* green */ +} 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 + * + * 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 + * + * 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 + * + * 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 + * + * 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 + * + * 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
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