From 5f8de423f190bbb79a62f804151bc24824fa32d8 Mon Sep 17 00:00:00 2001 From: "Matt A. Tobin" Date: Fri, 2 Feb 2018 04:16:08 -0500 Subject: Add m-esr52 at 52.6.0 --- devtools/client/jsonview/.eslintrc.js | 11 + .../client/jsonview/components/headers-panel.js | 79 + devtools/client/jsonview/components/headers.js | 105 + devtools/client/jsonview/components/json-panel.js | 194 ++ .../client/jsonview/components/main-tabbed-area.js | 89 + devtools/client/jsonview/components/moz.build | 18 + devtools/client/jsonview/components/reps/moz.build | 9 + .../client/jsonview/components/reps/toolbar.js | 58 + devtools/client/jsonview/components/search-box.js | 55 + devtools/client/jsonview/components/text-panel.js | 95 + devtools/client/jsonview/converter-child.js | 345 ++++ devtools/client/jsonview/converter-observer.js | 97 + devtools/client/jsonview/converter-sniffer.js | 106 + devtools/client/jsonview/css/general.css | 46 + devtools/client/jsonview/css/headers-panel.css | 78 + devtools/client/jsonview/css/json-panel.css | 16 + devtools/client/jsonview/css/main.css | 59 + devtools/client/jsonview/css/moz.build | 16 + devtools/client/jsonview/css/search-box.css | 24 + devtools/client/jsonview/css/search.svg | 22 + devtools/client/jsonview/css/text-panel.css | 26 + devtools/client/jsonview/css/toolbar.css | 92 + devtools/client/jsonview/json-viewer.js | 112 ++ devtools/client/jsonview/lib/moz.build | 9 + devtools/client/jsonview/lib/require.js | 2076 ++++++++++++++++++++ devtools/client/jsonview/main.js | 62 + devtools/client/jsonview/moz.build | 23 + devtools/client/jsonview/test/.eslintrc.js | 6 + devtools/client/jsonview/test/array_json.json | 1 + .../client/jsonview/test/array_json.json^headers^ | 1 + devtools/client/jsonview/test/browser.ini | 28 + .../jsonview/test/browser_jsonview_copy_headers.js | 35 + .../jsonview/test/browser_jsonview_copy_json.js | 31 + .../jsonview/test/browser_jsonview_copy_rawdata.js | 53 + .../jsonview/test/browser_jsonview_filter.js | 28 + .../jsonview/test/browser_jsonview_invalid_json.js | 20 + .../jsonview/test/browser_jsonview_save_json.js | 38 + .../jsonview/test/browser_jsonview_valid_json.js | 33 + devtools/client/jsonview/test/doc_frame_script.js | 98 + devtools/client/jsonview/test/head.js | 145 ++ devtools/client/jsonview/test/invalid_json.json | 1 + .../jsonview/test/invalid_json.json^headers^ | 1 + devtools/client/jsonview/test/simple_json.json | 1 + .../client/jsonview/test/simple_json.json^headers^ | 1 + devtools/client/jsonview/test/valid_json.json | 6 + .../client/jsonview/test/valid_json.json^headers^ | 1 + devtools/client/jsonview/utils.js | 101 + devtools/client/jsonview/viewer-config.js | 39 + 48 files changed, 4590 insertions(+) create mode 100644 devtools/client/jsonview/.eslintrc.js create mode 100644 devtools/client/jsonview/components/headers-panel.js create mode 100644 devtools/client/jsonview/components/headers.js create mode 100644 devtools/client/jsonview/components/json-panel.js create mode 100644 devtools/client/jsonview/components/main-tabbed-area.js create mode 100644 devtools/client/jsonview/components/moz.build create mode 100644 devtools/client/jsonview/components/reps/moz.build create mode 100644 devtools/client/jsonview/components/reps/toolbar.js create mode 100644 devtools/client/jsonview/components/search-box.js create mode 100644 devtools/client/jsonview/components/text-panel.js create mode 100644 devtools/client/jsonview/converter-child.js create mode 100644 devtools/client/jsonview/converter-observer.js create mode 100644 devtools/client/jsonview/converter-sniffer.js create mode 100644 devtools/client/jsonview/css/general.css create mode 100644 devtools/client/jsonview/css/headers-panel.css create mode 100644 devtools/client/jsonview/css/json-panel.css create mode 100644 devtools/client/jsonview/css/main.css create mode 100644 devtools/client/jsonview/css/moz.build create mode 100644 devtools/client/jsonview/css/search-box.css create mode 100644 devtools/client/jsonview/css/search.svg create mode 100644 devtools/client/jsonview/css/text-panel.css create mode 100644 devtools/client/jsonview/css/toolbar.css create mode 100644 devtools/client/jsonview/json-viewer.js create mode 100644 devtools/client/jsonview/lib/moz.build create mode 100644 devtools/client/jsonview/lib/require.js create mode 100644 devtools/client/jsonview/main.js create mode 100644 devtools/client/jsonview/moz.build create mode 100644 devtools/client/jsonview/test/.eslintrc.js create mode 100644 devtools/client/jsonview/test/array_json.json create mode 100644 devtools/client/jsonview/test/array_json.json^headers^ create mode 100644 devtools/client/jsonview/test/browser.ini create mode 100644 devtools/client/jsonview/test/browser_jsonview_copy_headers.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_copy_json.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_filter.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_invalid_json.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_save_json.js create mode 100644 devtools/client/jsonview/test/browser_jsonview_valid_json.js create mode 100644 devtools/client/jsonview/test/doc_frame_script.js create mode 100644 devtools/client/jsonview/test/head.js create mode 100644 devtools/client/jsonview/test/invalid_json.json create mode 100644 devtools/client/jsonview/test/invalid_json.json^headers^ create mode 100644 devtools/client/jsonview/test/simple_json.json create mode 100644 devtools/client/jsonview/test/simple_json.json^headers^ create mode 100644 devtools/client/jsonview/test/valid_json.json create mode 100644 devtools/client/jsonview/test/valid_json.json^headers^ create mode 100644 devtools/client/jsonview/utils.js create mode 100644 devtools/client/jsonview/viewer-config.js (limited to 'devtools/client/jsonview') diff --git a/devtools/client/jsonview/.eslintrc.js b/devtools/client/jsonview/.eslintrc.js new file mode 100644 index 000000000..bd1e31981 --- /dev/null +++ b/devtools/client/jsonview/.eslintrc.js @@ -0,0 +1,11 @@ +"use strict"; + +module.exports = { + "globals": { + "define": true, + "document": true, + "window": true, + "CustomEvent": true, + "Locale": true + } +}; diff --git a/devtools/client/jsonview/components/headers-panel.js b/devtools/client/jsonview/components/headers-panel.js new file mode 100644 index 000000000..9229aaa01 --- /dev/null +++ b/devtools/client/jsonview/components/headers-panel.js @@ -0,0 +1,79 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { DOM: dom, createFactory, createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + const { createFactories } = require("devtools/client/shared/components/reps/rep-utils"); + const { Headers } = createFactories(require("./headers")); + const { Toolbar, ToolbarButton } = createFactories(require("./reps/toolbar")); + + const { div } = dom; + + /** + * This template represents the 'Headers' panel + * s responsible for rendering its content. + */ + let HeadersPanel = createClass({ + displayName: "HeadersPanel", + + propTypes: { + actions: PropTypes.object, + data: PropTypes.object, + }, + + getInitialState: function () { + return { + data: {} + }; + }, + + render: function () { + let data = this.props.data; + + return ( + div({className: "headersPanelBox"}, + HeadersToolbar({actions: this.props.actions}), + div({className: "panelContent"}, + Headers({data: data}) + ) + ) + ); + } + }); + + /** + * This template is responsible for rendering a toolbar + * within the 'Headers' panel. + */ + let HeadersToolbar = createFactory(createClass({ + displayName: "HeadersToolbar", + + propTypes: { + actions: PropTypes.object, + }, + + // Commands + + onCopy: function (event) { + this.props.actions.onCopyHeaders(); + }, + + render: function () { + return ( + Toolbar({}, + ToolbarButton({className: "btn copy", onClick: this.onCopy}, + Locale.$STR("jsonViewer.Copy") + ) + ) + ); + }, + })); + + // Exports from this module + exports.HeadersPanel = HeadersPanel; +}); diff --git a/devtools/client/jsonview/components/headers.js b/devtools/client/jsonview/components/headers.js new file mode 100644 index 000000000..38ac4051c --- /dev/null +++ b/devtools/client/jsonview/components/headers.js @@ -0,0 +1,105 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { DOM: dom, createFactory, createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + + const { div, span, table, tbody, tr, td, } = dom; + + /** + * This template is responsible for rendering basic layout + * of the 'Headers' panel. It displays HTTP headers groups such as + * received or response headers. + */ + let Headers = createClass({ + displayName: "Headers", + + propTypes: { + data: PropTypes.object, + }, + + getInitialState: function () { + return {}; + }, + + render: function () { + let data = this.props.data; + + return ( + div({className: "netInfoHeadersTable"}, + div({className: "netHeadersGroup"}, + div({className: "netInfoHeadersGroup"}, + Locale.$STR("jsonViewer.responseHeaders") + ), + table({cellPadding: 0, cellSpacing: 0}, + HeaderList({headers: data.response}) + ) + ), + div({className: "netHeadersGroup"}, + div({className: "netInfoHeadersGroup"}, + Locale.$STR("jsonViewer.requestHeaders") + ), + table({cellPadding: 0, cellSpacing: 0}, + HeaderList({headers: data.request}) + ) + ) + ) + ); + } + }); + + /** + * This template renders headers list, + * name + value pairs. + */ + let HeaderList = createFactory(createClass({ + displayName: "HeaderList", + + propTypes: { + headers: PropTypes.arrayOf(PropTypes.shape({ + name: PropTypes.string, + value: PropTypes.string + })) + }, + + getInitialState: function () { + return { + headers: [] + }; + }, + + render: function () { + let headers = this.props.headers; + + headers.sort(function (a, b) { + return a.name > b.name ? 1 : -1; + }); + + let rows = []; + headers.forEach(header => { + rows.push( + tr({key: header.name}, + td({className: "netInfoParamName"}, + span({title: header.name}, header.name) + ), + td({className: "netInfoParamValue"}, header.value) + ) + ); + }); + + return ( + tbody({}, + rows + ) + ); + } + })); + + // Exports from this module + exports.Headers = Headers; +}); diff --git a/devtools/client/jsonview/components/json-panel.js b/devtools/client/jsonview/components/json-panel.js new file mode 100644 index 000000000..c7280a0b1 --- /dev/null +++ b/devtools/client/jsonview/components/json-panel.js @@ -0,0 +1,194 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { DOM: dom, createFactory, createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + const { createFactories } = require("devtools/client/shared/components/reps/rep-utils"); + const TreeView = createFactory(require("devtools/client/shared/components/tree/tree-view")); + const { Rep } = createFactories(require("devtools/client/shared/components/reps/rep")); + const { SearchBox } = createFactories(require("./search-box")); + const { Toolbar, ToolbarButton } = createFactories(require("./reps/toolbar")); + + const { div } = dom; + const AUTO_EXPAND_MAX_SIZE = 100 * 1024; + const AUTO_EXPAND_MAX_LEVEL = 7; + + /** + * This template represents the 'JSON' panel. The panel is + * responsible for rendering an expandable tree that allows simple + * inspection of JSON structure. + */ + let JsonPanel = createClass({ + displayName: "JsonPanel", + + propTypes: { + data: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.array, + PropTypes.object + ]), + jsonTextLength: PropTypes.number, + searchFilter: PropTypes.string, + actions: PropTypes.object, + }, + + getInitialState: function () { + return {}; + }, + + componentDidMount: function () { + document.addEventListener("keypress", this.onKeyPress, true); + }, + + componentWillUnmount: function () { + document.removeEventListener("keypress", this.onKeyPress, true); + }, + + onKeyPress: function (e) { + // XXX shortcut for focusing the Filter field (see Bug 1178771). + }, + + onFilter: function (object) { + if (!this.props.searchFilter) { + return true; + } + + let json = JSON.stringify(object).toLowerCase(); + return json.indexOf(this.props.searchFilter.toLowerCase()) >= 0; + }, + + getExpandedNodes: function (object, path = "", level = 0) { + if (typeof object != "object") { + return null; + } + + if (level > AUTO_EXPAND_MAX_LEVEL) { + return null; + } + + let expandedNodes = new Set(); + for (let prop in object) { + let nodePath = path + "/" + prop; + expandedNodes.add(nodePath); + + let nodes = this.getExpandedNodes(object[prop], nodePath, level + 1); + if (nodes) { + expandedNodes = new Set([...expandedNodes, ...nodes]); + } + } + return expandedNodes; + }, + + renderValue: props => { + let member = props.member; + + // Hide object summary when object is expanded (bug 1244912). + if (typeof member.value == "object" && member.open) { + return null; + } + + // Render the value (summary) using Reps library. + return Rep(Object.assign({}, props, { + cropLimit: 50, + })); + }, + + renderTree: function () { + // Append custom column for displaying values. This column + // Take all available horizontal space. + let columns = [{ + id: "value", + width: "100%" + }]; + + // Expand the document by default if its size isn't bigger than 100KB. + let expandedNodes = new Set(); + if (this.props.jsonTextLength <= AUTO_EXPAND_MAX_SIZE) { + expandedNodes = this.getExpandedNodes(this.props.data); + } + + // Render tree component. + return TreeView({ + object: this.props.data, + mode: "tiny", + onFilter: this.onFilter, + columns: columns, + renderValue: this.renderValue, + expandedNodes: expandedNodes, + }); + }, + + render: function () { + let content; + let data = this.props.data; + + try { + if (typeof data == "object") { + content = this.renderTree(); + } else { + content = div({className: "jsonParseError"}, + data + "" + ); + } + } catch (err) { + content = div({className: "jsonParseError"}, + err + "" + ); + } + + return ( + div({className: "jsonPanelBox"}, + JsonToolbar({actions: this.props.actions}), + div({className: "panelContent"}, + content + ) + ) + ); + } + }); + + /** + * This template represents a toolbar within the 'JSON' panel. + */ + let JsonToolbar = createFactory(createClass({ + displayName: "JsonToolbar", + + propTypes: { + actions: PropTypes.object, + }, + + // Commands + + onSave: function (event) { + this.props.actions.onSaveJson(); + }, + + onCopy: function (event) { + this.props.actions.onCopyJson(); + }, + + render: function () { + return ( + Toolbar({}, + ToolbarButton({className: "btn save", onClick: this.onSave}, + Locale.$STR("jsonViewer.Save") + ), + ToolbarButton({className: "btn copy", onClick: this.onCopy}, + Locale.$STR("jsonViewer.Copy") + ), + SearchBox({ + actions: this.props.actions + }) + ) + ); + }, + })); + + // Exports from this module + exports.JsonPanel = JsonPanel; +}); diff --git a/devtools/client/jsonview/components/main-tabbed-area.js b/devtools/client/jsonview/components/main-tabbed-area.js new file mode 100644 index 000000000..ecba73807 --- /dev/null +++ b/devtools/client/jsonview/components/main-tabbed-area.js @@ -0,0 +1,89 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + const { createFactories } = require("devtools/client/shared/components/reps/rep-utils"); + const { JsonPanel } = createFactories(require("./json-panel")); + const { TextPanel } = createFactories(require("./text-panel")); + const { HeadersPanel } = createFactories(require("./headers-panel")); + const { Tabs, TabPanel } = createFactories(require("devtools/client/shared/components/tabs/tabs")); + + /** + * This object represents the root application template + * responsible for rendering the basic tab layout. + */ + let MainTabbedArea = createClass({ + displayName: "MainTabbedArea", + + propTypes: { + jsonText: PropTypes.string, + tabActive: PropTypes.number, + actions: PropTypes.object, + headers: PropTypes.object, + searchFilter: PropTypes.string, + json: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object, + PropTypes.array + ]) + }, + + getInitialState: function () { + return { + json: {}, + headers: {}, + jsonText: this.props.jsonText, + tabActive: this.props.tabActive + }; + }, + + onTabChanged: function (index) { + this.setState({tabActive: index}); + }, + + render: function () { + return ( + Tabs({ + tabActive: this.state.tabActive, + onAfterChange: this.onTabChanged}, + TabPanel({ + className: "json", + title: Locale.$STR("jsonViewer.tab.JSON")}, + JsonPanel({ + data: this.props.json, + jsonTextLength: this.props.jsonText.length, + actions: this.props.actions, + searchFilter: this.state.searchFilter + }) + ), + TabPanel({ + className: "rawdata", + title: Locale.$STR("jsonViewer.tab.RawData")}, + TextPanel({ + data: this.state.jsonText, + actions: this.props.actions + }) + ), + TabPanel({ + className: "headers", + title: Locale.$STR("jsonViewer.tab.Headers")}, + HeadersPanel({ + data: this.props.headers, + actions: this.props.actions, + searchFilter: this.props.searchFilter + }) + ) + ) + ); + } + }); + + // Exports from this module + exports.MainTabbedArea = MainTabbedArea; +}); diff --git a/devtools/client/jsonview/components/moz.build b/devtools/client/jsonview/components/moz.build new file mode 100644 index 000000000..fa66c8709 --- /dev/null +++ b/devtools/client/jsonview/components/moz.build @@ -0,0 +1,18 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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 += [ + 'reps' +] + +DevToolsModules( + 'headers-panel.js', + 'headers.js', + 'json-panel.js', + 'main-tabbed-area.js', + 'search-box.js', + 'text-panel.js' +) diff --git a/devtools/client/jsonview/components/reps/moz.build b/devtools/client/jsonview/components/reps/moz.build new file mode 100644 index 000000000..1d239b7bd --- /dev/null +++ b/devtools/client/jsonview/components/reps/moz.build @@ -0,0 +1,9 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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( + 'toolbar.js', +) diff --git a/devtools/client/jsonview/components/reps/toolbar.js b/devtools/client/jsonview/components/reps/toolbar.js new file mode 100644 index 000000000..52a35ffbe --- /dev/null +++ b/devtools/client/jsonview/components/reps/toolbar.js @@ -0,0 +1,58 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const React = require("devtools/client/shared/vendor/react"); + const DOM = React.DOM; + + /** + * Renders a simple toolbar. + */ + let Toolbar = React.createClass({ + displayName: "Toolbar", + + propTypes: { + children: React.PropTypes.oneOfType([ + React.PropTypes.array, + React.PropTypes.element + ]) + }, + + render: function () { + return ( + DOM.div({className: "toolbar"}, + this.props.children + ) + ); + } + }); + + /** + * Renders a simple toolbar button. + */ + let ToolbarButton = React.createClass({ + displayName: "ToolbarButton", + + propTypes: { + active: React.PropTypes.bool, + disabled: React.PropTypes.bool, + children: React.PropTypes.string, + }, + + render: function () { + let props = Object.assign({className: "btn"}, this.props); + return ( + DOM.button(props, this.props.children) + ); + }, + }); + + // Exports from this module + exports.Toolbar = Toolbar; + exports.ToolbarButton = ToolbarButton; +}); diff --git a/devtools/client/jsonview/components/search-box.js b/devtools/client/jsonview/components/search-box.js new file mode 100644 index 000000000..fc9bcbcb8 --- /dev/null +++ b/devtools/client/jsonview/components/search-box.js @@ -0,0 +1,55 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { DOM: dom, createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + + const { input } = dom; + + // For smooth incremental searching (in case the user is typing quickly). + const searchDelay = 250; + + /** + * This object represents a search box located at the + * top right corner of the application. + */ + let SearchBox = createClass({ + displayName: "SearchBox", + + propTypes: { + actions: PropTypes.object, + }, + + onSearch: function (event) { + let searchBox = event.target; + let win = searchBox.ownerDocument.defaultView; + + if (this.searchTimeout) { + win.clearTimeout(this.searchTimeout); + } + + let callback = this.doSearch.bind(this, searchBox); + this.searchTimeout = win.setTimeout(callback, searchDelay); + }, + + doSearch: function (searchBox) { + this.props.actions.onSearch(searchBox.value); + }, + + render: function () { + return ( + input({className: "searchBox", + placeholder: Locale.$STR("jsonViewer.filterJSON"), + onChange: this.onSearch}) + ); + }, + }); + + // Exports from this module + exports.SearchBox = SearchBox; +}); diff --git a/devtools/client/jsonview/components/text-panel.js b/devtools/client/jsonview/components/text-panel.js new file mode 100644 index 000000000..1df2e349d --- /dev/null +++ b/devtools/client/jsonview/components/text-panel.js @@ -0,0 +1,95 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { DOM: dom, createFactory, createClass, PropTypes } = require("devtools/client/shared/vendor/react"); + const { createFactories } = require("devtools/client/shared/components/reps/rep-utils"); + const { Toolbar, ToolbarButton } = createFactories(require("./reps/toolbar")); + const { div, pre } = dom; + + /** + * This template represents the 'Raw Data' panel displaying + * JSON as a text received from the server. + */ + let TextPanel = createClass({ + displayName: "TextPanel", + + propTypes: { + actions: PropTypes.object, + data: PropTypes.string + }, + + getInitialState: function () { + return {}; + }, + + render: function () { + return ( + div({className: "textPanelBox"}, + TextToolbar({actions: this.props.actions}), + div({className: "panelContent"}, + pre({className: "data"}, + this.props.data + ) + ) + ) + ); + } + }); + + /** + * This object represents a toolbar displayed within the + * 'Raw Data' panel. + */ + let TextToolbar = createFactory(createClass({ + displayName: "TextToolbar", + + propTypes: { + actions: PropTypes.object, + }, + + // Commands + + onPrettify: function (event) { + this.props.actions.onPrettify(); + }, + + onSave: function (event) { + this.props.actions.onSaveJson(); + }, + + onCopy: function (event) { + this.props.actions.onCopyJson(); + }, + + render: function () { + return ( + Toolbar({}, + ToolbarButton({ + className: "btn save", + onClick: this.onSave}, + Locale.$STR("jsonViewer.Save") + ), + ToolbarButton({ + className: "btn copy", + onClick: this.onCopy}, + Locale.$STR("jsonViewer.Copy") + ), + ToolbarButton({ + className: "btn prettyprint", + onClick: this.onPrettify}, + Locale.$STR("jsonViewer.PrettyPrint") + ) + ) + ); + }, + })); + + // Exports from this module + exports.TextPanel = TextPanel; +}); diff --git a/devtools/client/jsonview/converter-child.js b/devtools/client/jsonview/converter-child.js new file mode 100644 index 000000000..61aa0c9a3 --- /dev/null +++ b/devtools/client/jsonview/converter-child.js @@ -0,0 +1,345 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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 {Cc, Ci, components} = require("chrome"); +const Services = require("Services"); +const {Class} = require("sdk/core/heritage"); +const {Unknown} = require("sdk/platform/xpcom"); +const xpcom = require("sdk/platform/xpcom"); +const Events = require("sdk/dom/events"); +const Clipboard = require("sdk/clipboard"); + +loader.lazyRequireGetter(this, "NetworkHelper", + "devtools/shared/webconsole/network-helper"); +loader.lazyRequireGetter(this, "JsonViewUtils", + "devtools/client/jsonview/utils"); + +const childProcessMessageManager = + Cc["@mozilla.org/childprocessmessagemanager;1"] + .getService(Ci.nsISyncMessageSender); + +// Amount of space that will be allocated for the stream's backing-store. +// Must be power of 2. Used to copy the data stream in onStopRequest. +const SEGMENT_SIZE = Math.pow(2, 17); + +const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view"; +const CONTRACT_ID = "@mozilla.org/streamconv;1?from=" + + JSON_VIEW_MIME_TYPE + "&to=*/*"; +const CLASS_ID = "{d8c9acee-dec5-11e4-8c75-1681e6b88ec1}"; + +// Localization +let jsonViewStrings = Services.strings.createBundle( + "chrome://devtools/locale/jsonview.properties"); + +/** + * This object detects 'application/vnd.mozilla.json.view' content type + * and converts it into a JSON Viewer application that allows simple + * JSON inspection. + * + * Inspired by JSON View: https://github.com/bhollis/jsonview/ + */ +let Converter = Class({ + extends: Unknown, + + interfaces: [ + "nsIStreamConverter", + "nsIStreamListener", + "nsIRequestObserver" + ], + + get wrappedJSObject() { + return this; + }, + + /** + * This component works as such: + * 1. asyncConvertData captures the listener + * 2. onStartRequest fires, initializes stuff, modifies the listener + * to match our output type + * 3. onDataAvailable transcodes the data into a UTF-8 string + * 4. onStopRequest gets the collected data and converts it, + * spits it to the listener + * 5. convert does nothing, it's just the synchronous version + * of asyncConvertData + */ + convert: function (fromStream, fromType, toType, ctx) { + return fromStream; + }, + + asyncConvertData: function (fromType, toType, listener, ctx) { + this.listener = listener; + }, + + onDataAvailable: function (request, context, inputStream, offset, count) { + // From https://developer.mozilla.org/en/Reading_textual_data + let is = Cc["@mozilla.org/intl/converter-input-stream;1"] + .createInstance(Ci.nsIConverterInputStream); + is.init(inputStream, this.charset, -1, + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + + // Seed it with something positive + while (count) { + let str = {}; + let bytesRead = is.readString(count, str); + if (!bytesRead) { + break; + } + count -= bytesRead; + this.data += str.value; + } + }, + + onStartRequest: function (request, context) { + this.data = ""; + this.uri = request.QueryInterface(Ci.nsIChannel).URI.spec; + + // Sets the charset if it is available. (For documents loaded from the + // filesystem, this is not set.) + this.charset = + request.QueryInterface(Ci.nsIChannel).contentCharset || "UTF-8"; + + this.channel = request; + this.channel.contentType = "text/html"; + this.channel.contentCharset = "UTF-8"; + // Because content might still have a reference to this window, + // force setting it to a null principal to avoid it being same- + // origin with (other) content. + this.channel.loadInfo.resetPrincipalsToNullPrincipal(); + + this.listener.onStartRequest(this.channel, context); + }, + + /** + * This should go something like this: + * 1. Make sure we have a unicode string. + * 2. Convert it to a Javascript object. + * 2.1 Removes the callback + * 3. Convert that to HTML? Or XUL? + * 4. Spit it back out at the listener + */ + onStopRequest: function (request, context, statusCode) { + let headers = { + response: [], + request: [] + }; + + let win = NetworkHelper.getWindowForRequest(request); + + let Locale = { + $STR: key => { + try { + return jsonViewStrings.GetStringFromName(key); + } catch (err) { + console.error(err); + return undefined; + } + } + }; + + JsonViewUtils.exportIntoContentScope(win, Locale, "Locale"); + + Events.once(win, "DOMContentLoaded", event => { + win.addEventListener("contentMessage", + this.onContentMessage.bind(this), false, true); + }); + + // The request doesn't have to be always nsIHttpChannel + // (e.g. in case of data: URLs) + if (request instanceof Ci.nsIHttpChannel) { + request.visitResponseHeaders({ + visitHeader: function (name, value) { + headers.response.push({name: name, value: value}); + } + }); + + request.visitRequestHeaders({ + visitHeader: function (name, value) { + headers.request.push({name: name, value: value}); + } + }); + } + + let outputDoc = ""; + + try { + headers = JSON.stringify(headers); + outputDoc = this.toHTML(this.data, headers, this.uri); + } catch (e) { + console.error("JSON Viewer ERROR " + e); + outputDoc = this.toErrorPage(e, this.data, this.uri); + } + + let storage = Cc["@mozilla.org/storagestream;1"] + .createInstance(Ci.nsIStorageStream); + + storage.init(SEGMENT_SIZE, 0xffffffff, null); + let out = storage.getOutputStream(0); + + let binout = Cc["@mozilla.org/binaryoutputstream;1"] + .createInstance(Ci.nsIBinaryOutputStream); + + binout.setOutputStream(out); + binout.writeUtf8Z(outputDoc); + binout.close(); + + // We need to trim 4 bytes off the front (this could be underlying bug). + let trunc = 4; + let instream = storage.newInputStream(trunc); + + // Pass the data to the main content listener + this.listener.onDataAvailable(this.channel, context, instream, 0, + instream.available()); + + this.listener.onStopRequest(this.channel, context, statusCode); + + this.listener = null; + }, + + htmlEncode: function (t) { + return t !== null ? t.toString() + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(//g, ">") : ""; + }, + + toHTML: function (json, headers, title) { + let themeClassName = "theme-" + JsonViewUtils.getCurrentTheme(); + let clientBaseUrl = "resource://devtools/client/"; + let baseUrl = clientBaseUrl + "jsonview/"; + let themeVarsUrl = clientBaseUrl + "themes/variables.css"; + let commonUrl = clientBaseUrl + "themes/common.css"; + let toolbarsUrl = clientBaseUrl + "themes/toolbars.css"; + + let os; + let platform = Services.appinfo.OS; + if (platform.startsWith("WINNT")) { + os = "win"; + } else if (platform.startsWith("Darwin")) { + os = "mac"; + } else { + os = "linux"; + } + + return "\n" + + "" + + "" + this.htmlEncode(title) + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "
" + + "
" + this.htmlEncode(json) + "
" + + "
" + this.htmlEncode(headers) + "
" + + ""; + }, + + toErrorPage: function (error, data, uri) { + // Escape unicode nulls + data = data.replace("\u0000", "\uFFFD"); + + let errorInfo = error + ""; + + let output = "
" + "error parsing"; + if (errorInfo.message) { + output += "
" + errorInfo.message + "
"; + } + + output += "
" + this.highlightError(data, + errorInfo.line, errorInfo.column) + "
"; + + return "\n" + + "" + this.htmlEncode(uri + " - Error") + "" + + "" + + "" + + output + + ""; + }, + + // Chrome <-> Content communication + + onContentMessage: function (e) { + // Do not handle events from different documents. + let win = NetworkHelper.getWindowForRequest(this.channel); + if (win != e.target) { + return; + } + + let value = e.detail.value; + switch (e.detail.type) { + case "copy": + Clipboard.set(value, "text"); + break; + + case "copy-headers": + this.copyHeaders(value); + break; + + case "save": + childProcessMessageManager.sendAsyncMessage( + "devtools:jsonview:save", value); + } + }, + + copyHeaders: function (headers) { + let value = ""; + let eol = (Services.appinfo.OS !== "WINNT") ? "\n" : "\r\n"; + + let responseHeaders = headers.response; + for (let i = 0; i < responseHeaders.length; i++) { + let header = responseHeaders[i]; + value += header.name + ": " + header.value + eol; + } + + value += eol; + + let requestHeaders = headers.request; + for (let i = 0; i < requestHeaders.length; i++) { + let header = requestHeaders[i]; + value += header.name + ": " + header.value + eol; + } + + Clipboard.set(value, "text"); + } +}); + +// Stream converter component definition +let service = xpcom.Service({ + id: components.ID(CLASS_ID), + contract: CONTRACT_ID, + Component: Converter, + register: false, + unregister: false +}); + +function register() { + if (!xpcom.isRegistered(service)) { + xpcom.register(service); + return true; + } + return false; +} + +function unregister() { + if (xpcom.isRegistered(service)) { + xpcom.unregister(service); + return true; + } + return false; +} + +exports.JsonViewService = { + register: register, + unregister: unregister +}; diff --git a/devtools/client/jsonview/converter-observer.js b/devtools/client/jsonview/converter-observer.js new file mode 100644 index 000000000..9b149c565 --- /dev/null +++ b/devtools/client/jsonview/converter-observer.js @@ -0,0 +1,97 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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 Cu = Components.utils; + +const {XPCOMUtils} = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); +const {Services} = Cu.import("resource://gre/modules/Services.jsm", {}); + +// Load devtools module lazily. +XPCOMUtils.defineLazyGetter(this, "devtools", function () { + const {devtools} = Cu.import("resource://devtools/shared/Loader.jsm", {}); + return devtools; +}); + +// Load JsonView services lazily. +XPCOMUtils.defineLazyGetter(this, "JsonViewService", function () { + const {JsonViewService} = devtools.require("devtools/client/jsonview/converter-child"); + return JsonViewService; +}); + +XPCOMUtils.defineLazyGetter(this, "JsonViewSniffer", function () { + const {JsonViewSniffer} = devtools.require("devtools/client/jsonview/converter-sniffer"); + return JsonViewSniffer; +}); + +// Constants +const JSON_VIEW_PREF = "devtools.jsonview.enabled"; + +/** + * Listen for 'devtools.jsonview.enabled' preference changes and + * register/unregister the JSON View XPCOM services as appropriate. + */ +function ConverterObserver() { +} + +ConverterObserver.prototype = { + initialize: function () { + // Only the DevEdition has this feature available by default. + // Users need to manually flip 'devtools.jsonview.enabled' preference + // to have it available in other distributions. + if (this.isEnabled()) { + this.register(); + } + + Services.prefs.addObserver(JSON_VIEW_PREF, this, false); + Services.obs.addObserver(this, "xpcom-shutdown", false); + }, + + observe: function (subject, topic, data) { + switch (topic) { + case "xpcom-shutdown": + this.onShutdown(); + break; + case "nsPref:changed": + this.onPrefChanged(); + break; + } + }, + + onShutdown: function () { + Services.prefs.removeObserver(JSON_VIEW_PREF, observer); + Services.obs.removeObserver(observer, "xpcom-shutdown"); + }, + + onPrefChanged: function () { + if (this.isEnabled()) { + this.register(); + } else { + this.unregister(); + } + }, + + register: function () { + JsonViewSniffer.register(); + JsonViewService.register(); + }, + + unregister: function () { + JsonViewSniffer.unregister(); + JsonViewService.unregister(); + }, + + isEnabled: function () { + return Services.prefs.getBoolPref(JSON_VIEW_PREF); + }, +}; + +// Listen to JSON View 'enable' pref and perform dynamic +// registration or unregistration of the main application +// component. +var observer = new ConverterObserver(); +observer.initialize(); diff --git a/devtools/client/jsonview/converter-sniffer.js b/devtools/client/jsonview/converter-sniffer.js new file mode 100644 index 000000000..65e5d2aad --- /dev/null +++ b/devtools/client/jsonview/converter-sniffer.js @@ -0,0 +1,106 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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 {Cc, Ci, components} = require("chrome"); +const xpcom = require("sdk/platform/xpcom"); +const {Unknown} = require("sdk/platform/xpcom"); +const {Class} = require("sdk/core/heritage"); + +const categoryManager = Cc["@mozilla.org/categorymanager;1"] + .getService(Ci.nsICategoryManager); + +loader.lazyRequireGetter(this, "NetworkHelper", + "devtools/shared/webconsole/network-helper"); + +// Constants +const JSON_TYPE = "application/json"; +const CONTRACT_ID = "@mozilla.org/devtools/jsonview-sniffer;1"; +const CLASS_ID = "{4148c488-dca1-49fc-a621-2a0097a62422}"; +const JSON_VIEW_MIME_TYPE = "application/vnd.mozilla.json.view"; +const JSON_VIEW_TYPE = "JSON View"; +const CONTENT_SNIFFER_CATEGORY = "net-content-sniffers"; + +/** + * This component represents a sniffer (implements nsIContentSniffer + * interface) responsible for changing top level 'application/json' + * document types to: 'application/vnd.mozilla.json.view'. + * + * This internal type is consequently rendered by JSON View component + * that represents the JSON through a viewer interface. + */ +var Sniffer = Class({ + extends: Unknown, + + interfaces: [ + "nsIContentSniffer", + ], + + get wrappedJSObject() { + return this; + }, + + getMIMETypeFromContent: function (request, data, length) { + // JSON View is enabled only for top level loads only. + if (!NetworkHelper.isTopLevelLoad(request)) { + return ""; + } + + if (request instanceof Ci.nsIChannel) { + try { + if (request.contentDisposition == + Ci.nsIChannel.DISPOSITION_ATTACHMENT) { + return ""; + } + } catch (e) { + // Channel doesn't support content dispositions + } + + // Check the response content type and if it's application/json + // change it to new internal type consumed by JSON View. + if (request.contentType == JSON_TYPE) { + return JSON_VIEW_MIME_TYPE; + } + } + + return ""; + } +}); + +var service = xpcom.Service({ + id: components.ID(CLASS_ID), + contract: CONTRACT_ID, + Component: Sniffer, + register: false, + unregister: false +}); + +function register() { + if (!xpcom.isRegistered(service)) { + xpcom.register(service); + categoryManager.addCategoryEntry(CONTENT_SNIFFER_CATEGORY, JSON_VIEW_TYPE, + CONTRACT_ID, false, false); + return true; + } + + return false; +} + +function unregister() { + if (xpcom.isRegistered(service)) { + categoryManager.deleteCategoryEntry(CONTENT_SNIFFER_CATEGORY, + JSON_VIEW_TYPE, false); + xpcom.unregister(service); + return true; + } + return false; +} + +exports.JsonViewSniffer = { + register: register, + unregister: unregister +}; diff --git a/devtools/client/jsonview/css/general.css b/devtools/client/jsonview/css/general.css new file mode 100644 index 000000000..0c68d65e7 --- /dev/null +++ b/devtools/client/jsonview/css/general.css @@ -0,0 +1,46 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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/. */ + +/******************************************************************************/ +/* General */ + +body { + color: var(--theme-body-color); + background-color: var(--theme-body-background); + padding: 0; + margin: 0; + overflow-x: hidden; +} + +*:focus { + outline: none !important; +} + +#content { + height: 100%; +} + +pre { + background-color: white; + border: none; + font-family: var(--monospace-font-family); +} + +#json, +#headers { + display: none; +} + +/******************************************************************************/ +/* Dark Theme */ + +body.theme-dark { + color: var(--theme-body-color); + background-color: var(--theme-body-background); +} + +.theme-dark pre { + background-color: var(--theme-body-background); +} diff --git a/devtools/client/jsonview/css/headers-panel.css b/devtools/client/jsonview/css/headers-panel.css new file mode 100644 index 000000000..89cec46e0 --- /dev/null +++ b/devtools/client/jsonview/css/headers-panel.css @@ -0,0 +1,78 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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 Panel */ + +.headersPanelBox { + height: 100%; +} + +.headersPanelBox .netInfoHeadersTable { + overflow: auto; + height: 100%; +} + +.headersPanelBox .netHeadersGroup { + padding: 10px; +} + +.headersPanelBox td { + vertical-align: bottom; +} + +.headersPanelBox .netInfoHeadersGroup { + color: var(--theme-body-color-alt); + margin-bottom: 10px; + border-bottom: 1px solid var(--theme-splitter-color); + padding-top: 8px; + padding-bottom: 4px; + font-weight: bold; + -moz-user-select: none; +} + +.headersPanelBox .netInfoParamValue { + word-wrap: break-word; +} + +.headersPanelBox .netInfoParamName { + padding: 2px 10px 0 0; + font-weight: bold; + vertical-align: top; + text-align: right; + white-space: nowrap; +} + +/******************************************************************************/ +/* Theme colors have been generated/copied from Network Panel's header view */ + +/* Light Theme */ +.theme-light .netInfoParamName { + color: var(--theme-highlight-red); +} + +.theme-light .netInfoParamValue { + color: var(--theme-highlight-purple); +} + +/* Dark Theme */ +.theme-dark .netInfoParamName { + color: var(--theme-highlight-purple); +} + +.theme-dark .netInfoParamValue { + color: var(--theme-highlight-gray); +} + +/* Firebug Theme */ +.theme-firebug .netInfoHeadersTable { + font-family: Lucida Grande, Tahoma, sans-serif; + font-size: 11px; + line-height: 12px; +} + +.theme-firebug .netInfoParamValue { + font-family: var(--monospace-font-family); +} diff --git a/devtools/client/jsonview/css/json-panel.css b/devtools/client/jsonview/css/json-panel.css new file mode 100644 index 000000000..b107d34a0 --- /dev/null +++ b/devtools/client/jsonview/css/json-panel.css @@ -0,0 +1,16 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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/. */ + +/******************************************************************************/ +/* JSON Panel */ + +.jsonParseError { + font-size: 12px; + font-family: Lucida Grande, Tahoma, sans-serif; + line-height: 15px; + width: 100%; + padding: 10px; + color: red; +} diff --git a/devtools/client/jsonview/css/main.css b/devtools/client/jsonview/css/main.css new file mode 100644 index 000000000..04f3cb87c --- /dev/null +++ b/devtools/client/jsonview/css/main.css @@ -0,0 +1,59 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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 "resource://devtools/client/shared/components/reps/reps.css"; +@import "resource://devtools/client/shared/components/tree/tree-view.css"; +@import "resource://devtools/client/shared/components/tabs/tabs.css"; + +@import "general.css"; +@import "search-box.css"; +@import "toolbar.css"; +@import "json-panel.css"; +@import "text-panel.css"; +@import "headers-panel.css"; + +/******************************************************************************/ +/* Panel Content */ + +.panelContent { + overflow-y: auto; + width: 100%; +} + +/* The tree takes the entire horizontal space within the panel content. */ +.panelContent .treeTable { + width: 100%; + font-family: var(--monospace-font-family); +} + +:root[platform="linux"] .treeTable { + font-size: 80%; /* To handle big monospace font */ +} + +/* Make sure there is a little space between label and value columns. */ +.panelContent .treeTable .treeLabelCell { + padding-right: 17px; +} + +/******************************************************************************/ +/* Theme Firebug */ + +.theme-firebug .panelContent { + height: calc(100% - 30px); +} + +/* JSON View is using bigger font-size for the main tabs so, + let's overwrite the default value. */ +.theme-firebug .tabs .tabs-navigation { + font-size: 14px; +} + +/******************************************************************************/ +/* Theme Light & Theme Dark*/ + +.theme-dark .panelContent, +.theme-light .panelContent { + height: calc(100% - 27px); +} diff --git a/devtools/client/jsonview/css/moz.build b/devtools/client/jsonview/css/moz.build new file mode 100644 index 000000000..e881b3469 --- /dev/null +++ b/devtools/client/jsonview/css/moz.build @@ -0,0 +1,16 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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( + 'general.css', + 'headers-panel.css', + 'json-panel.css', + 'main.css', + 'search-box.css', + 'search.svg', + 'text-panel.css', + 'toolbar.css' +) diff --git a/devtools/client/jsonview/css/search-box.css b/devtools/client/jsonview/css/search-box.css new file mode 100644 index 000000000..99615b648 --- /dev/null +++ b/devtools/client/jsonview/css/search-box.css @@ -0,0 +1,24 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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 Box */ + +.searchBox { + height: 18px; + font: message-box; + background-color: var(--theme-body-background); + background-image: url("chrome://devtools/skin/images/filter.svg#filterinput"); + background-repeat: no-repeat; + background-position: 2px center; + border: 1px solid var(--theme-splitter-color); + border-radius: 2px; + color: var(--theme-content-color1); + width: 200px; + margin-top: 0; + margin-right: 1px; + float: right; + padding-left: 20px; +} diff --git a/devtools/client/jsonview/css/search.svg b/devtools/client/jsonview/css/search.svg new file mode 100644 index 000000000..53f2d3651 --- /dev/null +++ b/devtools/client/jsonview/css/search.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/devtools/client/jsonview/css/text-panel.css b/devtools/client/jsonview/css/text-panel.css new file mode 100644 index 000000000..99b238556 --- /dev/null +++ b/devtools/client/jsonview/css/text-panel.css @@ -0,0 +1,26 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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/. */ + +/******************************************************************************/ +/* Text Panel */ + +.textPanelBox { + height: 100%; +} + +.textPanelBox .data { + overflow: auto; + height: 100%; +} + +.textPanelBox pre { + margin: 0; + font-family: var(--monospace-font-family); + color: var(--theme-content-color1); +} + +:root[platform="linux"] .textPanelBox .data { + font-size: 80%; /* To handle big monospace font */ +} diff --git a/devtools/client/jsonview/css/toolbar.css b/devtools/client/jsonview/css/toolbar.css new file mode 100644 index 000000000..833b2119f --- /dev/null +++ b/devtools/client/jsonview/css/toolbar.css @@ -0,0 +1,92 @@ +/* vim:set ts=2 sw=2 sts=2 et: */ +/* 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 */ + +.toolbar { + line-height: 20px; + height: 22px; + font: message-box; + padding: 4px 0 3px 0; +} + +.toolbar .btn { + margin-left: 5px; + background-color: #E6E6E6; + border: 1px solid rgb(204, 204, 204); + text-decoration: none; + display: inline-block; + text-align: center; + white-space: nowrap; + vertical-align: middle; + cursor: pointer; + -moz-user-select: none; + padding: 0 2px; + border-radius: 2px; +} + +.toolbar .btn::-moz-focus-inner { + border: 1px solid transparent; +} + +/******************************************************************************/ +/* Firebug Theme */ + +.theme-firebug .toolbar { + border-bottom: 1px solid rgb(170, 188, 207); + background-color: var(--theme-tab-toolbar-background) !important; + background-image: linear-gradient(rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0.2)); +} + +.theme-firebug .toolbar .btn { + border-radius: 2px; + color: #141414; + background-color: white; +} + +.theme-firebug .toolbar .btn:hover { + color: #333; + background-color: #e6e6e6; + border-color: #adadad; +} + +.theme-firebug .toolbar .btn:active { + background-image: none; + outline: 0; + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); +} + +/******************************************************************************/ +/* Light Theme & Dark Theme*/ + +.theme-dark .toolbar, +.theme-light .toolbar { + background-color: var(--theme-toolbar-background); + border-bottom: 1px solid var(--theme-splitter-color); + padding: 1px; + padding-left: 2px; +} + +.theme-dark .toolbar .btn, +.theme-light .toolbar .btn { + min-height: 18px; + color: var(--theme-content-color1); + text-shadow: none; + margin: 1px 2px 1px 2px; + border: none; + background-color: rgba(170, 170, 170, .2); /* --toolbar-tab-hover */ + transition: background 0.05s ease-in-out; +} + +.theme-dark .toolbar .btn:hover, +.theme-light .toolbar .btn:hover { + background: rgba(170, 170, 170, .3); /* Splitters */ +} + +.theme-dark .toolbar .btn:not([disabled]):hover:active, +.theme-light .toolbar .btn:not([disabled]):hover:active { + background: rgba(170, 170, 170, .4); /* --toolbar-tab-hover-active */ +} diff --git a/devtools/client/jsonview/json-viewer.js b/devtools/client/jsonview/json-viewer.js new file mode 100644 index 000000000..d96081da2 --- /dev/null +++ b/devtools/client/jsonview/json-viewer.js @@ -0,0 +1,112 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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"; + +define(function (require, exports, module) { + const { render } = require("devtools/client/shared/vendor/react-dom"); + const { createFactories } = require("devtools/client/shared/components/reps/rep-utils"); + const { MainTabbedArea } = createFactories(require("./components/main-tabbed-area")); + + const json = document.getElementById("json"); + const headers = document.getElementById("headers"); + + let jsonData; + + try { + jsonData = JSON.parse(json.textContent); + } catch (err) { + jsonData = err + ""; + } + + // Application state object. + let input = { + jsonText: json.textContent, + jsonPretty: null, + json: jsonData, + headers: JSON.parse(headers.textContent), + tabActive: 0, + prettified: false + }; + + json.remove(); + headers.remove(); + + /** + * Application actions/commands. This list implements all commands + * available for the JSON viewer. + */ + input.actions = { + onCopyJson: function () { + dispatchEvent("copy", input.prettified ? input.jsonPretty : input.jsonText); + }, + + onSaveJson: function () { + dispatchEvent("save", input.prettified ? input.jsonPretty : input.jsonText); + }, + + onCopyHeaders: function () { + dispatchEvent("copy-headers", input.headers); + }, + + onSearch: function (value) { + theApp.setState({searchFilter: value}); + }, + + onPrettify: function (data) { + if (input.prettified) { + theApp.setState({jsonText: input.jsonText}); + } else { + if (!input.jsonPretty) { + input.jsonPretty = JSON.stringify(jsonData, null, " "); + } + theApp.setState({jsonText: input.jsonPretty}); + } + + input.prettified = !input.prettified; + }, + }; + + /** + * Helper for dispatching an event. It's handled in chrome scope. + * + * @param {String} type Event detail type + * @param {Object} value Event detail value + */ + function dispatchEvent(type, value) { + let data = { + detail: { + type, + value, + } + }; + + let contentMessageEvent = new CustomEvent("contentMessage", data); + window.dispatchEvent(contentMessageEvent); + } + + /** + * Render the main application component. It's the main tab bar displayed + * at the top of the window. This component also represents ReacJS root. + */ + let content = document.getElementById("content"); + let theApp = render(MainTabbedArea(input), content); + + let onResize = event => { + window.document.body.style.height = window.innerHeight + "px"; + window.document.body.style.width = window.innerWidth + "px"; + }; + + window.addEventListener("resize", onResize); + onResize(); + + // Send notification event to the window. Can be useful for + // tests as well as extensions. + let event = new CustomEvent("JSONViewInitialized", {}); + window.jsonViewInitialized = true; + window.dispatchEvent(event); +}); + diff --git a/devtools/client/jsonview/lib/moz.build b/devtools/client/jsonview/lib/moz.build new file mode 100644 index 000000000..fff9a99f9 --- /dev/null +++ b/devtools/client/jsonview/lib/moz.build @@ -0,0 +1,9 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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( + 'require.js' +) diff --git a/devtools/client/jsonview/lib/require.js b/devtools/client/jsonview/lib/require.js new file mode 100644 index 000000000..77a5bb1d3 --- /dev/null +++ b/devtools/client/jsonview/lib/require.js @@ -0,0 +1,2076 @@ +/** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.1.15 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/jrburke/requirejs for details + */ +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + +var requirejs, require, define; +(function (global) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.1.15', + commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + ap = Array.prototype, + apsp = ap.splice, + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), + isWebWorker = !isBrowser && typeof importScripts !== 'undefined', + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i == 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + //Array splice in the values since the context code has a + //local var ref to defQueue, so cannot just reassign the one + //on context. + apsp.apply(defQueue, + [defQueue.length, 0].concat(globalDefQueue)); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + this.fetch(); + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + req.onResourceLoad(context, this.map, this.depMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Allow plugins to load other code without having to know the + //context or how to 'complete' the load. + load.fromText = bind(this, function (text, textAlt) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if(args[0] === id) { + defQueue.splice(i, 1); + } + }); + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs ? url + + ((url.indexOf('?') === -1 ? '?' : '&') + + config.urlArgs) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + onScriptLoad: function (evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id])); + } + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if (node.attachEvent && + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/jrburke/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/jrburke/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. + useInteractive = true; + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); + } + node.src = url; + + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if (baseElement) { + head.insertBefore(node, baseElement); + } else { + head.appendChild(node); + } + currentlyAddingScript = null; + + return node; + } else if (isWebWorker) { + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation that a build has been done so that + //only one script needs to be loaded anyway. This may need to be + //reevaluated if other use cases become common. + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by + //using the script's parent. + if (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one. + if (!cfg.baseUrl) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + } + + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; + } + }); + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, '') + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); + }; + + define.amd = { + jQuery: true + }; + + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this)); diff --git a/devtools/client/jsonview/main.js b/devtools/client/jsonview/main.js new file mode 100644 index 000000000..a438e2e34 --- /dev/null +++ b/devtools/client/jsonview/main.js @@ -0,0 +1,62 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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/. */ +/* globals JsonViewUtils*/ + +"use strict"; + +const { Cu } = require("chrome"); +const Services = require("Services"); + +const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {}); + +XPCOMUtils.defineLazyGetter(this, "JsonViewUtils", function () { + return require("devtools/client/jsonview/utils"); +}); + +/** + * Singleton object that represents the JSON View in-content tool. + * It has the same lifetime as the browser. Initialization done by + * DevTools() object from devtools/client/framework/devtools.js + */ +var JsonView = { + initialize: function () { + // Load JSON converter module. This converter is responsible + // for handling 'application/json' documents and converting + // them into a simple web-app that allows easy inspection + // of the JSON data. + Services.ppmm.loadProcessScript( + "resource://devtools/client/jsonview/converter-observer.js", + true); + + this.onSaveListener = this.onSave.bind(this); + + // Register for messages coming from the child process. + Services.ppmm.addMessageListener( + "devtools:jsonview:save", this.onSaveListener); + }, + + destroy: function () { + Services.ppmm.removeMessageListener( + "devtools:jsonview:save", this.onSaveListener); + }, + + // Message handlers for events from child processes + + /** + * Save JSON to a file needs to be implemented here + * in the parent process. + */ + onSave: function (message) { + let value = message.data; + let file = JsonViewUtils.getTargetFile(); + if (file) { + JsonViewUtils.saveToFile(file, value); + } + } +}; + +// Exports from this module +module.exports.JsonView = JsonView; diff --git a/devtools/client/jsonview/moz.build b/devtools/client/jsonview/moz.build new file mode 100644 index 000000000..06a98ed9b --- /dev/null +++ b/devtools/client/jsonview/moz.build @@ -0,0 +1,23 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# 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 += [ + 'components', + 'css', + 'lib' +] + +DevToolsModules( + 'converter-child.js', + 'converter-observer.js', + 'converter-sniffer.js', + 'json-viewer.js', + 'main.js', + 'utils.js', + 'viewer-config.js' +) + +BROWSER_CHROME_MANIFESTS += ['test/browser.ini'] diff --git a/devtools/client/jsonview/test/.eslintrc.js b/devtools/client/jsonview/test/.eslintrc.js new file mode 100644 index 000000000..8d15a76d9 --- /dev/null +++ b/devtools/client/jsonview/test/.eslintrc.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = { + // Extend from the shared list of defined globals for mochitests. + "extends": "../../../.eslintrc.mochitests.js" +}; diff --git a/devtools/client/jsonview/test/array_json.json b/devtools/client/jsonview/test/array_json.json new file mode 100644 index 000000000..f91c3e08d --- /dev/null +++ b/devtools/client/jsonview/test/array_json.json @@ -0,0 +1 @@ +[{"name": "jan"},{"name": "honza"},{"name": "odvarko"}] diff --git a/devtools/client/jsonview/test/array_json.json^headers^ b/devtools/client/jsonview/test/array_json.json^headers^ new file mode 100644 index 000000000..6010bfd18 --- /dev/null +++ b/devtools/client/jsonview/test/array_json.json^headers^ @@ -0,0 +1 @@ +Content-Type: application/json; charset=utf-8 diff --git a/devtools/client/jsonview/test/browser.ini b/devtools/client/jsonview/test/browser.ini new file mode 100644 index 000000000..14f640c8c --- /dev/null +++ b/devtools/client/jsonview/test/browser.ini @@ -0,0 +1,28 @@ +[DEFAULT] +tags = devtools +subsuite = devtools +support-files = + array_json.json + array_json.json^headers^ + doc_frame_script.js + head.js + invalid_json.json + invalid_json.json^headers^ + simple_json.json + simple_json.json^headers^ + valid_json.json + valid_json.json^headers^ + !/devtools/client/commandline/test/head.js + !/devtools/client/framework/test/head.js + !/devtools/client/framework/test/shared-head.js + +[browser_jsonview_copy_headers.js] +subsuite = clipboard +[browser_jsonview_copy_json.js] +subsuite = clipboard +[browser_jsonview_copy_rawdata.js] +subsuite = clipboard +[browser_jsonview_filter.js] +[browser_jsonview_invalid_json.js] +[browser_jsonview_valid_json.js] +[browser_jsonview_save_json.js] diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_headers.js b/devtools/client/jsonview/test/browser_jsonview_copy_headers.js new file mode 100644 index 000000000..1ffe9f8ca --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_copy_headers.js @@ -0,0 +1,35 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "valid_json.json"; + +add_task(function* () { + info("Test valid JSON started"); + + yield addJsonViewTab(TEST_JSON_URL); + + // Select the RawData tab + yield selectJsonViewContentTab("headers"); + + // Check displayed headers + let count = yield getElementCount(".headersPanelBox .netHeadersGroup"); + is(count, 2, "There must be two header groups"); + + let text = yield getElementText(".headersPanelBox .netInfoHeadersTable"); + isnot(text, "", "Headers text must not be empty"); + + let browser = gBrowser.selectedBrowser; + + // Verify JSON copy into the clipboard. + yield waitForClipboardPromise(function setup() { + BrowserTestUtils.synthesizeMouseAtCenter( + ".headersPanelBox .toolbar button.copy", + {}, browser); + }, function validator(value) { + return value.indexOf("application/json") > 0; + }); +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_json.js b/devtools/client/jsonview/test/browser_jsonview_copy_json.js new file mode 100644 index 000000000..b4c08b843 --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_copy_json.js @@ -0,0 +1,31 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "simple_json.json"; + +add_task(function* () { + info("Test copy JSON started"); + + yield addJsonViewTab(TEST_JSON_URL); + + let countBefore = yield getElementCount(".jsonPanelBox .treeTable .treeRow"); + ok(countBefore == 1, "There must be one row"); + + let text = yield getElementText(".jsonPanelBox .treeTable .treeRow"); + is(text, "name\"value\"", "There must be proper JSON displayed"); + + // Verify JSON copy into the clipboard. + let value = "{\"name\": \"value\"}\n"; + let browser = gBrowser.selectedBrowser; + let selector = ".jsonPanelBox .toolbar button.copy"; + yield waitForClipboardPromise(function setup() { + BrowserTestUtils.synthesizeMouseAtCenter(selector, {}, browser); + }, function validator(result) { + let str = normalizeNewLines(result); + return str == value; + }); +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js b/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js new file mode 100644 index 000000000..d2346ea42 --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_copy_rawdata.js @@ -0,0 +1,53 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "simple_json.json"; + +let jsonText = "{\"name\": \"value\"}\n"; +let prettyJson = "{\n \"name\": \"value\"\n}"; + +add_task(function* () { + info("Test copy raw data started"); + + yield addJsonViewTab(TEST_JSON_URL); + + // Select the RawData tab + yield selectJsonViewContentTab("rawdata"); + + // Check displayed JSON + let text = yield getElementText(".textPanelBox .data"); + is(text, jsonText, "Proper JSON must be displayed in DOM"); + + let browser = gBrowser.selectedBrowser; + + // Verify JSON copy into the clipboard. + yield waitForClipboardPromise(function setup() { + BrowserTestUtils.synthesizeMouseAtCenter( + ".textPanelBox .toolbar button.copy", + {}, browser); + }, jsonText); + + // Click 'Pretty Print' button + yield BrowserTestUtils.synthesizeMouseAtCenter( + ".textPanelBox .toolbar button.prettyprint", + {}, browser); + + let prettyText = yield getElementText(".textPanelBox .data"); + prettyText = normalizeNewLines(prettyText); + ok(prettyText.startsWith(prettyJson), + "Pretty printed JSON must be displayed"); + + // Verify JSON copy into the clipboard. + yield waitForClipboardPromise(function setup() { + BrowserTestUtils.synthesizeMouseAtCenter( + ".textPanelBox .toolbar button.copy", + {}, browser); + }, function validator(value) { + let str = normalizeNewLines(value); + return str == prettyJson; + }); +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_filter.js b/devtools/client/jsonview/test/browser_jsonview_filter.js new file mode 100644 index 000000000..5e87bb8ae --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_filter.js @@ -0,0 +1,28 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "array_json.json"; + +add_task(function* () { + info("Test valid JSON started"); + + yield addJsonViewTab(TEST_JSON_URL); + + let count = yield getElementCount(".jsonPanelBox .treeTable .treeRow"); + is(count, 6, "There must be expected number of rows"); + + // XXX use proper shortcut to focus the filter box + // as soon as bug Bug 1178771 is fixed. + yield sendString("h", ".jsonPanelBox .searchBox"); + + // The filtering is done asynchronously so, we need to wait. + yield waitForFilter(); + + let hiddenCount = yield getElementCount( + ".jsonPanelBox .treeTable .treeRow.hidden"); + is(hiddenCount, 4, "There must be expected number of hidden rows"); +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_invalid_json.js b/devtools/client/jsonview/test/browser_jsonview_invalid_json.js new file mode 100644 index 000000000..de3cbd74d --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_invalid_json.js @@ -0,0 +1,20 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "invalid_json.json"; + +add_task(function* () { + info("Test invalid JSON started"); + + yield addJsonViewTab(TEST_JSON_URL); + + let count = yield getElementCount(".jsonPanelBox .treeTable .treeRow"); + ok(count == 0, "There must be no row"); + + let text = yield getElementText(".jsonPanelBox .jsonParseError"); + ok(text, "There must be an error description"); +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_save_json.js b/devtools/client/jsonview/test/browser_jsonview_save_json.js new file mode 100644 index 000000000..4b95c563f --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_save_json.js @@ -0,0 +1,38 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "valid_json.json"; + +let { MockFilePicker } = SpecialPowers; + +MockFilePicker.init(window); +MockFilePicker.returnValue = MockFilePicker.returnCancel; + +registerCleanupFunction(function () { + MockFilePicker.cleanup(); +}); + +add_task(function* () { + info("Test save JSON started"); + + yield addJsonViewTab(TEST_JSON_URL); + + let promise = new Promise((resolve) => { + MockFilePicker.showCallback = () => { + MockFilePicker.showCallback = null; + ok(true, "File picker was opened"); + resolve(); + }; + }); + + let browser = gBrowser.selectedBrowser; + yield BrowserTestUtils.synthesizeMouseAtCenter( + ".jsonPanelBox button.save", + {}, browser); + + yield promise; +}); diff --git a/devtools/client/jsonview/test/browser_jsonview_valid_json.js b/devtools/client/jsonview/test/browser_jsonview_valid_json.js new file mode 100644 index 000000000..83d0e1088 --- /dev/null +++ b/devtools/client/jsonview/test/browser_jsonview_valid_json.js @@ -0,0 +1,33 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_JSON_URL = URL_ROOT + "valid_json.json"; + +add_task(function* () { + info("Test valid JSON started"); + + let tab = yield addJsonViewTab(TEST_JSON_URL); + + ok(tab.linkedBrowser.contentPrincipal.isNullPrincipal, "Should have null principal"); + + let countBefore = yield getElementCount(".jsonPanelBox .treeTable .treeRow"); + ok(countBefore == 3, "There must be three rows"); + + let objectCellCount = yield getElementCount( + ".jsonPanelBox .treeTable .objectCell"); + ok(objectCellCount == 1, "There must be one object cell"); + + let objectCellText = yield getElementText( + ".jsonPanelBox .treeTable .objectCell"); + ok(objectCellText == "", "The summary is hidden when object is expanded"); + + // Collapsed auto-expanded node. + yield clickJsonNode(".jsonPanelBox .treeTable .treeLabel"); + + let countAfter = yield getElementCount(".jsonPanelBox .treeTable .treeRow"); + ok(countAfter == 1, "There must be one row"); +}); diff --git a/devtools/client/jsonview/test/doc_frame_script.js b/devtools/client/jsonview/test/doc_frame_script.js new file mode 100644 index 000000000..3d19b3433 --- /dev/null +++ b/devtools/client/jsonview/test/doc_frame_script.js @@ -0,0 +1,98 @@ +/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* globals Services, sendAsyncMessage, addMessageListener */ + +// XXX Some helper API could go to: +// testing/mochitest/tests/SimpleTest/AsyncContentUtils.js +// (or at least to share test API in devtools) + +// Set up a dummy environment so that EventUtils works. We need to be careful to +// pass a window object into each EventUtils method we call rather than having +// it rely on the |window| global. +let EventUtils = {}; +EventUtils.window = content; +EventUtils.parent = EventUtils.window; +EventUtils._EU_Ci = Components.interfaces; // eslint-disable-line +EventUtils._EU_Cc = Components.classes; // eslint-disable-line +EventUtils.navigator = content.navigator; +EventUtils.KeyboardEvent = content.KeyboardEvent; + +Services.scriptloader.loadSubScript( + "chrome://mochikit/content/tests/SimpleTest/EventUtils.js", EventUtils); + +/** + * When the JSON View is done rendering it triggers custom event + * "JSONViewInitialized", then the Test:TestPageProcessingDone message + * will be sent to the parent process for tests to wait for this event + * if needed. + */ +content.addEventListener("JSONViewInitialized", () => { + sendAsyncMessage("Test:JsonView:JSONViewInitialized"); +}, false); + +addMessageListener("Test:JsonView:GetElementCount", function (msg) { + let {selector} = msg.data; + let nodeList = content.document.querySelectorAll(selector); + sendAsyncMessage(msg.name, {count: nodeList.length}); +}); + +addMessageListener("Test:JsonView:GetElementText", function (msg) { + let {selector} = msg.data; + let element = content.document.querySelector(selector); + let text = element ? element.textContent : null; + sendAsyncMessage(msg.name, {text: text}); +}); + +addMessageListener("Test:JsonView:FocusElement", function (msg) { + let {selector} = msg.data; + let element = content.document.querySelector(selector); + if (element) { + element.focus(); + } + sendAsyncMessage(msg.name); +}); + +addMessageListener("Test:JsonView:SendString", function (msg) { + let {selector, str} = msg.data; + if (selector) { + let element = content.document.querySelector(selector); + if (element) { + element.focus(); + } + } + + EventUtils.sendString(str, content); + + sendAsyncMessage(msg.name); +}); + +addMessageListener("Test:JsonView:WaitForFilter", function (msg) { + let firstRow = content.document.querySelector( + ".jsonPanelBox .treeTable .treeRow"); + + // Check if the filter is already set. + if (firstRow.classList.contains("hidden")) { + sendAsyncMessage(msg.name); + return; + } + + // Wait till the first row has 'hidden' class set. + let observer = new content.MutationObserver(function (mutations) { + for (let i = 0; i < mutations.length; i++) { + let mutation = mutations[i]; + if (mutation.attributeName == "class") { + if (firstRow.classList.contains("hidden")) { + observer.disconnect(); + sendAsyncMessage(msg.name); + break; + } + } + } + }); + + observer.observe(firstRow, { attributes: true }); +}); diff --git a/devtools/client/jsonview/test/head.js b/devtools/client/jsonview/test/head.js new file mode 100644 index 000000000..b71883e67 --- /dev/null +++ b/devtools/client/jsonview/test/head.js @@ -0,0 +1,145 @@ +/* vim: set ts=2 et sw=2 tw=80: */ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ +/* eslint no-unused-vars: [2, {"vars": "local", "args": "none"}] */ +/* import-globals-from ../../framework/test/shared-head.js */ +/* import-globals-from ../../framework/test/head.js */ + +"use strict"; + +// shared-head.js handles imports, constants, and utility functions +Services.scriptloader.loadSubScript( + "chrome://mochitests/content/browser/devtools/client/framework/test/head.js", this); + +const JSON_VIEW_PREF = "devtools.jsonview.enabled"; + +// Enable JSON View for the test +Services.prefs.setBoolPref(JSON_VIEW_PREF, true); + +registerCleanupFunction(() => { + Services.prefs.clearUserPref(JSON_VIEW_PREF); +}); + +// XXX move some API into devtools/framework/test/shared-head.js + +/** + * Add a new test tab in the browser and load the given url. + * @param {String} url The url to be loaded in the new tab + * @return a promise that resolves to the tab object when the url is loaded + */ +function addJsonViewTab(url) { + info("Adding a new JSON tab with URL: '" + url + "'"); + + let deferred = promise.defer(); + addTab(url).then(tab => { + let browser = tab.linkedBrowser; + + // Load devtools/shared/frame-script-utils.js + getFrameScript(); + + // Load frame script with helpers for JSON View tests. + let rootDir = getRootDirectory(gTestPath); + let frameScriptUrl = rootDir + "doc_frame_script.js"; + browser.messageManager.loadFrameScript(frameScriptUrl, false); + + // Resolve if the JSONView is fully loaded or wait + // for an initialization event. + if (content.window.wrappedJSObject.jsonViewInitialized) { + deferred.resolve(tab); + } else { + waitForContentMessage("Test:JsonView:JSONViewInitialized").then(() => { + deferred.resolve(tab); + }); + } + }); + + return deferred.promise; +} + +/** + * Expanding a node in the JSON tree + */ +function clickJsonNode(selector) { + info("Expanding node: '" + selector + "'"); + + let browser = gBrowser.selectedBrowser; + return BrowserTestUtils.synthesizeMouseAtCenter(selector, {}, browser); +} + +/** + * Select JSON View tab (in the content). + */ +function selectJsonViewContentTab(name) { + info("Selecting tab: '" + name + "'"); + + let browser = gBrowser.selectedBrowser; + let selector = ".tabs-menu .tabs-menu-item." + name + " a"; + return BrowserTestUtils.synthesizeMouseAtCenter(selector, {}, browser); +} + +function getElementCount(selector) { + info("Get element count: '" + selector + "'"); + + let data = { + selector: selector + }; + + return executeInContent("Test:JsonView:GetElementCount", data) + .then(result => { + return result.count; + }); +} + +function getElementText(selector) { + info("Get element text: '" + selector + "'"); + + let data = { + selector: selector + }; + + return executeInContent("Test:JsonView:GetElementText", data) + .then(result => { + return result.text; + }); +} + +function focusElement(selector) { + info("Focus element: '" + selector + "'"); + + let data = { + selector: selector + }; + + return executeInContent("Test:JsonView:FocusElement", data); +} + +/** + * Send the string aStr to the focused element. + * + * For now this method only works for ASCII characters and emulates the shift + * key state on US keyboard layout. + */ +function sendString(str, selector) { + info("Send string: '" + str + "'"); + + let data = { + selector: selector, + str: str + }; + + return executeInContent("Test:JsonView:SendString", data); +} + +function waitForTime(delay) { + let deferred = promise.defer(); + setTimeout(deferred.resolve, delay); + return deferred.promise; +} + +function waitForFilter() { + return executeInContent("Test:JsonView:WaitForFilter"); +} + +function normalizeNewLines(value) { + return value.replace("(\r\n|\n)", "\n"); +} diff --git a/devtools/client/jsonview/test/invalid_json.json b/devtools/client/jsonview/test/invalid_json.json new file mode 100644 index 000000000..004e1e203 --- /dev/null +++ b/devtools/client/jsonview/test/invalid_json.json @@ -0,0 +1 @@ +{,} diff --git a/devtools/client/jsonview/test/invalid_json.json^headers^ b/devtools/client/jsonview/test/invalid_json.json^headers^ new file mode 100644 index 000000000..6010bfd18 --- /dev/null +++ b/devtools/client/jsonview/test/invalid_json.json^headers^ @@ -0,0 +1 @@ +Content-Type: application/json; charset=utf-8 diff --git a/devtools/client/jsonview/test/simple_json.json b/devtools/client/jsonview/test/simple_json.json new file mode 100644 index 000000000..831dfbcfb --- /dev/null +++ b/devtools/client/jsonview/test/simple_json.json @@ -0,0 +1 @@ +{"name": "value"} diff --git a/devtools/client/jsonview/test/simple_json.json^headers^ b/devtools/client/jsonview/test/simple_json.json^headers^ new file mode 100644 index 000000000..6010bfd18 --- /dev/null +++ b/devtools/client/jsonview/test/simple_json.json^headers^ @@ -0,0 +1 @@ +Content-Type: application/json; charset=utf-8 diff --git a/devtools/client/jsonview/test/valid_json.json b/devtools/client/jsonview/test/valid_json.json new file mode 100644 index 000000000..ca7356ccd --- /dev/null +++ b/devtools/client/jsonview/test/valid_json.json @@ -0,0 +1,6 @@ +{ + "family": { + "father": "John Doe", + "mother": "Alice Doe" + } +} diff --git a/devtools/client/jsonview/test/valid_json.json^headers^ b/devtools/client/jsonview/test/valid_json.json^headers^ new file mode 100644 index 000000000..6010bfd18 --- /dev/null +++ b/devtools/client/jsonview/test/valid_json.json^headers^ @@ -0,0 +1 @@ +Content-Type: application/json; charset=utf-8 diff --git a/devtools/client/jsonview/utils.js b/devtools/client/jsonview/utils.js new file mode 100644 index 000000000..a70afdc68 --- /dev/null +++ b/devtools/client/jsonview/utils.js @@ -0,0 +1,101 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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 { Cu, Cc, Ci } = require("chrome"); +const Services = require("Services"); +const { getMostRecentBrowserWindow } = require("sdk/window/utils"); + +const OPEN_FLAGS = { + RDONLY: parseInt("0x01", 16), + WRONLY: parseInt("0x02", 16), + CREATE_FILE: parseInt("0x08", 16), + APPEND: parseInt("0x10", 16), + TRUNCATE: parseInt("0x20", 16), + EXCL: parseInt("0x80", 16) +}; + +/** + * Open File Save As dialog and let the user to pick proper file location. + */ +exports.getTargetFile = function () { + let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); + + let win = getMostRecentBrowserWindow(); + fp.init(win, null, Ci.nsIFilePicker.modeSave); + fp.appendFilter("JSON Files", "*.json; *.jsonp;"); + fp.appendFilters(Ci.nsIFilePicker.filterText); + fp.appendFilters(Ci.nsIFilePicker.filterAll); + fp.filterIndex = 0; + + let rv = fp.show(); + if (rv == Ci.nsIFilePicker.returnOK || rv == Ci.nsIFilePicker.returnReplace) { + return fp.file; + } + + return null; +}; + +/** + * Save JSON to a file + */ +exports.saveToFile = function (file, jsonString) { + let foStream = Cc["@mozilla.org/network/file-output-stream;1"] + .createInstance(Ci.nsIFileOutputStream); + + // write, create, truncate + let openFlags = OPEN_FLAGS.WRONLY | OPEN_FLAGS.CREATE_FILE | + OPEN_FLAGS.TRUNCATE; + + let permFlags = parseInt("0666", 8); + foStream.init(file, openFlags, permFlags, 0); + + let converter = Cc["@mozilla.org/intl/converter-output-stream;1"] + .createInstance(Ci.nsIConverterOutputStream); + + converter.init(foStream, "UTF-8", 0, 0); + + // The entire jsonString can be huge so, write the data in chunks. + let chunkLength = 1024 * 1204; + for (let i = 0; i <= jsonString.length; i++) { + let data = jsonString.substr(i, chunkLength + 1); + if (data) { + converter.writeString(data); + } + i = i + chunkLength; + } + + // this closes foStream + converter.close(); +}; + +/** + * Get the current theme from preferences. + */ +exports.getCurrentTheme = function () { + return Services.prefs.getCharPref("devtools.theme"); +}; + +/** + * Export given object into the target window scope. + */ +exports.exportIntoContentScope = function (win, obj, defineAs) { + let clone = Cu.createObjectIn(win, { + defineAs: defineAs + }); + + let props = Object.getOwnPropertyNames(obj); + for (let i = 0; i < props.length; i++) { + let propName = props[i]; + let propValue = obj[propName]; + if (typeof propValue == "function") { + Cu.exportFunction(propValue, clone, { + defineAs: propName + }); + } + } +}; diff --git a/devtools/client/jsonview/viewer-config.js b/devtools/client/jsonview/viewer-config.js new file mode 100644 index 000000000..b5ffbe34d --- /dev/null +++ b/devtools/client/jsonview/viewer-config.js @@ -0,0 +1,39 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript ts=2 et sw=2 tw=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/. */ +/* global requirejs */ + +"use strict"; + +/** + * RequireJS configuration for JSON Viewer. + * + * ReactJS library is shared among DevTools. Both, the minified (production) + * version and developer versions of the library are available. + * + * In order to use the developer version you need to specify the following + * in your .mozconfig (see also bug 1181646): + * ac_add_options --enable-debug-js-modules + * + * The path mapping uses paths fallback (a feature supported by RequireJS) + * See also: http://requirejs.org/docs/api.html#pathsfallbacks + * + * React module ID is using exactly the same (relative) path as the rest + * of the code base, so it's consistent and modules can be easily reused. + */ +require.config({ + baseUrl: ".", + paths: { + "devtools/client/shared": "resource://devtools/client/shared", + "devtools/shared": "resource://devtools/shared", + "devtools/client/shared/vendor/react": [ + "resource://devtools/client/shared/vendor/react-dev", + "resource://devtools/client/shared/vendor/react" + ], + } +}); + +// Load the main panel module +requirejs(["json-viewer"]); -- cgit v1.2.3