--- a/devtools/.eslintrc
+++ b/devtools/.eslintrc
@@ -324,18 +324,19 @@
// Deprecated, will be removed in 1.0.
"space-after-function-name": 0,
// Require a space around all keywords.
"keyword-spacing": 2,
// Require a space before the start brace of a block.
"space-before-blocks": [2, "always"],
// Deprecated, will be removed in 1.0.
"space-before-function-parentheses": 0,
- // Disallow space before function opening parenthesis.
- "space-before-function-paren": [2, "never"],
+ // Require space after keyword for anonymous functions, but disallow space
+ // after name of named functions.
+ "space-before-function-paren": [2, {"anonymous": "always", "named": "never"}],
// Disable the rule that checks if spaces inside {} and [] are there or not.
// Our code is split on conventions, and it'd be nice to have 2 rules
// instead, one for [] and one for {}. So, disabling until we write them.
"space-in-brackets": 0,
// Disallow spaces inside parentheses.
"space-in-parens": [2, "never"],
// Require spaces around operators, except for a|0.
"space-infix-ops": [2, {"int32Hint": true}],
--- a/devtools/client/aboutdebugging/modules/worker.js
+++ b/devtools/client/aboutdebugging/modules/worker.js
@@ -16,17 +16,17 @@ loader.lazyRequireGetter(this, "Toolbox"
/**
* Open a window-hosted toolbox to debug the worker associated to the provided
* worker actor.
*
* @param {DebuggerClient} client
* @param {Object} workerActor
* worker actor form to debug
*/
-exports.debugWorker = function(client, workerActor) {
+exports.debugWorker = function (client, workerActor) {
client.attachWorker(workerActor, (response, workerClient) => {
let workerTarget = TargetFactory.forWorker(workerClient);
gDevTools.showToolbox(workerTarget, "jsdebugger", Toolbox.HostType.WINDOW)
.then(toolbox => {
toolbox.once("destroy", () => workerClient.detach());
});
});
};
--- a/devtools/client/aboutdebugging/test/browser_addons_debug_bootstrapped.js
+++ b/devtools/client/aboutdebugging/test/browser_addons_debug_bootstrapped.js
@@ -42,17 +42,17 @@ add_task(function* () {
done();
}, "addon-console-works", false);
});
// Be careful, this JS function is going to be executed in the addon toolbox,
// which lives in another process. So do not try to use any scope variable!
let env = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
- let testScript = function() {
+ let testScript = function () {
/* eslint-disable no-undef */
toolbox.selectTool("webconsole")
.then(console => {
let { jsterm } = console.hud;
return jsterm.execute("myBootstrapAddonFunction()");
})
.then(() => toolbox.destroy());
/* eslint-enable no-undef */
--- a/devtools/client/aboutdebugging/test/browser_addons_reload.js
+++ b/devtools/client/aboutdebugging/test/browser_addons_reload.js
@@ -7,17 +7,17 @@ const ADDON_NAME = "test-devtools";
/**
* Returns a promise that resolves when the given add-on event is fired. The
* resolved value is an array of arguments passed for the event.
*/
function promiseAddonEvent(event) {
return new Promise(resolve => {
let listener = {
- [event]: function(...args) {
+ [event]: function (...args) {
AddonManager.removeAddonListener(listener);
resolve(args);
}
};
AddonManager.addAddonListener(listener);
});
}
--- a/devtools/client/aboutdebugging/test/browser_service_workers.js
+++ b/devtools/client/aboutdebugging/test/browser_service_workers.js
@@ -36,24 +36,24 @@ add_task(function* () {
ok(names.includes(SERVICE_WORKER),
"The service worker url appears in the list: " + names);
// Finally, unregister the service worker itself
let aboutDebuggingUpdate = waitForMutation(serviceWorkersElement,
{ childList: true });
// Use message manager to work with e10s
- let frameScript = function() {
+ let frameScript = function () {
// Retrieve the `sw` promise created in the html page
let { sw } = content.wrappedJSObject;
- sw.then(function(registration) {
- registration.unregister().then(function() {
+ sw.then(function (registration) {
+ registration.unregister().then(function () {
sendAsyncMessage("sw-unregistered");
},
- function(e) {
+ function (e) {
dump("SW not unregistered; " + e + "\n");
});
});
};
let mm = swTab.linkedBrowser.messageManager;
mm.loadFrameScript("data:,(" + encodeURIComponent(frameScript) + ")()", true);
yield new Promise(done => {
--- a/devtools/client/aboutdebugging/test/browser_service_workers_push.js
+++ b/devtools/client/aboutdebugging/test/browser_service_workers_push.js
@@ -32,19 +32,19 @@ add_task(function* () {
// Listen for mutations in the service-workers list.
let serviceWorkersElement = getServiceWorkerList(document);
let onMutation = waitForMutation(serviceWorkersElement, { childList: true });
// Open a tab that registers a push service worker.
let swTab = yield addTab(TAB_URL);
info("Make the test page notify us when the service worker sends a message.");
- let frameScript = function() {
+ let frameScript = function () {
let win = content.wrappedJSObject;
- win.navigator.serviceWorker.addEventListener("message", function(event) {
+ win.navigator.serviceWorker.addEventListener("message", function (event) {
sendAsyncMessage(event.data);
}, false);
};
let mm = swTab.linkedBrowser.messageManager;
mm.loadFrameScript("data:,(" + encodeURIComponent(frameScript) + ")()", true);
// Expect the service worker to claim the test window when activating.
let onClaimed = new Promise(done => {
--- a/devtools/client/aboutdebugging/test/browser_service_workers_timeout.js
+++ b/devtools/client/aboutdebugging/test/browser_service_workers_timeout.js
@@ -43,17 +43,17 @@ add_task(function* () {
let name = names.filter(element => element.textContent === SERVICE_WORKER)[0];
ok(name, "Found the service worker in the list");
let targetElement = name.parentNode.parentNode;
let debugBtn = targetElement.querySelector(".debug-button");
ok(debugBtn, "Found its debug button");
// Click on it and wait for the toolbox to be ready
let onToolboxReady = new Promise(done => {
- gDevTools.once("toolbox-ready", function(e, toolbox) {
+ gDevTools.once("toolbox-ready", function (e, toolbox) {
done(toolbox);
});
});
debugBtn.click();
let toolbox = yield onToolboxReady;
// Wait for more than the regular timeout,
--- a/devtools/client/aboutdebugging/test/head.js
+++ b/devtools/client/aboutdebugging/test/head.js
@@ -150,17 +150,17 @@ function* installAddon(document, path, n
function* uninstallAddon(document, addonId, addonName) {
let addonList = getAddonList(document);
let addonListMutation = waitForMutation(addonList, { childList: true });
// Now uninstall this addon
yield new Promise(done => {
AddonManager.getAddonByID(addonId, addon => {
let listener = {
- onUninstalled: function(uninstalledAddon) {
+ onUninstalled: function (uninstalledAddon) {
if (uninstalledAddon != addon) {
return;
}
AddonManager.removeAddonListener(listener);
done();
}
};
@@ -236,20 +236,20 @@ function assertHasTarget(expected, docum
/**
* Returns a promise that will resolve after the service worker in the page
* has successfully registered itself.
* @param {Tab} tab
*/
function waitForServiceWorkerRegistered(tab) {
// Make the test page notify us when the service worker is registered.
- let frameScript = function() {
+ let frameScript = function () {
// Retrieve the `sw` promise created in the html page.
let { sw } = content.wrappedJSObject;
- sw.then(function(registration) {
+ sw.then(function (registration) {
sendAsyncMessage("sw-registered");
});
};
let mm = tab.linkedBrowser.messageManager;
mm.loadFrameScript("data:,(" + encodeURIComponent(frameScript) + ")()", true);
return new Promise(done => {
mm.addMessageListener("sw-registered", function listener() {
@@ -261,24 +261,24 @@ function waitForServiceWorkerRegistered(
/**
* Asks the service worker within the test page to unregister, and returns a
* promise that will resolve when it has successfully unregistered itself.
* @param {Tab} tab
*/
function unregisterServiceWorker(tab) {
// Use message manager to work with e10s.
- let frameScript = function() {
+ let frameScript = function () {
// Retrieve the `sw` promise created in the html page.
let { sw } = content.wrappedJSObject;
- sw.then(function(registration) {
- registration.unregister().then(function() {
+ sw.then(function (registration) {
+ registration.unregister().then(function () {
sendAsyncMessage("sw-unregistered");
},
- function(e) {
+ function (e) {
dump("SW not unregistered; " + e + "\n");
});
});
};
let mm = tab.linkedBrowser.messageManager;
mm.loadFrameScript("data:,(" + encodeURIComponent(frameScript) + ")()", true);
return new Promise(done => {
--- a/devtools/client/aboutdebugging/test/service-workers/empty-sw.html
+++ b/devtools/client/aboutdebugging/test/service-workers/empty-sw.html
@@ -5,18 +5,18 @@
<title>Service worker test</title>
</head>
<body>
<script type="text/javascript">
"use strict";
var sw = navigator.serviceWorker.register("empty-sw.js");
sw.then(
- function() {
+ function () {
dump("SW registered\n");
},
- function(e) {
+ function (e) {
dump("SW not registered: " + e + "\n");
}
);
</script>
</body>
</html>
--- a/devtools/client/aboutdebugging/test/service-workers/push-sw.html
+++ b/devtools/client/aboutdebugging/test/service-workers/push-sw.html
@@ -4,18 +4,18 @@
<meta charset="UTF-8">
<title>Service worker push test</title>
</head>
<body>
<script type="text/javascript">
"use strict";
var sw = navigator.serviceWorker.register("push-sw.js");
sw.then(
- function(registration) {
+ function (registration) {
dump("SW registered\n");
},
- function(error) {
+ function (error) {
dump("SW not registered: " + error + "\n");
}
);
</script>
</body>
</html>
--- a/devtools/client/aboutdebugging/test/service-workers/push-sw.js
+++ b/devtools/client/aboutdebugging/test/service-workers/push-sw.js
@@ -3,31 +3,31 @@
/* eslint-env worker */
/* global clients */
"use strict";
// Send a message to all controlled windows.
function postMessage(message) {
- return clients.matchAll().then(function(clientlist) {
- clientlist.forEach(function(client) {
+ return clients.matchAll().then(function (clientlist) {
+ clientlist.forEach(function (client) {
client.postMessage(message);
});
});
}
// Don't wait for the next page load to become the active service worker.
-self.addEventListener("install", function(event) {
+self.addEventListener("install", function (event) {
event.waitUntil(self.skipWaiting());
});
// Claim control over the currently open test page when activating.
-self.addEventListener("activate", function(event) {
- event.waitUntil(self.clients.claim().then(function() {
+self.addEventListener("activate", function (event) {
+ event.waitUntil(self.clients.claim().then(function () {
return postMessage("sw-claimed");
}));
});
// Forward all "push" events to the controlled window.
-self.addEventListener("push", function(event) {
+self.addEventListener("push", function (event) {
event.waitUntil(postMessage("sw-pushed"));
});
--- a/devtools/client/animationinspector/animation-controller.js
+++ b/devtools/client/animationinspector/animation-controller.js
@@ -187,34 +187,34 @@ var AnimationsController = {
if (this.animationsFront) {
this.animationsFront.destroy();
this.animationsFront = null;
}
this.destroyed.resolve();
}),
- startListeners: function() {
+ startListeners: function () {
// Re-create the list of players when a new node is selected, except if the
// sidebar isn't visible.
gInspector.selection.on("new-node-front", this.onNewNodeFront);
gInspector.sidebar.on("select", this.onPanelVisibilityChange);
gToolbox.on("select", this.onPanelVisibilityChange);
},
- stopListeners: function() {
+ stopListeners: function () {
gInspector.selection.off("new-node-front", this.onNewNodeFront);
gInspector.sidebar.off("select", this.onPanelVisibilityChange);
gToolbox.off("select", this.onPanelVisibilityChange);
if (this.isListeningToMutations) {
this.animationsFront.off("mutations", this.onAnimationMutations);
}
},
- isPanelVisible: function() {
+ isPanelVisible: function () {
return gToolbox.currentToolId === "inspector" &&
gInspector.sidebar &&
gInspector.sidebar.getCurrentTabID() == "animationinspector";
},
onPanelVisibilityChange: Task.async(function* () {
if (this.isPanelVisible()) {
this.onNewNodeFront();
@@ -243,17 +243,17 @@ var AnimationsController = {
this.emit(this.PLAYERS_UPDATED_EVENT, this.animationPlayers);
done();
}),
/**
* Toggle (pause/play) all animations in the current target.
*/
- toggleAll: function() {
+ toggleAll: function () {
if (!this.traits.hasToggleAll) {
return promise.resolve();
}
return this.animationsFront.toggleAll()
.then(() => this.emit(this.ALL_ANIMATIONS_TOGGLED_EVENT, this))
.catch(e => console.error(e));
},
@@ -336,17 +336,17 @@ var AnimationsController = {
// Start listening for animation mutations only after the first method call
// otherwise events won't be sent.
if (!this.isListeningToMutations && this.traits.hasMutationEvents) {
this.animationsFront.on("mutations", this.onAnimationMutations);
this.isListeningToMutations = true;
}
}),
- onAnimationMutations: function(changes) {
+ onAnimationMutations: function (changes) {
// Insert new players into this.animationPlayers when new animations are
// added.
for (let {type, player} of changes) {
if (type === "added") {
this.animationPlayers.push(player);
}
if (type === "removed") {
@@ -373,14 +373,14 @@ var AnimationsController = {
if (!state.documentCurrentTime) {
return false;
}
time = Math.max(time, state.documentCurrentTime);
}
return time;
},
- destroyAnimationPlayers: function() {
+ destroyAnimationPlayers: function () {
this.animationPlayers = [];
}
};
EventEmitter.decorate(AnimationsController);
--- a/devtools/client/animationinspector/animation-panel.js
+++ b/devtools/client/animationinspector/animation-panel.js
@@ -103,17 +103,17 @@ var AnimationsPanel = {
this.playersEl = this.errorMessageEl = null;
this.toggleAllButtonEl = this.pickerButtonEl = null;
this.playTimelineButtonEl = this.rewindTimelineButtonEl = null;
this.timelineCurrentTimeEl = this.rateSelectorEl = null;
this.destroyed.resolve();
}),
- startListeners: function() {
+ startListeners: function () {
AnimationsController.on(AnimationsController.PLAYERS_UPDATED_EVENT,
this.refreshAnimationsUI);
this.pickerButtonEl.addEventListener("click", this.togglePicker);
gToolbox.on("picker-started", this.onPickerStarted);
gToolbox.on("picker-stopped", this.onPickerStopped);
this.toggleAllButtonEl.addEventListener("click", this.onToggleAllClicked);
@@ -129,17 +129,17 @@ var AnimationsPanel = {
this.animationsTimelineComponent.on("timeline-data-changed",
this.onTimelineDataChanged);
if (this.rateSelectorComponent) {
this.rateSelectorComponent.on("rate-changed", this.onRateChanged);
}
},
- stopListeners: function() {
+ stopListeners: function () {
AnimationsController.off(AnimationsController.PLAYERS_UPDATED_EVENT,
this.refreshAnimationsUI);
this.pickerButtonEl.removeEventListener("click", this.togglePicker);
gToolbox.off("picker-started", this.onPickerStarted);
gToolbox.off("picker-stopped", this.onPickerStopped);
this.toggleAllButtonEl.removeEventListener("click",
@@ -156,116 +156,116 @@ var AnimationsPanel = {
this.animationsTimelineComponent.off("timeline-data-changed",
this.onTimelineDataChanged);
if (this.rateSelectorComponent) {
this.rateSelectorComponent.off("rate-changed", this.onRateChanged);
}
},
- onKeyDown: function(event) {
+ onKeyDown: function (event) {
let keyEvent = Ci.nsIDOMKeyEvent;
// If the space key is pressed, it should toggle the play state of
// the animations displayed in the panel, or of all the animations on
// the page if the selected node does not have any animation on it.
if (event.keyCode === keyEvent.DOM_VK_SPACE) {
if (AnimationsController.animationPlayers.length > 0) {
this.playPauseTimeline().catch(ex => console.error(ex));
} else {
this.toggleAll().catch(ex => console.error(ex));
}
event.preventDefault();
}
},
- togglePlayers: function(isVisible) {
+ togglePlayers: function (isVisible) {
if (isVisible) {
document.body.removeAttribute("empty");
document.body.setAttribute("timeline", "true");
} else {
document.body.setAttribute("empty", "true");
document.body.removeAttribute("timeline");
$("#error-type").textContent =
L10N.getStr("panel.invalidElementSelected");
}
},
- onPickerStarted: function() {
+ onPickerStarted: function () {
this.pickerButtonEl.setAttribute("checked", "true");
},
- onPickerStopped: function() {
+ onPickerStopped: function () {
this.pickerButtonEl.removeAttribute("checked");
},
- onToggleAllClicked: function() {
+ onToggleAllClicked: function () {
this.toggleAll().catch(ex => console.error(ex));
},
/**
* Toggle (pause/play) all animations in the current target
* and update the UI the toggleAll button.
*/
toggleAll: Task.async(function* () {
this.toggleAllButtonEl.classList.toggle("paused");
yield AnimationsController.toggleAll();
}),
- onTimelinePlayClicked: function() {
+ onTimelinePlayClicked: function () {
this.playPauseTimeline().catch(ex => console.error(ex));
},
/**
* Depending on the state of the timeline either pause or play the animations
* displayed in it.
* If the animations are finished, this will play them from the start again.
* If the animations are playing, this will pause them.
* If the animations are paused, this will resume them.
*
* @return {Promise} Resolves when the playState is changed and the UI
* is refreshed
*/
- playPauseTimeline: function() {
+ playPauseTimeline: function () {
return AnimationsController
.toggleCurrentAnimations(this.timelineData.isMoving)
.then(() => this.refreshAnimationsStateAndUI());
},
- onTimelineRewindClicked: function() {
+ onTimelineRewindClicked: function () {
this.rewindTimeline().catch(ex => console.error(ex));
},
/**
* Reset the startTime of all current animations shown in the timeline and
* pause them.
*
* @return {Promise} Resolves when currentTime is set and the UI is refreshed
*/
- rewindTimeline: function() {
+ rewindTimeline: function () {
return AnimationsController
.setCurrentTimeAll(0, true)
.then(() => this.refreshAnimationsStateAndUI());
},
/**
* Set the playback rate of all current animations shown in the timeline to
* the value of this.rateSelectorEl.
*/
- onRateChanged: function(e, rate) {
+ onRateChanged: function (e, rate) {
AnimationsController.setPlaybackRateAll(rate)
.then(() => this.refreshAnimationsStateAndUI())
.catch(ex => console.error(ex));
},
- onTabNavigated: function() {
+ onTabNavigated: function () {
this.toggleAllButtonEl.classList.remove("paused");
},
- onTimelineDataChanged: function(e, data) {
+ onTimelineDataChanged: function (e, data) {
this.timelineData = data;
let {isMoving, isUserDrag, time} = data;
this.playTimelineButtonEl.classList.toggle("paused", !isMoving);
let l10nPlayProperty = isMoving ? "timeline.resumedButtonTooltip" :
"timeline.pausedButtonTooltip";
@@ -283,17 +283,17 @@ var AnimationsPanel = {
.then(() => {
this.setCurrentTimeAllPromise = null;
});
}
this.displayTimelineCurrentTime();
},
- displayTimelineCurrentTime: function() {
+ displayTimelineCurrentTime: function () {
let {time} = this.timelineData;
this.timelineCurrentTimeEl.textContent = formatStopwatchTime(time);
},
/**
* Make sure all known animations have their states up to date (which is
* useful after the playState or currentTime has been changed and in case the
* animations aren't auto-refreshing), and then refresh the UI.
--- a/devtools/client/animationinspector/components/animation-details.js
+++ b/devtools/client/animationinspector/components/animation-details.js
@@ -30,27 +30,27 @@ function AnimationDetails(serverTraits)
exports.AnimationDetails = AnimationDetails;
AnimationDetails.prototype = {
// These are part of frame objects but are not animated properties. This
// array is used to skip them.
NON_PROPERTIES: ["easing", "composite", "computedOffset", "offset"],
- init: function(containerEl) {
+ init: function (containerEl) {
this.containerEl = containerEl;
},
- destroy: function() {
+ destroy: function () {
this.unrender();
this.containerEl = null;
this.serverTraits = null;
},
- unrender: function() {
+ unrender: function () {
for (let component of this.keyframeComponents) {
component.off("frame-selected", this.onFrameSelected);
component.destroy();
}
this.keyframeComponents = [];
while (this.containerEl.firstChild) {
this.containerEl.firstChild.remove();
@@ -173,17 +173,17 @@ AnimationDetails.prototype = {
animation: animation
});
keyframesComponent.on("frame-selected", this.onFrameSelected);
this.keyframeComponents.push(keyframesComponent);
}
}),
- onFrameSelected: function(e, args) {
+ onFrameSelected: function (e, args) {
// Relay the event up, it's needed in parents too.
this.emit(e, args);
}
};
/**
* Turn propertyName into property-name.
* @param {String} jsPropertyName A camelcased CSS property name. Typically
--- a/devtools/client/animationinspector/components/animation-target-node.js
+++ b/devtools/client/animationinspector/components/animation-target-node.js
@@ -25,22 +25,22 @@ function AnimationTargetNode(inspector,
this.inspector = inspector;
this.previewer = new DomNodePreview(inspector, options);
EventEmitter.decorate(this);
}
exports.AnimationTargetNode = AnimationTargetNode;
AnimationTargetNode.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
this.previewer.init(containerEl);
this.isDestroyed = false;
},
- destroy: function() {
+ destroy: function () {
this.previewer.destroy();
this.inspector = null;
this.isDestroyed = true;
},
render: Task.async(function* (playerFront) {
// Get the nodeFront from the cache if it was stored previously.
let nodeFront = nodeFronts.get(playerFront);
--- a/devtools/client/animationinspector/components/animation-time-block.js
+++ b/devtools/client/animationinspector/components/animation-time-block.js
@@ -22,35 +22,35 @@ const L10N = new LocalizationHelper(STRI
function AnimationTimeBlock() {
EventEmitter.decorate(this);
this.onClick = this.onClick.bind(this);
}
exports.AnimationTimeBlock = AnimationTimeBlock;
AnimationTimeBlock.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
this.containerEl = containerEl;
this.containerEl.addEventListener("click", this.onClick);
},
- destroy: function() {
+ destroy: function () {
this.containerEl.removeEventListener("click", this.onClick);
this.unrender();
this.containerEl = null;
this.animation = null;
},
- unrender: function() {
+ unrender: function () {
while (this.containerEl.firstChild) {
this.containerEl.firstChild.remove();
}
},
- render: function(animation) {
+ render: function (animation) {
this.unrender();
this.animation = animation;
let {state} = this.animation;
// Create a container element to hold the delay and iterations.
// It is positioned according to its delay (divided by the playbackrate),
// and its width is according to its duration (divided by the playbackrate).
@@ -115,17 +115,17 @@ AnimationTimeBlock.prototype = {
"class": "end-delay" + (state.endDelay < 0 ? " negative" : ""),
"style": `left:${endDelayX}%;
width:${endDelayW}%;`
}
});
}
},
- getTooltipText: function(state) {
+ getTooltipText: function (state) {
let getTime = time => L10N.getFormatStr("player.timeLabel",
L10N.numberWithDecimals(time / 1000, 2));
let text = "";
// Adding the name.
text += getFormattedAnimationTitle({state});
text += "\n";
@@ -177,17 +177,17 @@ AnimationTimeBlock.prototype = {
// needed.
if (state.isRunningOnCompositor) {
text += L10N.getStr("player.runningOnCompositorTooltip");
}
return text;
},
- onClick: function(e) {
+ onClick: function (e) {
e.stopPropagation();
this.emit("selected", this.animation);
}
};
/**
* Get a formatted title for this animation. This will be either:
* "some-name", "some-name : CSS Transition", "some-name : CSS Animation",
--- a/devtools/client/animationinspector/components/animation-timeline.js
+++ b/devtools/client/animationinspector/components/animation-timeline.js
@@ -55,17 +55,17 @@ function AnimationsTimeline(inspector, s
this.onFrameSelected = this.onFrameSelected.bind(this);
EventEmitter.decorate(this);
}
exports.AnimationsTimeline = AnimationsTimeline;
AnimationsTimeline.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
this.win = containerEl.ownerDocument.defaultView;
this.rootWrapperEl = createNode({
parent: containerEl,
attributes: {
"class": "animation-timeline"
}
});
@@ -107,17 +107,17 @@ AnimationsTimeline.prototype = {
"class": "animations"
}
});
this.win.addEventListener("resize",
this.onWindowResize);
},
- destroy: function() {
+ destroy: function () {
this.stopAnimatingScrubber();
this.unrender();
this.win.removeEventListener("resize",
this.onWindowResize);
this.timeHeaderEl.removeEventListener("mousedown",
this.onScrubberMouseDown);
this.scrubberHandleEl.removeEventListener("mousedown",
@@ -137,57 +137,57 @@ AnimationsTimeline.prototype = {
},
/**
* Destroy sub-components that have been created and stored on this instance.
* @param {String} name An array of components will be expected in this[name]
* @param {Array} handlers An option list of event handlers information that
* should be used to remove these handlers.
*/
- destroySubComponents: function(name, handlers = []) {
+ destroySubComponents: function (name, handlers = []) {
for (let component of this[name]) {
for (let {event, fn} of handlers) {
component.off(event, fn);
}
component.destroy();
}
this[name] = [];
},
- unrender: function() {
+ unrender: function () {
for (let animation of this.animations) {
animation.off("changed", this.onAnimationStateChanged);
}
this.stopAnimatingScrubber();
TimeScale.reset();
this.destroySubComponents("targetNodes");
this.destroySubComponents("timeBlocks");
this.destroySubComponents("details", [{
event: "frame-selected",
fn: this.onFrameSelected
}]);
this.animationsEl.innerHTML = "";
},
- onWindowResize: function() {
+ onWindowResize: function () {
// Don't do anything if the root element has a width of 0
if (this.rootWrapperEl.offsetWidth === 0) {
return;
}
if (this.windowResizeTimer) {
this.win.clearTimeout(this.windowResizeTimer);
}
this.windowResizeTimer = this.win.setTimeout(() => {
this.drawHeaderAndBackground();
}, TIMELINE_BACKGROUND_RESIZE_DEBOUNCE_TIMER);
},
- onAnimationSelected: function(e, animation) {
+ onAnimationSelected: function (e, animation) {
let index = this.animations.indexOf(animation);
if (index === -1) {
return;
}
let el = this.rootWrapperEl;
let animationEl = el.querySelectorAll(".animation")[index];
let propsEl = el.querySelectorAll(".animated-properties")[index];
@@ -203,53 +203,53 @@ AnimationsTimeline.prototype = {
} else {
this.emit("animation-unselected", animation);
}
},
/**
* When a frame gets selected, move the scrubber to the corresponding position
*/
- onFrameSelected: function(e, {x}) {
+ onFrameSelected: function (e, {x}) {
this.moveScrubberTo(x, true);
},
- onScrubberMouseDown: function(e) {
+ onScrubberMouseDown: function (e) {
this.moveScrubberTo(e.pageX);
this.win.addEventListener("mouseup", this.onScrubberMouseUp);
this.win.addEventListener("mouseout", this.onScrubberMouseOut);
this.win.addEventListener("mousemove", this.onScrubberMouseMove);
// Prevent text selection while dragging.
e.preventDefault();
},
- onScrubberMouseUp: function() {
+ onScrubberMouseUp: function () {
this.cancelTimeHeaderDragging();
},
- onScrubberMouseOut: function(e) {
+ onScrubberMouseOut: function (e) {
// Check that mouseout happened on the window itself, and if yes, cancel
// the dragging.
if (!this.win.document.contains(e.relatedTarget)) {
this.cancelTimeHeaderDragging();
}
},
- cancelTimeHeaderDragging: function() {
+ cancelTimeHeaderDragging: function () {
this.win.removeEventListener("mouseup", this.onScrubberMouseUp);
this.win.removeEventListener("mouseout", this.onScrubberMouseOut);
this.win.removeEventListener("mousemove", this.onScrubberMouseMove);
},
- onScrubberMouseMove: function(e) {
+ onScrubberMouseMove: function (e) {
this.moveScrubberTo(e.pageX);
},
- moveScrubberTo: function(pageX, noOffset) {
+ moveScrubberTo: function (pageX, noOffset) {
this.stopAnimatingScrubber();
// The offset needs to be in % and relative to the timeline's area (so we
// subtract the scrubber's left offset, which is equal to the sidebar's
// width).
let offset = pageX;
if (!noOffset) {
offset -= this.timeHeaderEl.offsetLeft;
@@ -266,17 +266,17 @@ AnimationsTimeline.prototype = {
this.emit("timeline-data-changed", {
isPaused: true,
isMoving: false,
isUserDrag: true,
time: time
});
},
- render: function(animations, documentCurrentTime) {
+ render: function (animations, documentCurrentTime) {
this.unrender();
this.animations = animations;
if (!this.animations.length) {
return;
}
// Loop first to set the time scale for all current animations.
@@ -356,30 +356,30 @@ AnimationsTimeline.prototype = {
} else {
this.scrubberEl.style.display = "block";
this.startAnimatingScrubber(this.wasRewound()
? TimeScale.minStartTime
: documentCurrentTime);
}
},
- isAtLeastOneAnimationPlaying: function() {
+ isAtLeastOneAnimationPlaying: function () {
return this.animations.some(({state}) => state.playState === "running");
},
- wasRewound: function() {
+ wasRewound: function () {
return !this.isAtLeastOneAnimationPlaying() &&
this.animations.every(({state}) => state.currentTime === 0);
},
- hasInfiniteAnimations: function() {
+ hasInfiniteAnimations: function () {
return this.animations.some(({state}) => !state.iterationCount);
},
- startAnimatingScrubber: function(time) {
+ startAnimatingScrubber: function (time) {
let isOutOfBounds = time < TimeScale.minStartTime ||
time > TimeScale.maxEndTime;
let isAllPaused = !this.isAtLeastOneAnimationPlaying();
let hasInfinite = this.hasInfiniteAnimations();
let x = TimeScale.startTimeToDistance(time);
if (x > 100 && !hasInfinite) {
x = 100;
@@ -411,30 +411,30 @@ AnimationsTimeline.prototype = {
if (!this.rafID) {
// In case the scrubber was stopped in the meantime.
return;
}
this.startAnimatingScrubber(time + this.win.performance.now() - now);
});
},
- stopAnimatingScrubber: function() {
+ stopAnimatingScrubber: function () {
if (this.rafID) {
this.win.cancelAnimationFrame(this.rafID);
this.rafID = null;
}
},
- onAnimationStateChanged: function() {
+ onAnimationStateChanged: function () {
// For now, simply re-render the component. The animation front's state has
// already been updated.
this.render(this.animations);
},
- drawHeaderAndBackground: function() {
+ drawHeaderAndBackground: function () {
let width = this.timeHeaderEl.offsetWidth;
let animationDuration = TimeScale.maxEndTime - TimeScale.minStartTime;
let minTimeInterval = TIME_GRADUATION_MIN_SPACING *
animationDuration / width;
let intervalLength = findOptimalTimeInterval(minTimeInterval);
let intervalWidth = intervalLength * width / animationDuration;
// And the time graduation header.
--- a/devtools/client/animationinspector/components/keyframes.js
+++ b/devtools/client/animationinspector/components/keyframes.js
@@ -16,34 +16,34 @@ const {createNode} = require("devtools/c
function Keyframes() {
EventEmitter.decorate(this);
this.onClick = this.onClick.bind(this);
}
exports.Keyframes = Keyframes;
Keyframes.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
this.containerEl = containerEl;
this.keyframesEl = createNode({
parent: this.containerEl,
attributes: {"class": "keyframes"}
});
this.containerEl.addEventListener("click", this.onClick);
},
- destroy: function() {
+ destroy: function () {
this.containerEl.removeEventListener("click", this.onClick);
this.keyframesEl.remove();
this.containerEl = this.keyframesEl = this.animation = null;
},
- render: function({keyframes, propertyName, animation}) {
+ render: function ({keyframes, propertyName, animation}) {
this.keyframes = keyframes;
this.propertyName = propertyName;
this.animation = animation;
let iterationStartOffset =
animation.state.iterationStart % 1 == 0
? 0
: 1 - animation.state.iterationStart % 1;
@@ -59,17 +59,17 @@ Keyframes.prototype = {
"data-offset": frame.offset,
"data-property": propertyName,
"title": frame.value
}
});
}
},
- onClick: function(e) {
+ onClick: function (e) {
// If the click happened on a frame, tell our parent about it.
if (!e.target.classList.contains("frame")) {
return;
}
e.stopPropagation();
this.emit("frame-selected", {
animation: this.animation,
--- a/devtools/client/animationinspector/components/rate-selector.js
+++ b/devtools/client/animationinspector/components/rate-selector.js
@@ -28,49 +28,49 @@ const PLAYBACK_RATES = [.1, .25, .5, 1,
function RateSelector() {
this.onRateChanged = this.onRateChanged.bind(this);
EventEmitter.decorate(this);
}
exports.RateSelector = RateSelector;
RateSelector.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
this.selectEl = createNode({
parent: containerEl,
nodeType: "select",
attributes: {
"class": "devtools-button",
"title": L10N.getStr("timeline.rateSelectorTooltip")
}
});
this.selectEl.addEventListener("change", this.onRateChanged);
},
- destroy: function() {
+ destroy: function () {
this.selectEl.removeEventListener("change", this.onRateChanged);
this.selectEl.remove();
this.selectEl = null;
},
- getAnimationsRates: function(animations) {
+ getAnimationsRates: function (animations) {
return sortedUnique(animations.map(a => a.state.playbackRate));
},
- getAllRates: function(animations) {
+ getAllRates: function (animations) {
let animationsRates = this.getAnimationsRates(animations);
if (animationsRates.length > 1) {
return PLAYBACK_RATES;
}
return sortedUnique(PLAYBACK_RATES.concat(animationsRates));
},
- render: function(animations) {
+ render: function (animations) {
let allRates = this.getAnimationsRates(animations);
let hasOneRate = allRates.length === 1;
this.selectEl.innerHTML = "";
if (!hasOneRate) {
// When the animations displayed have mixed playback rates, we can't
// select any of the predefined ones, instead, insert an empty rate.
@@ -91,17 +91,17 @@ RateSelector.prototype = {
// If there's only one rate and this is the option for it, select it.
if (hasOneRate && rate === allRates[0]) {
option.setAttribute("selected", "true");
}
}
},
- onRateChanged: function() {
+ onRateChanged: function () {
let rate = parseFloat(this.selectEl.value);
if (!isNaN(rate)) {
this.emit("rate-changed", rate);
}
}
};
let sortedUnique = arr => [...new Set(arr)].sort((a, b) => a > b);
--- a/devtools/client/animationinspector/test/doc_frame_script.js
+++ b/devtools/client/animationinspector/test/doc_frame_script.js
@@ -11,17 +11,17 @@
* Toggle (play or pause) one of the animation players of a given node.
* @param {Object} data
* - {String} selector The CSS selector to get the node (can be a "super"
* selector).
* - {Number} animationIndex The index of the node's animationPlayers to play
* or pause
* - {Boolean} pause True to pause the animation, false to play.
*/
-addMessageListener("Test:ToggleAnimationPlayer", function(msg) {
+addMessageListener("Test:ToggleAnimationPlayer", function (msg) {
let {selector, animationIndex, pause} = msg.data;
let node = superQuerySelector(selector);
if (!node) {
return;
}
let animation = node.getAnimations()[animationIndex];
if (pause) {
@@ -36,17 +36,17 @@ addMessageListener("Test:ToggleAnimation
/**
* Change the currentTime of one of the animation players of a given node.
* @param {Object} data
* - {String} selector The CSS selector to get the node (can be a "super"
* selector).
* - {Number} animationIndex The index of the node's animationPlayers to change.
* - {Number} currentTime The current time to set.
*/
-addMessageListener("Test:SetAnimationPlayerCurrentTime", function(msg) {
+addMessageListener("Test:SetAnimationPlayerCurrentTime", function (msg) {
let {selector, animationIndex, currentTime} = msg.data;
let node = superQuerySelector(selector);
if (!node) {
return;
}
let animation = node.getAnimations()[animationIndex];
animation.currentTime = currentTime;
@@ -57,17 +57,17 @@ addMessageListener("Test:SetAnimationPla
/**
* Change the playbackRate of one of the animation players of a given node.
* @param {Object} data
* - {String} selector The CSS selector to get the node (can be a "super"
* selector).
* - {Number} animationIndex The index of the node's animationPlayers to change.
* - {Number} playbackRate The rate to set.
*/
-addMessageListener("Test:SetAnimationPlayerPlaybackRate", function(msg) {
+addMessageListener("Test:SetAnimationPlayerPlaybackRate", function (msg) {
let {selector, animationIndex, playbackRate} = msg.data;
let node = superQuerySelector(selector);
if (!node) {
return;
}
let player = node.getAnimations()[animationIndex];
player.playbackRate = playbackRate;
@@ -77,17 +77,17 @@ addMessageListener("Test:SetAnimationPla
/**
* Get the current playState of an animation player on a given node.
* @param {Object} data
* - {String} selector The CSS selector to get the node (can be a "super"
* selector).
* - {Number} animationIndex The index of the node's animationPlayers to check
*/
-addMessageListener("Test:GetAnimationPlayerState", function(msg) {
+addMessageListener("Test:GetAnimationPlayerState", function (msg) {
let {selector, animationIndex} = msg.data;
let node = superQuerySelector(selector);
if (!node) {
return;
}
let animation = node.getAnimations()[animationIndex];
animation.ready.then(() => {
--- a/devtools/client/animationinspector/test/doc_multiple_animation_types.html
+++ b/devtools/client/animationinspector/test/doc_multiple_animation_types.html
@@ -40,17 +40,17 @@
<div class="ball script-animation"></div>
<div class="ball css-animation"></div>
<div class="ball css-transition"></div>
<script>
/* globals KeyframeEffect, Animation */
"use strict";
- setTimeout(function() {
+ setTimeout(function () {
document.querySelector(".css-transition").style.backgroundColor = "yellow";
}, 0);
let effect = new KeyframeEffect(
document.querySelector(".script-animation"), [
{opacity: 1, offset: 0},
{opacity: .1, offset: 1}
], { duration: 10000, fill: "forwards" });
--- a/devtools/client/animationinspector/test/doc_negative_animation.html
+++ b/devtools/client/animationinspector/test/doc_negative_animation.html
@@ -49,18 +49,18 @@
var negative = document.querySelector(".negative");
var zero = document.querySelector(".zero");
var positive = document.querySelector(".positive");
// The non-delayed animation starts now.
zero.classList.add("move");
// The negative-delayed animation starts in 1 second.
- setTimeout(function() {
+ setTimeout(function () {
negative.classList.add("move");
}, 1000);
// The positive-delayed animation starts in 200 ms.
- setTimeout(function() {
+ setTimeout(function () {
positive.classList.add("move");
}, 200);
</script>
</body>
-</html>
\ No newline at end of file
+</html>
--- a/devtools/client/animationinspector/test/head.js
+++ b/devtools/client/animationinspector/test/head.js
@@ -42,17 +42,17 @@ function enableWebAnimationsAPI() {
}
/**
* 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
*/
var _addTab = addTab;
-addTab = function(url) {
+addTab = function (url) {
return enableWebAnimationsAPI().then(() => _addTab(url)).then(tab => {
let browser = tab.linkedBrowser;
info("Loading the helper frame script " + FRAME_SCRIPT_URL);
browser.messageManager.loadFrameScript(FRAME_SCRIPT_URL, false);
info("Loading the helper frame script " + COMMON_FRAME_SCRIPT_URL);
browser.messageManager.loadFrameScript(COMMON_FRAME_SCRIPT_URL, false);
return tab;
});
--- a/devtools/client/animationinspector/utils.js
+++ b/devtools/client/animationinspector/utils.js
@@ -134,17 +134,17 @@ exports.formatStopwatchTime = formatStop
var TimeScale = {
minStartTime: Infinity,
maxEndTime: 0,
/**
* Add a new animation to time scale.
* @param {Object} state A PlayerFront.state object.
*/
- addAnimation: function(state) {
+ addAnimation: function (state) {
let {previousStartTime, delay, duration, endDelay,
iterationCount, playbackRate} = state;
endDelay = typeof endDelay === "undefined" ? 0 : endDelay;
let toRate = v => v / playbackRate;
let minZero = v => Math.max(v, 0);
let rateRelativeDuration =
toRate(duration * (!iterationCount ? 1 : iterationCount));
@@ -168,85 +168,85 @@ var TimeScale = {
toRate(minZero(endDelay));
let endTime = previousStartTime + length;
this.maxEndTime = Math.max(this.maxEndTime, endTime);
},
/**
* Reset the current time scale.
*/
- reset: function() {
+ reset: function () {
this.minStartTime = Infinity;
this.maxEndTime = 0;
},
/**
* Convert a startTime to a distance in %, in the current time scale.
* @param {Number} time
* @return {Number}
*/
- startTimeToDistance: function(time) {
+ startTimeToDistance: function (time) {
time -= this.minStartTime;
return this.durationToDistance(time);
},
/**
* Convert a duration to a distance in %, in the current time scale.
* @param {Number} time
* @return {Number}
*/
- durationToDistance: function(duration) {
+ durationToDistance: function (duration) {
return duration * 100 / this.getDuration();
},
/**
* Convert a distance in % to a time, in the current time scale.
* @param {Number} distance
* @return {Number}
*/
- distanceToTime: function(distance) {
+ distanceToTime: function (distance) {
return this.minStartTime + (this.getDuration() * distance / 100);
},
/**
* Convert a distance in % to a time, in the current time scale.
* The time will be relative to the current minimum start time.
* @param {Number} distance
* @return {Number}
*/
- distanceToRelativeTime: function(distance) {
+ distanceToRelativeTime: function (distance) {
let time = this.distanceToTime(distance);
return time - this.minStartTime;
},
/**
* Depending on the time scale, format the given time as milliseconds or
* seconds.
* @param {Number} time
* @return {String} The formatted time string.
*/
- formatTime: function(time) {
+ formatTime: function (time) {
// Format in milliseconds if the total duration is short enough.
if (this.getDuration() <= MILLIS_TIME_FORMAT_MAX_DURATION) {
return L10N.getFormatStr("timeline.timeGraduationLabel", time.toFixed(0));
}
// Otherwise format in seconds.
return L10N.getFormatStr("player.timeLabel", (time / 1000).toFixed(1));
},
- getDuration: function() {
+ getDuration: function () {
return this.maxEndTime - this.minStartTime;
},
/**
* Given an animation, get the various dimensions (in %) useful to draw the
* animation in the timeline.
*/
- getAnimationDimensions: function({state}) {
+ getAnimationDimensions: function ({state}) {
let start = state.previousStartTime || 0;
let duration = state.duration;
let rate = state.playbackRate;
let count = state.iterationCount;
let delay = state.delay || 0;
let endDelay = state.endDelay || 0;
// The start position.
@@ -274,17 +274,17 @@ var TimeScale = {
/**
* Given an animation, get the background data for .iterations element.
* This background represents iterationCount and iterationStart.
* Returns three properties.
* 1. size: x of background-size (%)
* 2. position: x of background-position (%)
* 3. repeat: background-repeat (string)
*/
- getIterationsBackgroundData: function({state}) {
+ getIterationsBackgroundData: function ({state}) {
let iterationCount = state.iterationCount || 1;
let iterationStartW = state.iterationStart % 1 * 100;
let background = {};
if (iterationCount == 1) {
background.size = 100 - iterationStartW;
background.position = 0;
background.repeat = "no-repeat";
} else {
--- a/devtools/client/definitions.js
+++ b/devtools/client/definitions.js
@@ -68,21 +68,21 @@ Tools.options = {
invertIconForLightTheme: true,
bgTheme: "theme-body",
label: l10n("options.label", toolboxStrings),
iconOnly: true,
panelLabel: l10n("options.panelLabel", toolboxStrings),
tooltip: l10n("optionsButton.tooltip", toolboxStrings),
inMenu: false,
- isTargetSupported: function() {
+ isTargetSupported: function () {
return true;
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new OptionsPanel(iframeWindow, toolbox);
}
};
Tools.inspector = {
id: "inspector",
accesskey: l10n("inspector.accesskey", inspectorStrings),
key: l10n("inspector.commandkey", inspectorStrings),
@@ -100,25 +100,25 @@ Tools.inspector = {
inMenu: true,
commands: [
"devtools/client/responsivedesign/resize-commands",
"devtools/client/inspector/inspector-commands",
"devtools/client/eyedropper/commands.js"
],
preventClosingOnKey: true,
- onkey: function(panel, toolbox) {
+ onkey: function (panel, toolbox) {
toolbox.highlighterUtils.togglePicker();
},
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("inspector");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new InspectorPanel(iframeWindow, toolbox);
}
};
Tools.webConsole = {
id: "webconsole",
key: l10n("cmd.commandkey", webConsoleStrings),
accesskey: l10n("webConsoleCmd.accesskey", webConsoleStrings),
@@ -133,30 +133,30 @@ Tools.webConsole = {
get tooltip() {
return l10n("ToolboxWebconsole.tooltip2", webConsoleStrings,
(osString == "Darwin" ? "Cmd+Opt+" : "Ctrl+Shift+") + this.key);
},
inMenu: true,
commands: "devtools/client/webconsole/console-commands",
preventClosingOnKey: true,
- onkey: function(panel, toolbox) {
+ onkey: function (panel, toolbox) {
if (toolbox.splitConsole) {
return toolbox.focusConsoleInput();
}
panel.focusInput();
return undefined;
},
- isTargetSupported: function() {
+ isTargetSupported: function () {
return true;
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new WebConsolePanel(iframeWindow, toolbox);
}
};
Tools.jsdebugger = {
id: "jsdebugger",
key: l10n("debuggerMenu.commandkey", debuggerStrings),
accesskey: l10n("debuggerMenu.accesskey", debuggerStrings),
@@ -170,21 +170,21 @@ Tools.jsdebugger = {
panelLabel: l10n("ToolboxDebugger.panelLabel", debuggerStrings),
get tooltip() {
return l10n("ToolboxDebugger.tooltip2", debuggerStrings,
(osString == "Darwin" ? "Cmd+Opt+" : "Ctrl+Shift+") + this.key);
},
inMenu: true,
commands: "devtools/client/debugger/debugger-commands",
- isTargetSupported: function() {
+ isTargetSupported: function () {
return true;
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new DebuggerPanel(iframeWindow, toolbox);
}
};
Tools.styleEditor = {
id: "styleeditor",
key: l10n("open.commandkey", styleEditorStrings),
ordinal: 4,
@@ -197,41 +197,41 @@ Tools.styleEditor = {
panelLabel: l10n("ToolboxStyleEditor.panelLabel", styleEditorStrings),
get tooltip() {
return l10n("ToolboxStyleEditor.tooltip3", styleEditorStrings,
"Shift+" + functionkey(this.key));
},
inMenu: true,
commands: "devtools/client/styleeditor/styleeditor-commands",
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("styleEditor") || target.hasActor("styleSheets");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new StyleEditorPanel(iframeWindow, toolbox);
}
};
Tools.shaderEditor = {
id: "shadereditor",
ordinal: 5,
visibilityswitch: "devtools.shadereditor.enabled",
icon: "chrome://devtools/skin/images/tool-shadereditor.svg",
invertIconForLightTheme: true,
url: "chrome://devtools/content/shadereditor/shadereditor.xul",
label: l10n("ToolboxShaderEditor.label", shaderEditorStrings),
panelLabel: l10n("ToolboxShaderEditor.panelLabel", shaderEditorStrings),
tooltip: l10n("ToolboxShaderEditor.tooltip", shaderEditorStrings),
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("webgl") && !target.chrome;
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new ShaderEditorPanel(iframeWindow, toolbox);
}
};
Tools.canvasDebugger = {
id: "canvasdebugger",
ordinal: 6,
visibilityswitch: "devtools.canvasdebugger.enabled",
@@ -239,21 +239,21 @@ Tools.canvasDebugger = {
invertIconForLightTheme: true,
url: "chrome://devtools/content/canvasdebugger/canvasdebugger.xul",
label: l10n("ToolboxCanvasDebugger.label", canvasDebuggerStrings),
panelLabel: l10n("ToolboxCanvasDebugger.panelLabel", canvasDebuggerStrings),
tooltip: l10n("ToolboxCanvasDebugger.tooltip", canvasDebuggerStrings),
// Hide the Canvas Debugger in the Add-on Debugger and Browser Toolbox
// (bug 1047520).
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("canvas") && !target.chrome;
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new CanvasDebuggerPanel(iframeWindow, toolbox);
}
};
Tools.performance = {
id: "performance",
ordinal: 7,
icon: "chrome://devtools/skin/images/tool-profiler.svg",
@@ -267,42 +267,42 @@ Tools.performance = {
return l10n("performance.tooltip", performanceStrings,
"Shift+" + functionkey(this.key));
},
accesskey: l10n("performance.accesskey", performanceStrings),
key: l10n("performance.commandkey", performanceStrings),
modifiers: "shift",
inMenu: true,
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("profiler");
},
- build: function(frame, target) {
+ build: function (frame, target) {
return new PerformancePanel(frame, target);
}
};
Tools.memory = {
id: "memory",
ordinal: 8,
icon: "chrome://devtools/skin/images/tool-memory.svg",
invertIconForLightTheme: true,
highlightedicon: "chrome://devtools/skin/images/tool-memory-active.svg",
url: "chrome://devtools/content/memory/memory.xhtml",
visibilityswitch: "devtools.memory.enabled",
label: l10n("memory.label", memoryStrings),
panelLabel: l10n("memory.panelLabel", memoryStrings),
tooltip: l10n("memory.tooltip", memoryStrings),
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.getTrait("heapSnapshots");
},
- build: function(frame, target) {
+ build: function (frame, target) {
return new MemoryPanel(frame, target);
}
};
Tools.netMonitor = {
id: "netmonitor",
accesskey: l10n("netmonitor.accesskey", netMonitorStrings),
key: l10n("netmonitor.commandkey", netMonitorStrings),
@@ -315,21 +315,21 @@ Tools.netMonitor = {
label: l10n("netmonitor.label", netMonitorStrings),
panelLabel: l10n("netmonitor.panelLabel", netMonitorStrings),
get tooltip() {
return l10n("netmonitor.tooltip2", netMonitorStrings,
(osString == "Darwin" ? "Cmd+Opt+" : "Ctrl+Shift+") + this.key);
},
inMenu: true,
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.getTrait("networkMonitor");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new NetMonitorPanel(iframeWindow, toolbox);
}
};
Tools.storage = {
id: "storage",
key: l10n("storage.commandkey", storageStrings),
ordinal: 10,
@@ -343,42 +343,42 @@ Tools.storage = {
menuLabel: l10n("storage.menuLabel", storageStrings),
panelLabel: l10n("storage.panelLabel", storageStrings),
get tooltip() {
return l10n("storage.tooltip3", storageStrings,
"Shift+" + functionkey(this.key));
},
inMenu: true,
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.isLocalTab ||
(target.hasActor("storage") && target.getTrait("storageInspector"));
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new StoragePanel(iframeWindow, toolbox);
}
};
Tools.webAudioEditor = {
id: "webaudioeditor",
ordinal: 11,
visibilityswitch: "devtools.webaudioeditor.enabled",
icon: "chrome://devtools/skin/images/tool-webaudio.svg",
invertIconForLightTheme: true,
url: "chrome://devtools/content/webaudioeditor/webaudioeditor.xul",
label: l10n("ToolboxWebAudioEditor1.label", webAudioEditorStrings),
panelLabel: l10n("ToolboxWebAudioEditor1.panelLabel", webAudioEditorStrings),
tooltip: l10n("ToolboxWebAudioEditor1.tooltip", webAudioEditorStrings),
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return !target.chrome && target.hasActor("webaudio");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new WebAudioEditorPanel(iframeWindow, toolbox);
}
};
Tools.scratchpad = {
id: "scratchpad",
ordinal: 12,
visibilityswitch: "devtools.scratchpad.enabled",
@@ -386,21 +386,21 @@ Tools.scratchpad = {
invertIconForLightTheme: true,
url: "chrome://devtools/content/scratchpad/scratchpad.xul",
label: l10n("scratchpad.label", scratchpadStrings),
panelLabel: l10n("scratchpad.panelLabel", scratchpadStrings),
tooltip: l10n("scratchpad.tooltip", scratchpadStrings),
inMenu: false,
commands: "devtools/client/scratchpad/scratchpad-commands",
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.hasActor("console");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new ScratchpadPanel(iframeWindow, toolbox);
}
};
Tools.dom = {
id: "dom",
accesskey: l10n("dom.accesskey", domStrings),
key: l10n("dom.commandkey", domStrings),
@@ -413,21 +413,21 @@ Tools.dom = {
label: l10n("dom.label", domStrings),
panelLabel: l10n("dom.panelLabel", domStrings),
get tooltip() {
return l10n("dom.tooltip", domStrings,
(osString == "Darwin" ? "Cmd+Opt+" : "Ctrl+Shift+") + this.key);
},
inMenu: true,
- isTargetSupported: function(target) {
+ isTargetSupported: function (target) {
return target.getTrait("webConsoleCommands");
},
- build: function(iframeWindow, toolbox) {
+ build: function (iframeWindow, toolbox) {
return new DomPanel(iframeWindow, toolbox);
}
};
var defaultTools = [
Tools.options,
Tools.webConsole,
Tools.inspector,
--- a/devtools/client/devtools-startup.js
+++ b/devtools/client/devtools-startup.js
@@ -23,17 +23,17 @@ const kDebuggerPrefs = [
"devtools.chrome.enabled"
];
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
function DevToolsStartup() {}
DevToolsStartup.prototype = {
- handle: function(cmdLine) {
+ handle: function (cmdLine) {
let consoleFlag = cmdLine.handleFlag("jsconsole", false);
let debuggerFlag = cmdLine.handleFlag("jsdebugger", false);
let devtoolsFlag = cmdLine.handleFlag("devtools", false);
if (consoleFlag) {
this.handleConsoleFlag(cmdLine);
}
if (debuggerFlag) {
@@ -47,38 +47,38 @@ DevToolsStartup.prototype = {
// We get an error if the option is given but not followed by a value.
// By catching and trying again, the value is effectively optional.
debuggerServerFlag = cmdLine.handleFlag("start-debugger-server", false);
}
if (debuggerServerFlag) {
this.handleDebuggerServerFlag(cmdLine, debuggerServerFlag);
}
- let onStartup = function(window) {
+ let onStartup = function (window) {
Services.obs.removeObserver(onStartup,
"browser-delayed-startup-finished");
// Ensure loading core module once firefox is ready
this.initDevTools();
if (devtoolsFlag) {
this.handleDevToolsFlag(window);
}
}.bind(this);
Services.obs.addObserver(onStartup, "browser-delayed-startup-finished",
false);
},
- initDevTools: function() {
+ initDevTools: function () {
let { loader } = Cu.import("resource://devtools/shared/Loader.jsm", {});
// Ensure loading main devtools module that hooks up into browser UI
// and initialize all devtools machinery.
loader.require("devtools/client/framework/devtools-browser");
},
- handleConsoleFlag: function(cmdLine) {
+ handleConsoleFlag: function (cmdLine) {
let window = Services.wm.getMostRecentWindow("devtools:webconsole");
if (!window) {
this.initDevTools();
let { require } = Cu.import("resource://devtools/shared/Loader.jsm", {});
let hudservice = require("devtools/client/webconsole/hudservice");
let { console } = Cu.import("resource://gre/modules/Console.jsm", {});
hudservice.toggleBrowserConsole().then(null, console.error);
@@ -88,17 +88,17 @@ DevToolsStartup.prototype = {
}
if (cmdLine.state == Ci.nsICommandLine.STATE_REMOTE_AUTO) {
cmdLine.preventDefault = true;
}
},
// Open the toolbox on the selected tab once the browser starts up.
- handleDevToolsFlag: function(window) {
+ handleDevToolsFlag: function (window) {
const {require} = Cu.import("resource://devtools/shared/Loader.jsm", {});
const {gDevTools} = require("devtools/client/framework/devtools");
const {TargetFactory} = require("devtools/client/framework/target");
let target = TargetFactory.forTab(window.gBrowser.selectedTab);
gDevTools.showToolbox(target);
},
_isRemoteDebuggingEnabled() {
@@ -117,29 +117,29 @@ DevToolsStartup.prototype = {
Cu.reportError(errorMsg);
// Dump as well, as we're doing this from a commandline, make sure people
// don't miss it:
dump(errorMsg + "\n");
}
return remoteDebuggingEnabled;
},
- handleDebuggerFlag: function(cmdLine) {
+ handleDebuggerFlag: function (cmdLine) {
if (!this._isRemoteDebuggingEnabled()) {
return;
}
Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm");
BrowserToolboxProcess.init();
if (cmdLine.state == Ci.nsICommandLine.STATE_REMOTE_AUTO) {
cmdLine.preventDefault = true;
}
},
- handleDebuggerServerFlag: function(cmdLine, portOrPath) {
+ handleDebuggerServerFlag: function (cmdLine, portOrPath) {
if (!this._isRemoteDebuggingEnabled()) {
return;
}
if (portOrPath === true) {
// Default to TCP port 6000 if no value given
portOrPath = 6000;
}
let { DevToolsLoader } =
--- a/devtools/client/dom/content/components/dom-tree.js
+++ b/devtools/client/dom/content/components/dom-tree.js
@@ -34,28 +34,28 @@ var DomTree = React.createClass({
},
displayName: "DomTree",
/**
* Filter DOM properties. Return true if the object
* should be visible in the tree.
*/
- onFilter: function(object) {
+ onFilter: function (object) {
if (!this.props.filter) {
return true;
}
return (object.name && object.name.indexOf(this.props.filter) > -1);
},
/**
* Render DOM panel content
*/
- render: function() {
+ render: function () {
let columns = [{
"id": "value"
}];
// This is the integration point with Reps. The DomTree is using
// Reps to render all values. The code also specifies default rep
// used for data types that don't have its own specific template.
let renderValue = props => {
--- a/devtools/client/dom/content/components/main-frame.js
+++ b/devtools/client/dom/content/components/main-frame.js
@@ -28,17 +28,17 @@ var MainFrame = React.createClass({
dispatch: PropTypes.func.isRequired,
},
displayName: "MainFrame",
/**
* Render DOM panel content
*/
- render: function() {
+ render: function () {
return (
div({className: "mainFrame"},
MainToolbar({
dispatch: this.props.dispatch,
object: this.props.object
}),
DomTree({
object: this.props.object,
--- a/devtools/client/dom/content/components/main-toolbar.js
+++ b/devtools/client/dom/content/components/main-toolbar.js
@@ -30,25 +30,25 @@ const PropTypes = React.PropTypes;
var MainToolbar = React.createClass({
propTypes: {
object: PropTypes.any.isRequired,
dispatch: PropTypes.func.isRequired,
},
displayName: "MainToolbar",
- onRefresh: function() {
+ onRefresh: function () {
this.props.dispatch(fetchProperties(this.props.object));
},
- onSearch: function(value) {
+ onSearch: function (value) {
this.props.dispatch(setVisibilityFilter(value));
},
- render: function() {
+ render: function () {
return (
Toolbar({},
ToolbarButton({
className: "btn refresh",
onClick: this.onRefresh},
l10n.getStr("dom.refresh")
),
SearchBox({
--- a/devtools/client/dom/content/components/search-box.js
+++ b/devtools/client/dom/content/components/search-box.js
@@ -22,40 +22,40 @@ const PropTypes = React.PropTypes;
*/
var SearchBox = React.createClass({
propTypes: {
onSearch: PropTypes.func,
},
displayName: "SearchBox",
- componentWillUnmount: function() {
+ componentWillUnmount: function () {
// Clean up an existing timeout.
if (this.searchTimeout) {
window.clearTimeout(this.searchTimeout);
}
},
- onSearch: function(event) {
+ onSearch: function (event) {
let searchBox = event.target;
// Clean up an existing timeout before creating a new one.
if (this.searchTimeout) {
window.clearTimeout(this.searchTimeout);
}
// Execute the search after a timeout. It makes the UX
// smoother if the user is typing quickly.
this.searchTimeout = window.setTimeout(() => {
this.searchTimeout = null;
this.props.onSearch(searchBox.value);
}, searchDelay);
},
- render: function() {
+ render: function () {
return (
input({
className: "searchBox",
placeholder: l10n.getStr("dom.filterDOMPanel"),
onChange: this.onSearch
})
);
}
--- a/devtools/client/dom/content/dom-decorator.js
+++ b/devtools/client/dom/content/dom-decorator.js
@@ -12,17 +12,17 @@ const { Property } = require("./reducers
function DomDecorator() {
}
/**
* Decorator for DOM panel tree component. It's responsible for
* appending an icon to read only properties.
*/
DomDecorator.prototype = {
- getRowClass: function(object) {
+ getRowClass: function (object) {
if (object instanceof Property) {
let value = object.value;
let names = [];
if (value.enumerable) {
names.push("enumerable");
}
if (value.writable) {
@@ -37,14 +37,14 @@ DomDecorator.prototype = {
return null;
},
/**
* Return custom React template for specified object. The template
* might depend on specified column.
*/
- getValueRep: function(value, colId) {
+ getValueRep: function (value, colId) {
}
};
// Exports from this module
exports.DomDecorator = DomDecorator;
--- a/devtools/client/dom/content/dom-view.js
+++ b/devtools/client/dom/content/dom-view.js
@@ -31,31 +31,31 @@ function DomView(localStore) {
addEventListener("devtools/chrome/message",
this.onMessage.bind(this), true);
// Make it local so, tests can access it.
this.store = localStore;
}
DomView.prototype = {
- initialize: function(rootGrip) {
+ initialize: function (rootGrip) {
let content = document.querySelector("#content");
let mainFrame = MainFrame({
object: rootGrip,
});
// Render top level component
let provider = React.createElement(Provider, {
store: this.store
}, mainFrame);
this.mainFrame = ReactDOM.render(provider, content);
},
- onMessage: function(event) {
+ onMessage: function (event) {
let data = event.data;
let method = data.type;
if (typeof this[method] == "function") {
this[method](data.args);
}
},
};
--- a/devtools/client/dom/content/grip-provider.js
+++ b/devtools/client/dom/content/grip-provider.js
@@ -18,17 +18,17 @@ function GripProvider(grips, dispatch) {
* This object provides data for the tree displayed in the tooltip
* content.
*/
GripProvider.prototype = {
/**
* Fetches properties from the backend. These properties might be
* displayed as child objects in e.g. a tree UI widget.
*/
- getChildren: function(object) {
+ getChildren: function (object) {
let grip = object;
if (object instanceof Property) {
grip = this.getValue(object);
}
if (!grip || !grip.actor) {
return [];
}
@@ -38,17 +38,17 @@ GripProvider.prototype = {
// Fetch missing data from the backend. Returning a promise
// from data provider causes the tree to show a spinner.
return this.dispatch(fetchProperties(grip));
}
return props;
},
- hasChildren: function(object) {
+ hasChildren: function (object) {
if (object instanceof Property) {
let value = this.getValue(object);
if (!value) {
return false;
}
let hasChildren = value.ownPropertyLength > 0;
@@ -65,33 +65,33 @@ GripProvider.prototype = {
}
return (value.type == "object" && hasChildren);
}
return null;
},
- getValue: function(object) {
+ getValue: function (object) {
if (object instanceof Property) {
let value = object.value;
return (typeof value.value != "undefined") ? value.value :
value.getterValue;
}
return object;
},
- getLabel: function(object) {
+ getLabel: function (object) {
return (object instanceof Property) ? object.name : null;
},
- getKey: function(object) {
+ getKey: function (object) {
return (object instanceof Property) ? object.key : null;
},
- getType: function(object) {
+ getType: function (object) {
return object.class ? object.class : "";
},
};
// Exports from this module
exports.GripProvider = GripProvider;
--- a/devtools/client/dom/content/utils.js
+++ b/devtools/client/dom/content/utils.js
@@ -5,17 +5,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/**
* The default localization just returns the last part of the key
* (all after the last dot).
*/
const DefaultL10N = {
- getStr: function(key) {
+ getStr: function (key) {
let index = key.lastIndexOf(".");
return key.substr(index + 1);
}
};
/**
* The 'l10n' object is set by main.js in case the DOM panel content
* runs within a scope with chrome privileges.
--- a/devtools/client/dom/dom-panel.js
+++ b/devtools/client/dom/dom-panel.js
@@ -55,17 +55,17 @@ DomPanel.prototype = {
this.emit("ready");
deferred.resolve(this);
return this._opening;
}),
// Initialization
- initialize: function() {
+ initialize: function () {
this.panelWin.addEventListener("devtools/content/message",
this.onContentMessage, true);
this.target.on("navigate", this.onTabNavigated);
this._toolbox.on("select", this.onPanelVisibilityChange);
let provider = {
getPrototypeAndProperties: this.getPrototypeAndProperties.bind(this)
@@ -90,17 +90,17 @@ DomPanel.prototype = {
this.emit("destroyed");
deferred.resolve();
return this._destroying;
}),
// Events
- refresh: function() {
+ refresh: function () {
// Do not refresh if the panel isn't visible.
if (!this.isPanelVisible()) {
return;
}
// Do not refresh if it isn't necessary.
if (!this.shouldRefresh) {
return;
@@ -114,38 +114,38 @@ DomPanel.prototype = {
});
},
/**
* Make sure the panel is refreshed when the page is reloaded.
* The panel is refreshed immediatelly if it's currently selected
* or lazily when the user actually selects it.
*/
- onTabNavigated: function() {
+ onTabNavigated: function () {
this.shouldRefresh = true;
this.refresh();
},
/**
* Make sure the panel is refreshed (if needed) when it's selected.
*/
- onPanelVisibilityChange: function() {
+ onPanelVisibilityChange: function () {
this.refresh();
},
// Helpers
/**
* Return true if the DOM panel is currently selected.
*/
- isPanelVisible: function() {
+ isPanelVisible: function () {
return this._toolbox.currentToolId === "dom";
},
- getPrototypeAndProperties: function(grip) {
+ getPrototypeAndProperties: function (grip) {
let deferred = defer();
if (!grip.actor) {
console.error("No actor!", grip);
deferred.reject(new Error("Failed to get actor from grip."));
return deferred.promise;
}
@@ -172,44 +172,44 @@ DomPanel.prototype = {
}
});
this.pendingRequests.set(grip.actor, deferred.promise);
return deferred.promise;
},
- getRootGrip: function() {
+ getRootGrip: function () {
let deferred = defer();
// Attach Console. It might involve RDP communication, so wait
// asynchronously for the result
this.target.activeConsole.evaluateJSAsync("window", res => {
deferred.resolve(res.result);
});
return deferred.promise;
},
- postContentMessage: function(type, args) {
+ postContentMessage: function (type, args) {
let data = {
type: type,
args: args,
};
let event = new this.panelWin.MessageEvent("devtools/chrome/message", {
bubbles: true,
cancelable: true,
data: data,
});
this.panelWin.dispatchEvent(event);
},
- onContentMessage: function(event) {
+ onContentMessage: function (event) {
let data = event.data;
let method = data.type;
if (typeof this[method] == "function") {
this[method](data.args);
}
},
get target() {
--- a/devtools/client/inspector/layout/layout.js
+++ b/devtools/client/inspector/layout/layout.js
@@ -38,30 +38,30 @@ function EditingSession(doc, rules) {
EditingSession.prototype = {
/**
* Gets the value of a single property from the CSS rule.
*
* @param rule The CSS rule
* @param property The name of the property
*/
- getPropertyFromRule: function(rule, property) {
+ getPropertyFromRule: function (rule, property) {
let dummyStyle = this._element.style;
dummyStyle.cssText = rule.cssText;
return dummyStyle.getPropertyValue(property);
},
/**
* Returns the current value for a property as a string or the empty string if
* no style rules affect the property.
*
* @param property The name of the property as a string
*/
- getProperty: function(property) {
+ getProperty: function (property) {
// Create a hidden element for getPropertyFromRule to use
let div = this._doc.createElement("div");
div.setAttribute("style", "display: none");
this._doc.getElementById("sidebar-panel-layoutview").appendChild(div);
this._element = this._doc.createElement("p");
div.appendChild(this._element);
// As the rules are in order of priority we can just iterate until we find
@@ -80,17 +80,17 @@ EditingSession.prototype = {
/**
* Sets a number of properties on the node. Returns a promise that will be
* resolved when the modifications are complete.
*
* @param properties An array of properties, each is an object with name and
* value properties. If the value is "" then the property
* is removed.
*/
- setProperties: function(properties) {
+ setProperties: function (properties) {
let modifications = this._rules[0].startModifyingProperties();
for (let property of properties) {
if (!this._modifications.has(property.name)) {
this._modifications.set(property.name,
this.getPropertyFromRule(this._rules[0], property.name));
}
@@ -103,31 +103,31 @@ EditingSession.prototype = {
return modifications.apply().then(null, console.error);
},
/**
* Reverts all of the property changes made by this instance. Returns a
* promise that will be resolved when complete.
*/
- revert: function() {
+ revert: function () {
let modifications = this._rules[0].startModifyingProperties();
for (let [property, value] of this._modifications) {
if (value != "") {
modifications.setProperty(-1, property, value, "");
} else {
modifications.removeProperty(-1, property);
}
}
return modifications.apply().then(null, console.error);
},
- destroy: function() {
+ destroy: function () {
this._doc = null;
this._rules = null;
this._modifications.clear();
}
};
/**
* The layout-view panel
@@ -141,17 +141,17 @@ function LayoutView(inspector, win) {
this.sizeLabel = this.doc.querySelector(".layout-size > span");
this.sizeHeadingLabel = this.doc.getElementById("layout-element-size");
this._geometryEditorHighlighter = null;
this.init();
}
LayoutView.prototype = {
- init: function() {
+ init: function () {
this.update = this.update.bind(this);
this.onNewSelection = this.onNewSelection.bind(this);
this.inspector.selection.on("new-node-front", this.onNewSelection);
this.onNewNode = this.onNewNode.bind(this);
this.inspector.sidebar.on("layoutview-selected", this.onNewNode);
@@ -261,31 +261,31 @@ LayoutView.prototype = {
container.setAttribute("dir", dir ? "rtl" : "ltr");
let nodeGeometry = this.doc.getElementById("layout-geometry-editor");
this.onGeometryButtonClick = this.onGeometryButtonClick.bind(this);
nodeGeometry.addEventListener("click", this.onGeometryButtonClick);
},
- initBoxModelHighlighter: function() {
+ initBoxModelHighlighter: function () {
let highlightElts = this.doc.querySelectorAll("#layout-container *[title]");
this.onHighlightMouseOver = this.onHighlightMouseOver.bind(this);
this.onHighlightMouseOut = this.onHighlightMouseOut.bind(this);
for (let element of highlightElts) {
element.addEventListener("mouseover", this.onHighlightMouseOver, true);
element.addEventListener("mouseout", this.onHighlightMouseOut, true);
}
},
/**
* Start listening to reflows in the current tab.
*/
- trackReflows: function() {
+ trackReflows: function () {
if (!this.reflowFront) {
let toolbox = this.inspector.toolbox;
if (toolbox.target.form.reflowActor) {
this.reflowFront = ReflowFront(toolbox.target.client,
toolbox.target.form);
} else {
return;
}
@@ -293,29 +293,29 @@ LayoutView.prototype = {
this.reflowFront.on("reflows", this.update);
this.reflowFront.start();
},
/**
* Stop listening to reflows in the current tab.
*/
- untrackReflows: function() {
+ untrackReflows: function () {
if (!this.reflowFront) {
return;
}
this.reflowFront.off("reflows", this.update);
this.reflowFront.stop();
},
/**
* Called when the user clicks on one of the editable values in the layoutview
*/
- initEditor: function(element, event, dimension) {
+ initEditor: function (element, event, dimension) {
let { property } = dimension;
let session = new EditingSession(this.doc, this.elementRules);
let initialValue = session.getProperty(property);
let editor = new InplaceEditor({
element: element,
initial: initialValue,
contentType: InplaceEditor.CONTENT_TYPES.CSS_VALUE,
@@ -355,36 +355,36 @@ LayoutView.prototype = {
}
}, event);
},
/**
* Is the layoutview visible in the sidebar.
* @return {Boolean}
*/
- isViewVisible: function() {
+ isViewVisible: function () {
return this.inspector &&
this.inspector.sidebar.getCurrentTabID() == "layoutview";
},
/**
* Is the layoutview visible in the sidebar and is the current node valid to
* be displayed in the view.
* @return {Boolean}
*/
- isViewVisibleAndNodeValid: function() {
+ isViewVisibleAndNodeValid: function () {
return this.isViewVisible() &&
this.inspector.selection.isConnected() &&
this.inspector.selection.isElementNode();
},
/**
* Destroy the nodes. Remove listeners.
*/
- destroy: function() {
+ destroy: function () {
let highlightElts = this.doc.querySelectorAll("#layout-container *[title]");
for (let element of highlightElts) {
element.removeEventListener("mouseover", this.onHighlightMouseOver, true);
element.removeEventListener("mouseout", this.onHighlightMouseOut, true);
}
let nodeGeometry = this.doc.getElementById("layout-geometry-editor");
@@ -412,91 +412,91 @@ LayoutView.prototype = {
if (this.reflowFront) {
this.untrackReflows();
this.reflowFront.destroy();
this.reflowFront = null;
}
},
- onSidebarSelect: function(e, sidebar) {
+ onSidebarSelect: function (e, sidebar) {
this.setActive(sidebar === "layoutview");
},
/**
* Selection 'new-node-front' event handler.
*/
- onNewSelection: function() {
+ onNewSelection: function () {
let done = this.inspector.updating("layoutview");
this.onNewNode()
.then(() => this.hideGeometryEditor())
.then(done, (err) => {
console.error(err);
done();
}).catch(console.error);
},
/**
* @return a promise that resolves when the view has been updated
*/
- onNewNode: function() {
+ onNewNode: function () {
this.setActive(this.isViewVisibleAndNodeValid());
return this.update();
},
- onHighlightMouseOver: function(e) {
+ onHighlightMouseOver: function (e) {
let region = e.target.getAttribute("data-box");
if (!region) {
return;
}
this.showBoxModel({
region,
showOnly: region,
onlyRegionArea: true
});
},
- onHighlightMouseOut: function() {
+ onHighlightMouseOut: function () {
this.hideBoxModel();
},
- onGeometryButtonClick: function({target}) {
+ onGeometryButtonClick: function ({target}) {
if (target.hasAttribute("checked")) {
target.removeAttribute("checked");
this.hideGeometryEditor();
} else {
target.setAttribute("checked", "true");
this.showGeometryEditor();
}
},
- onPickerStarted: function() {
+ onPickerStarted: function () {
this.hideGeometryEditor();
},
- onMarkupViewLeave: function() {
+ onMarkupViewLeave: function () {
this.showGeometryEditor(true);
},
- onMarkupViewNodeHover: function() {
+ onMarkupViewNodeHover: function () {
this.hideGeometryEditor(false);
},
- onWillNavigate: function() {
+ onWillNavigate: function () {
this._geometryEditorHighlighter.release().catch(console.error);
this._geometryEditorHighlighter = null;
},
/**
* Stop tracking reflows and hide all values when no node is selected or the
* layout-view is hidden, otherwise track reflows and show values.
* @param {Boolean} isActive
*/
- setActive: function(isActive) {
+ setActive: function (isActive) {
if (isActive === this.isActive) {
return;
}
this.isActive = isActive;
let panel = this.doc.getElementById("sidebar-panel-layoutview");
panel.classList.toggle("inactive", !isActive);
@@ -507,17 +507,17 @@ LayoutView.prototype = {
}
},
/**
* Compute the dimensions of the node and update the values in
* the layoutview/view.xhtml document.
* @return a promise that will be resolved when complete.
*/
- update: function() {
+ update: function () {
let lastRequest = Task.spawn((function* () {
if (!this.isViewVisibleAndNodeValid()) {
return null;
}
let node = this.inspector.selection.nodeFront;
let layout = yield this.inspector.pageStyle.getLayout(node, {
autoMargins: this.isActive
@@ -614,17 +614,17 @@ LayoutView.prototype = {
/**
* Update the text in the tooltip shown when hovering over a value to provide
* information about the source CSS rule that sets this value.
* @param {DOMNode} el The element that will receive the tooltip.
* @param {String} property The name of the CSS property for the tooltip.
* @param {Array} rules An array of applied rules retrieved by
* styleActor.getApplied.
*/
- updateSourceRuleTooltip: function(el, property, rules) {
+ updateSourceRuleTooltip: function (el, property, rules) {
// Dummy element used to parse the cssText of applied rules.
let dummyEl = this.doc.createElement("div");
// Rules are in order of priority so iterate until we find the first that
// defines a value for the property.
let sourceRule, value;
for (let {rule} of rules) {
dummyEl.style.cssText = rule.cssText;
@@ -644,39 +644,39 @@ LayoutView.prototype = {
}
el.setAttribute("title", title);
},
/**
* Show the box-model highlighter on the currently selected element
* @param {Object} options Options passed to the highlighter actor
*/
- showBoxModel: function(options = {}) {
+ showBoxModel: function (options = {}) {
let toolbox = this.inspector.toolbox;
let nodeFront = this.inspector.selection.nodeFront;
toolbox.highlighterUtils.highlightNodeFront(nodeFront, options);
},
/**
* Hide the box-model highlighter on the currently selected element
*/
- hideBoxModel: function() {
+ hideBoxModel: function () {
let toolbox = this.inspector.toolbox;
toolbox.highlighterUtils.unhighlight();
},
/**
* Show the geometry editor highlighter on the currently selected element
* @param {Boolean} [showOnlyIfActive=false]
* Indicates if the Geometry Editor should be shown only if it's active but
* hidden.
*/
- showGeometryEditor: function(showOnlyIfActive = false) {
+ showGeometryEditor: function (showOnlyIfActive = false) {
let toolbox = this.inspector.toolbox;
let nodeFront = this.inspector.selection.nodeFront;
let nodeGeometry = this.doc.getElementById("layout-geometry-editor");
let isActive = nodeGeometry.hasAttribute("checked");
if (showOnlyIfActive && !isActive) {
return;
}
@@ -704,17 +704,17 @@ LayoutView.prototype = {
});
},
/**
* Hide the geometry editor highlighter on the currently selected element
* @param {Boolean} [updateButton=true]
* Indicates if the Geometry Editor's button needs to be unchecked too
*/
- hideGeometryEditor: function(updateButton = true) {
+ hideGeometryEditor: function (updateButton = true) {
if (this._geometryEditorHighlighter) {
this._geometryEditorHighlighter.hide().catch(console.error);
}
if (updateButton) {
let nodeGeometry = this.doc.getElementById("layout-geometry-editor");
nodeGeometry.removeAttribute("checked");
}
@@ -731,17 +731,17 @@ LayoutView.prototype = {
if (node) {
isEditable = yield this.inspector.pageStyle.isPositionEditable(node);
}
let nodeGeometry = this.doc.getElementById("layout-geometry-editor");
nodeGeometry.style.visibility = isEditable ? "visible" : "hidden";
}),
- manageOverflowingText: function(span) {
+ manageOverflowingText: function (span) {
let classList = span.parentNode.classList;
if (classList.contains("layout-left") ||
classList.contains("layout-right")) {
let force = span.textContent.length > LONG_TEXT_ROTATE_LIMIT;
classList.toggle("layout-rotate", force);
}
}
--- a/devtools/client/inspector/layout/test/browser_layout_guides.js
+++ b/devtools/client/inspector/layout/test/browser_layout_guides.js
@@ -18,17 +18,17 @@ const TEST_URL = "data:text/html;charset
var highlightedNodeFront, highlighterOptions;
add_task(function* () {
yield addTab(TEST_URL);
let {toolbox, inspector, view} = yield openLayoutView();
yield selectNode("div", inspector);
// Mock the highlighter by replacing the showBoxModel method.
- toolbox.highlighter.showBoxModel = function(nodeFront, options) {
+ toolbox.highlighter.showBoxModel = function (nodeFront, options) {
highlightedNodeFront = nodeFront;
highlighterOptions = options;
};
let elt = view.doc.getElementById("layout-margins");
yield testGuideOnLayoutHover(elt, "margin", inspector, view);
elt = view.doc.getElementById("layout-borders");
--- a/devtools/client/inspector/layout/test/head.js
+++ b/devtools/client/inspector/layout/test/head.js
@@ -54,20 +54,20 @@ function selectAndHighlightNode(nodeOrSe
* @return a promise that resolves when the inspector is ready and the layout
* view is visible and ready
*/
function openLayoutView() {
return openInspectorSidebarTab("layoutview").then(data => {
// The actual highligher show/hide methods are mocked in layoutview tests.
// The highlighter is tested in devtools/inspector/test.
function mockHighlighter({highlighter}) {
- highlighter.showBoxModel = function() {
+ highlighter.showBoxModel = function () {
return promise.resolve();
};
- highlighter.hideBoxModel = function() {
+ highlighter.hideBoxModel = function () {
return promise.resolve();
};
}
mockHighlighter(data.toolbox);
return {
toolbox: data.toolbox,
inspector: data.inspector,
--- a/devtools/client/inspector/markup/html-editor.js
+++ b/devtools/client/inspector/markup/html-editor.js
@@ -65,17 +65,17 @@ function HTMLEditor(htmlDocument) {
}
HTMLEditor.prototype = {
/**
* Need to refresh position by manually setting CSS values, so this will
* need to be called on resizes and other sizing changes.
*/
- refresh: function() {
+ refresh: function () {
let element = this._attachedElement;
if (element) {
this.container.style.top = element.offsetTop + "px";
this.container.style.left = element.offsetLeft + "px";
this.container.style.width = element.offsetWidth + "px";
this.container.style.height = element.parentNode.offsetHeight + "px";
this.editor.refresh();
@@ -84,27 +84,27 @@ HTMLEditor.prototype = {
/**
* Anchor the editor to a particular element.
*
* @param DOMNode element
* The element that the editor will be anchored to.
* Should belong to the HTMLDocument passed into the constructor.
*/
- _attach: function(element) {
+ _attach: function (element) {
this._detach();
this._attachedElement = element;
element.classList.add("html-editor-container");
this.refresh();
},
/**
* Unanchor the editor from an element.
*/
- _detach: function() {
+ _detach: function () {
if (this._attachedElement) {
this._attachedElement.classList.remove("html-editor-container");
this._attachedElement = undefined;
}
},
/**
* Anchor the editor to a particular element, and show the editor.
@@ -112,17 +112,17 @@ HTMLEditor.prototype = {
* @param DOMNode element
* The element that the editor will be anchored to.
* Should belong to the HTMLDocument passed into the constructor.
* @param string text
* Value to set the contents of the editor to
* @param function cb
* The function to call when hiding
*/
- show: function(element, text) {
+ show: function (element, text) {
if (this._visible) {
return;
}
this._originalValue = text;
this.editor.setText(text);
this._attach(element);
this.container.style.display = "flex";
@@ -136,17 +136,17 @@ HTMLEditor.prototype = {
/**
* Hide the editor, optionally committing the changes
*
* @param bool shouldCommit
* A change will be committed by default. If this param
* strictly equals false, no change will occur.
*/
- hide: function(shouldCommit) {
+ hide: function (shouldCommit) {
if (!this._visible) {
return;
}
this.container.style.display = "none";
this._detach();
let newValue = this.editor.getText();
@@ -155,17 +155,17 @@ HTMLEditor.prototype = {
this._originalValue = undefined;
this._visible = undefined;
this.emit("popuphidden", !preventCommit, newValue);
},
/**
* Destroy this object and unbind all event handlers
*/
- destroy: function() {
+ destroy: function () {
this.doc.defaultView.removeEventListener("resize",
this.refresh, true);
this.container.removeEventListener("click", this.hide, false);
this.editorInner.removeEventListener("click", stopPropagation, false);
this.hide(false);
this.container.remove();
this.editor.destroy();
--- a/devtools/client/inspector/markup/markup.js
+++ b/devtools/client/inspector/markup/markup.js
@@ -154,39 +154,39 @@ function MarkupView(inspector, frame, co
MarkupView.prototype = {
/**
* How long does a node flash when it mutates (in ms).
*/
CONTAINER_FLASHING_DURATION: 500,
_selectedContainer: null,
- _initTooltips: function() {
+ _initTooltips: function () {
this.tooltip = new Tooltip(this._inspector.panelDoc);
this._makeTooltipPersistent(false);
},
- _makeTooltipPersistent: function(state) {
+ _makeTooltipPersistent: function (state) {
if (state) {
this.tooltip.stopTogglingOnHover();
} else {
this.tooltip.startTogglingOnHover(this._elt,
this._isImagePreviewTarget.bind(this));
}
},
- _onToolboxPickerHover: function(event, nodeFront) {
+ _onToolboxPickerHover: function (event, nodeFront) {
this.showNode(nodeFront).then(() => {
this._showContainerAsHovered(nodeFront);
}, e => console.error(e));
},
isDragging: false,
- _onMouseMove: function(event) {
+ _onMouseMove: function (event) {
let target = event.target;
// Auto-scroll if we're dragging.
if (this.isDragging) {
event.preventDefault();
this._autoScroll(event);
return;
}
@@ -213,17 +213,17 @@ MarkupView.prototype = {
this.emit("node-hover");
},
/**
* Executed on each mouse-move while a node is being dragged in the view.
* Auto-scrolls the view to reveal nodes below the fold to drop the dragged
* node in.
*/
- _autoScroll: function(event) {
+ _autoScroll: function (event) {
let docEl = this.doc.documentElement;
if (this._autoScrollInterval) {
clearInterval(this._autoScrollInterval);
}
// Auto-scroll when the mouse approaches top/bottom edge.
let fromBottom = docEl.clientHeight - event.pageY + this.win.scrollY;
@@ -249,17 +249,17 @@ MarkupView.prototype = {
DRAG_DROP_MIN_AUTOSCROLL_SPEED, DRAG_DROP_MAX_AUTOSCROLL_SPEED);
this._autoScrollInterval = setInterval(() => {
docEl.scrollTop += speed - DRAG_DROP_MAX_AUTOSCROLL_SPEED;
}, 0);
}
},
- _onMouseClick: function(event) {
+ _onMouseClick: function (event) {
// From the target passed here, let's find the parent MarkupContainer
// and ask it if the tooltip should be shown
let parentNode = event.target;
let container;
while (parentNode !== this.doc.body) {
if (parentNode.container) {
container = parentNode.container;
break;
@@ -269,33 +269,33 @@ MarkupView.prototype = {
if (container instanceof MarkupElementContainer) {
// With the newly found container, delegate the tooltip content creation
// and decision to show or not the tooltip
container._buildEventTooltipContent(event.target, this.tooltip);
}
},
- _onMouseUp: function() {
+ _onMouseUp: function () {
this.indicateDropTarget(null);
this.indicateDragTarget(null);
if (this._autoScrollInterval) {
clearInterval(this._autoScrollInterval);
}
},
- _onCollapseAttributesPrefChange: function() {
+ _onCollapseAttributesPrefChange: function () {
this.collapseAttributes =
Services.prefs.getBoolPref(ATTR_COLLAPSE_ENABLED_PREF);
this.collapseAttributeLength =
Services.prefs.getIntPref(ATTR_COLLAPSE_LENGTH_PREF);
this.update();
},
- cancelDragging: function() {
+ cancelDragging: function () {
if (!this.isDragging) {
return;
}
for (let [, container] of this._containers) {
if (container.isDragging) {
container.cancelDragging();
break;
@@ -312,30 +312,30 @@ MarkupView.prototype = {
_hoveredNode: null,
/**
* Show a NodeFront's container as being hovered
*
* @param {NodeFront} nodeFront
* The node to show as hovered
*/
- _showContainerAsHovered: function(nodeFront) {
+ _showContainerAsHovered: function (nodeFront) {
if (this._hoveredNode === nodeFront) {
return;
}
if (this._hoveredNode) {
this.getContainer(this._hoveredNode).hovered = false;
}
this.getContainer(nodeFront).hovered = true;
this._hoveredNode = nodeFront;
},
- _onMouseLeave: function() {
+ _onMouseLeave: function () {
if (this._autoScrollInterval) {
clearInterval(this._autoScrollInterval);
}
if (this.isDragging) {
return;
}
this._hideBoxModel(true);
@@ -351,77 +351,77 @@ MarkupView.prototype = {
* Show the box model highlighter on a given node front
*
* @param {NodeFront} nodeFront
* The node to show the highlighter for
* @return {Promise} Resolves when the highlighter for this nodeFront is
* shown, taking into account that there could already be highlighter
* requests queued up
*/
- _showBoxModel: function(nodeFront) {
+ _showBoxModel: function (nodeFront) {
return this._inspector.toolbox.highlighterUtils
.highlightNodeFront(nodeFront);
},
/**
* Hide the box model highlighter on a given node front
*
* @param {NodeFront} nodeFront
* The node to hide the highlighter for
* @param {Boolean} forceHide
* See toolbox-highlighter-utils/unhighlight
* @return {Promise} Resolves when the highlighter for this nodeFront is
* hidden, taking into account that there could already be highlighter
* requests queued up
*/
- _hideBoxModel: function(forceHide) {
+ _hideBoxModel: function (forceHide) {
return this._inspector.toolbox.highlighterUtils.unhighlight(forceHide);
},
_briefBoxModelTimer: null,
- _clearBriefBoxModelTimer: function() {
+ _clearBriefBoxModelTimer: function () {
if (this._briefBoxModelTimer) {
clearTimeout(this._briefBoxModelTimer);
this._briefBoxModelPromise.resolve();
this._briefBoxModelPromise = null;
this._briefBoxModelTimer = null;
}
},
- _brieflyShowBoxModel: function(nodeFront) {
+ _brieflyShowBoxModel: function (nodeFront) {
this._clearBriefBoxModelTimer();
let onShown = this._showBoxModel(nodeFront);
this._briefBoxModelPromise = promise.defer();
this._briefBoxModelTimer = setTimeout(() => {
this._hideBoxModel()
.then(this._briefBoxModelPromise.resolve,
this._briefBoxModelPromise.resolve);
}, NEW_SELECTION_HIGHLIGHTER_TIMER);
return promise.all([onShown, this._briefBoxModelPromise.promise]);
},
- template: function(name, dest, options = {stack: "markup.xhtml"}) {
+ template: function (name, dest, options = {stack: "markup.xhtml"}) {
let node = this.doc.getElementById("template-" + name).cloneNode(true);
node.removeAttribute("id");
template(node, dest, options);
return node;
},
/**
* Get the MarkupContainer object for a given node, or undefined if
* none exists.
*/
- getContainer: function(node) {
+ getContainer: function (node) {
return this._containers.get(node);
},
- update: function() {
+ update: function () {
let updateChildren = (node) => {
this.getContainer(node).update();
for (let child of node.treeChildren()) {
updateChildren(child);
}
};
// Start with the documentElement
@@ -442,17 +442,17 @@ MarkupView.prototype = {
* to decide whether this target should be used to display an image preview
* tooltip.
* Delegates the actual decision to the corresponding MarkupContainer instance
* if one is found.
*
* @return {Promise} the promise returned by
* MarkupElementContainer._isImagePreviewTarget
*/
- _isImagePreviewTarget: function(target) {
+ _isImagePreviewTarget: function (target) {
// From the target passed here, let's find the parent MarkupContainer
// and ask it if the tooltip should be shown
if (this.isDragging) {
return promise.reject(false);
}
let parent = target, container;
while (parent !== this.doc.body) {
@@ -481,34 +481,34 @@ MarkupView.prototype = {
* - if it's "navigateaway" (since the page is being navigated away from)
* - if it's "test" (this is a special case for mochitest. In tests, we often
* need to select elements but don't necessarily want the highlighter to come
* and go after a delay as this might break test scenarios)
* We also do not want to start a brief highlight timeout if the node is
* already being hovered over, since in that case it will already be
* highlighted.
*/
- _shouldNewSelectionBeHighlighted: function() {
+ _shouldNewSelectionBeHighlighted: function () {
let reason = this._inspector.selection.reason;
let unwantedReasons = [
"inspector-open",
"navigateaway",
"nodeselected",
"test"
];
let isHighlight = this._hoveredNode === this._inspector.selection.nodeFront;
return !isHighlight && reason && unwantedReasons.indexOf(reason) === -1;
},
/**
* React to new-node-front selection events.
* Highlights the node if needed, and make sure it is shown and selected in
* the view.
*/
- _onNewSelection: function() {
+ _onNewSelection: function () {
let selection = this._inspector.selection;
this.htmlEditor.hide();
if (this._hoveredNode && this._hoveredNode !== selection.nodeFront) {
this.getContainer(this._hoveredNode).hovered = false;
this._hoveredNode = null;
}
@@ -548,17 +548,17 @@ MarkupView.prototype = {
promise.all([onShowBoxModel, onShow]).then(done);
},
/**
* Maybe focus the current node selection's MarkupContainer depending on why
* the current node got selected.
*/
- maybeFocusNewSelection: function() {
+ maybeFocusNewSelection: function () {
let {reason, nodeFront} = this._inspector.selection;
// The list of reasons that should lead to focusing the node.
let reasonsToFocus = [
// If the user picked an element with the element picker.
"picker-node-picked",
// If the user selected an element with the browser context menu.
"browser-context-menu",
@@ -570,51 +570,51 @@ MarkupView.prototype = {
this.getContainer(nodeFront).focus();
}
},
/**
* Create a TreeWalker to find the next/previous
* node for selection.
*/
- _selectionWalker: function(start) {
+ _selectionWalker: function (start) {
let walker = this.doc.createTreeWalker(
start || this._elt,
Ci.nsIDOMNodeFilter.SHOW_ELEMENT,
- function(element) {
+ function (element) {
if (element.container &&
element.container.elt === element &&
element.container.visible) {
return Ci.nsIDOMNodeFilter.FILTER_ACCEPT;
}
return Ci.nsIDOMNodeFilter.FILTER_SKIP;
}
);
walker.currentNode = this._selectedContainer.elt;
return walker;
},
- _onCopy: function(evt) {
+ _onCopy: function (evt) {
// Ignore copy events from editors
if (this._isInputOrTextarea(evt.target)) {
return;
}
let selection = this._inspector.selection;
if (selection.isNode()) {
this._inspector.copyOuterHTML();
}
evt.stopPropagation();
evt.preventDefault();
},
/**
* Key handling.
*/
- _onKeyDown: function(event) {
+ _onKeyDown: function (event) {
let handled = true;
let previousNode, nextNode;
// Ignore keystrokes that originated in editors.
if (this._isInputOrTextarea(event.target)) {
return;
}
@@ -725,30 +725,30 @@ MarkupView.prototype = {
event.stopPropagation();
event.preventDefault();
}
},
/**
* Check if a node is an input or textarea
*/
- _isInputOrTextarea: function(element) {
+ _isInputOrTextarea: function (element) {
let name = element.tagName.toLowerCase();
return name === "input" || name === "textarea";
},
/**
* If there's an attribute on the current node that's currently focused, then
* delete this attribute, otherwise delete the node itself.
*
* @param {Boolean} moveBackward
* If set to true and if we're deleting the node, focus the previous
* sibling after deletion, otherwise the next one.
*/
- deleteNodeOrAttribute: function(moveBackward) {
+ deleteNodeOrAttribute: function (moveBackward) {
let focusedAttribute = this.doc.activeElement
? this.doc.activeElement.closest(".attreditor")
: null;
if (focusedAttribute) {
// The focused attribute might not be in the current selected container.
let container = focusedAttribute.closest("li.child").container;
container.removeAttribute(focusedAttribute.dataset.attr);
} else {
@@ -760,17 +760,17 @@ MarkupView.prototype = {
* Delete a node from the DOM.
* This is an undoable action.
*
* @param {NodeFront} node
* The node to remove.
* @param {Boolean} moveBackward
* If set to true, focus the previous sibling, otherwise the next one.
*/
- deleteNode: function(node, moveBackward) {
+ deleteNode: function (node, moveBackward) {
if (node.isDocumentElement ||
node.nodeType == Ci.nsIDOMNode.DOCUMENT_TYPE_NODE ||
node.isAnonymous) {
return;
}
let container = this.getContainer(node);
@@ -797,17 +797,17 @@ MarkupView.prototype = {
this.walker.insertBefore(node, parent, nextSibling);
});
}).then(null, console.error);
},
/**
* If an editable item is focused, select its container.
*/
- _onFocus: function(event) {
+ _onFocus: function (event) {
let parent = event.target;
while (!parent.container) {
parent = parent.parentNode;
}
if (parent) {
this.navigate(parent.container, true);
}
},
@@ -816,17 +816,17 @@ MarkupView.prototype = {
* Handle a user-requested navigation to a given MarkupContainer,
* updating the inspector's currently-selected node.
*
* @param {MarkupContainer} container
* The container we're navigating to.
* @param {Boolean} ignoreFocus
* If false, keyboard focus will be moved to the container too.
*/
- navigate: function(container, ignoreFocus) {
+ navigate: function (container, ignoreFocus) {
if (!container) {
return;
}
let node = container.node;
this.markNodeAsSelected(node, "treepanel");
if (!ignoreFocus) {
@@ -838,17 +838,17 @@ MarkupView.prototype = {
* Make sure a node is included in the markup tool.
*
* @param {NodeFront} node
* The node in the content document.
* @param {Boolean} flashNode
* Whether the newly imported node should be flashed
* @return {MarkupContainer} The MarkupContainer object for this element.
*/
- importNode: function(node, flashNode) {
+ importNode: function (node, flashNode) {
if (!node) {
return null;
}
if (this._containers.has(node)) {
return this.getContainer(node);
}
@@ -879,17 +879,17 @@ MarkupView.prototype = {
this._inspector.emit("container-created", container);
return container;
},
/**
* Mutation observer used for included nodes.
*/
- _mutationObserver: function(mutations) {
+ _mutationObserver: function (mutations) {
for (let mutation of mutations) {
let type = mutation.type;
let target = mutation.target;
if (mutation.type === "documentUnload") {
// Treat this as a childList change of the child (maybe the protocol
// should do this).
type = "childList";
@@ -931,30 +931,30 @@ MarkupView.prototype = {
},
/**
* React to display-change events from the walker
*
* @param {Array} nodes
* An array of nodeFronts
*/
- _onDisplayChange: function(nodes) {
+ _onDisplayChange: function (nodes) {
for (let node of nodes) {
let container = this.getContainer(node);
if (container) {
container.isDisplayed = node.isDisplayed;
}
}
},
/**
* Given a list of mutations returned by the mutation observer, flash the
* corresponding containers to attract attention.
*/
- _flashMutatedNodes: function(mutations) {
+ _flashMutatedNodes: function (mutations) {
let addedOrEditedContainers = new Set();
let removedContainers = new Set();
for (let {type, target, added, removed, newValue} of mutations) {
let container = this.getContainer(target);
if (container) {
if (type === "characterData") {
@@ -995,17 +995,17 @@ MarkupView.prototype = {
container.flashMutation();
}
},
/**
* Make sure the given node's parents are expanded and the
* node is scrolled on to screen.
*/
- showNode: function(node, centered = true) {
+ showNode: function (node, centered = true) {
let parent = node;
this.importNode(node);
while ((parent = parent.parentNode())) {
this.importNode(parent);
this.expandNode(parent);
}
@@ -1027,42 +1027,42 @@ MarkupView.prototype = {
"while waiting for children");
}
});
},
/**
* Expand the container's children.
*/
- _expandContainer: function(container) {
+ _expandContainer: function (container) {
return this._updateChildren(container, {expand: true}).then(() => {
if (this._destroyer) {
console.warn("Could not expand the node, the markup-view was " +
"destroyed");
return;
}
container.setExpanded(true);
});
},
/**
* Expand the node's children.
*/
- expandNode: function(node) {
+ expandNode: function (node) {
let container = this.getContainer(node);
this._expandContainer(container);
},
/**
* Expand the entire tree beneath a container.
*
* @param {MarkupContainer} container
* The container to expand.
*/
- _expandAll: function(container) {
+ _expandAll: function (container) {
return this._expandContainer(container).then(() => {
let child = container.children.firstChild;
let promises = [];
while (child) {
promises.push(this._expandAll(child.container));
child = child.nextSibling;
}
return promise.all(promises);
@@ -1070,40 +1070,40 @@ MarkupView.prototype = {
},
/**
* Expand the entire tree beneath a node.
*
* @param {DOMNode} node
* The node to expand, or null to start from the top.
*/
- expandAll: function(node) {
+ expandAll: function (node) {
node = node || this._rootNode;
return this._expandAll(this.getContainer(node));
},
/**
* Collapse the node's children.
*/
- collapseNode: function(node) {
+ collapseNode: function (node) {
let container = this.getContainer(node);
container.setExpanded(false);
},
/**
* Returns either the innerHTML or the outerHTML for a remote node.
*
* @param {NodeFront} node
* The NodeFront to get the outerHTML / innerHTML for.
* @param {Boolean} isOuter
* If true, makes the function return the outerHTML,
* otherwise the innerHTML.
* @return {Promise} that will be resolved with the outerHTML / innerHTML.
*/
- _getNodeHTML: function(node, isOuter) {
+ _getNodeHTML: function (node, isOuter) {
let walkerPromise = null;
if (isOuter) {
walkerPromise = this.walker.outerHTML(node);
} else {
walkerPromise = this.walker.innerHTML(node);
}
@@ -1117,38 +1117,38 @@ MarkupView.prototype = {
/**
* Retrieve the outerHTML for a remote node.
*
* @param {NodeFront} node
* The NodeFront to get the outerHTML for.
* @return {Promise} that will be resolved with the outerHTML.
*/
- getNodeOuterHTML: function(node) {
+ getNodeOuterHTML: function (node) {
return this._getNodeHTML(node, true);
},
/**
* Retrieve the innerHTML for a remote node.
*
* @param {NodeFront} node
* The NodeFront to get the innerHTML for.
* @return {Promise} that will be resolved with the innerHTML.
*/
- getNodeInnerHTML: function(node) {
+ getNodeInnerHTML: function (node) {
return this._getNodeHTML(node);
},
/**
* Listen to mutations, expect a given node to be removed and try and select
* the node that sits at the same place instead.
* This is useful when changing the outerHTML or the tag name so that the
* newly inserted node gets selected instead of the one that just got removed.
*/
- reselectOnRemoved: function(removedNode, reason) {
+ reselectOnRemoved: function (removedNode, reason) {
// Only allow one removed node reselection at a time, so that when there are
// more than 1 request in parallel, the last one wins.
this.cancelReselectOnRemoved();
// Get the removedNode index in its parent node to reselect the right node.
let isHTMLTag = removedNode.tagName.toLowerCase() === "html";
let oldContainer = this.getContainer(removedNode);
let parentContainer = this.getContainer(removedNode.parentNode());
@@ -1192,17 +1192,17 @@ MarkupView.prototype = {
this._inspector.on("markupmutation", onMutations);
},
/**
* Make sure to stop listening for node removal markupmutations and not
* reselect the corresponding node when that happens.
* Useful when the outerHTML/tagname edition failed.
*/
- cancelReselectOnRemoved: function() {
+ cancelReselectOnRemoved: function () {
if (this._removedNodeObserver) {
this._inspector.off("markupmutation", this._removedNodeObserver);
this._removedNodeObserver = null;
this.emit("canceledreselectonremoved");
}
},
/**
@@ -1212,17 +1212,17 @@ MarkupView.prototype = {
* @param {NodeFront} node
* Node which outerHTML will be replaced.
* @param {String} newValue
* The new outerHTML to set on the node.
* @param {String} oldValue
* The old outerHTML that will be used if the user undoes the update.
* @return {Promise} that will resolve when the outer HTML has been updated.
*/
- updateNodeOuterHTML: function(node, newValue) {
+ updateNodeOuterHTML: function (node, newValue) {
let container = this.getContainer(node);
if (!container) {
return promise.reject();
}
// Changing the outerHTML removes the node which outerHTML was changed.
// Listen to this removal to reselect the right node afterwards.
this.reselectOnRemoved(node, "outerhtml");
@@ -1237,17 +1237,17 @@ MarkupView.prototype = {
* @param {Node} node
* node which innerHTML will be replaced.
* @param {String} newValue
* The new innerHTML to set on the node.
* @param {String} oldValue
* The old innerHTML that will be used if the user undoes the update.
* @return {Promise} that will resolve when the inner HTML has been updated.
*/
- updateNodeInnerHTML: function(node, newValue, oldValue) {
+ updateNodeInnerHTML: function (node, newValue, oldValue) {
let container = this.getContainer(node);
if (!container) {
return promise.reject();
}
let def = promise.defer();
container.undo.do(() => {
@@ -1267,17 +1267,17 @@ MarkupView.prototype = {
* @param {String} position
* The position as specified for Element.insertAdjacentHTML
* (i.e. "beforeBegin", "afterBegin", "beforeEnd", "afterEnd").
* @param {String} newValue
* The adjacent HTML.
* @return {Promise} that will resolve when the adjacent HTML has
* been inserted.
*/
- insertAdjacentHTMLToNode: function(node, position, value) {
+ insertAdjacentHTMLToNode: function (node, position, value) {
let container = this.getContainer(node);
if (!container) {
return promise.reject();
}
let def = promise.defer();
let injectedNodes = [];
@@ -1294,17 +1294,17 @@ MarkupView.prototype = {
},
/**
* Open an editor in the UI to allow editing of a node's outerHTML.
*
* @param {NodeFront} node
* The NodeFront to edit.
*/
- beginEditingOuterHTML: function(node) {
+ beginEditingOuterHTML: function (node) {
this.getNodeOuterHTML(node).then(oldValue => {
let container = this.getContainer(node);
if (!container) {
return;
}
this.htmlEditor.show(container.tagLine, oldValue);
this.htmlEditor.once("popuphidden", (e, commit, value) => {
// Need to focus the <html> element instead of the frame / window
@@ -1323,17 +1323,17 @@ MarkupView.prototype = {
*
* @param {NodeFront} node
* The NodeFront to mark as expanded.
* @param {Boolean} expanded
* Whether the expand or collapse.
* @param {Boolean} expandDescendants
* Whether to expand all descendants too
*/
- setNodeExpanded: function(node, expanded, expandDescendants) {
+ setNodeExpanded: function (node, expanded, expandDescendants) {
if (expanded) {
if (expandDescendants) {
this.expandAll(node);
} else {
this.expandNode(node);
}
} else {
this.collapseNode(node);
@@ -1346,17 +1346,17 @@ MarkupView.prototype = {
*
* @param {NodeFront} aNode
* The NodeFront to mark as selected.
* @param {String} reason
* The reason for marking the node as selected.
* @return {Boolean} False if the node is already marked as selected, true
* otherwise.
*/
- markNodeAsSelected: function(node, reason) {
+ markNodeAsSelected: function (node, reason) {
let container = this.getContainer(node);
if (this._selectedContainer === container) {
return false;
}
// Un-select the previous container.
if (this._selectedContainer) {
this._selectedContainer.selected = false;
@@ -1375,17 +1375,17 @@ MarkupView.prototype = {
return true;
},
/**
* Make sure that every ancestor of the selection are updated
* and included in the list of visible children.
*/
- _ensureVisible: function(node) {
+ _ensureVisible: function (node) {
while (node) {
let container = this.getContainer(node);
let parent = node.parentNode();
if (!container.elt.parentNode) {
let parentContainer = this.getContainer(parent);
if (parentContainer) {
parentContainer.childrenDirty = true;
this._updateChildren(parentContainer, {expand: true});
@@ -1395,31 +1395,31 @@ MarkupView.prototype = {
node = parent;
}
return this._waitForChildren();
},
/**
* Unmark selected node (no node selected).
*/
- unmarkSelectedNode: function() {
+ unmarkSelectedNode: function () {
if (this._selectedContainer) {
this._selectedContainer.selected = false;
this._selectedContainer = null;
}
},
/**
* Check if the current selection is a descendent of the container.
* if so, make sure it's among the visible set for the container,
* and set the dirty flag if needed.
*
* @return The node that should be made visible, if any.
*/
- _checkSelectionVisible: function(container) {
+ _checkSelectionVisible: function (container) {
let centered = null;
let node = this._inspector.selection.nodeFront;
while (node) {
if (node.parentNode() === container.node) {
centered = node;
break;
}
node = node.parentNode();
@@ -1444,17 +1444,17 @@ MarkupView.prototype = {
*
* @param {MarkupContainer} container
* The markup container whose children need updating
* @param {Object} options
* Options are {expand:boolean,flash:boolean}
* @return {Promise} that will be resolved when the children are ready
* (which may be immediately).
*/
- _updateChildren: function(container, options) {
+ _updateChildren: function (container, options) {
let expand = options && options.expand;
let flash = options && options.flash;
container.hasChildren = container.node.hasChildren;
if (!this._queuedChildUpdates) {
this._queuedChildUpdates = new Map();
}
@@ -1567,43 +1567,43 @@ MarkupView.prototype = {
container.children.appendChild(fragment);
return container;
}).then(null, console.error);
this._queuedChildUpdates.set(container, updatePromise);
return updatePromise;
},
- _waitForChildren: function() {
+ _waitForChildren: function () {
if (!this._queuedChildUpdates) {
return promise.resolve(undefined);
}
return promise.all([...this._queuedChildUpdates.values()]);
},
/**
* Return a list of the children to display for this container.
*/
- _getVisibleChildren: function(container, centered) {
+ _getVisibleChildren: function (container, centered) {
let maxChildren = container.maxChildren || this.maxChildren;
if (maxChildren == -1) {
maxChildren = undefined;
}
return this.walker.children(container.node, {
maxNodes: maxChildren,
center: centered
});
},
/**
* Tear down the markup panel.
*/
- destroy: function() {
+ destroy: function () {
if (this._destroyer) {
return this._destroyer;
}
this._destroyer = promise.resolve();
this._clearBriefBoxModelTimer();
@@ -1658,27 +1658,27 @@ MarkupView.prototype = {
/**
* Find the closest element with class tag-line. These are used to indicate
* drag and drop targets.
*
* @param {DOMNode} el
* @return {DOMNode}
*/
- findClosestDragDropTarget: function(el) {
+ findClosestDragDropTarget: function (el) {
return el.classList.contains("tag-line")
? el
: el.querySelector(".tag-line") || el.closest(".tag-line");
},
/**
* Takes an element as it's only argument and marks the element
* as the drop target
*/
- indicateDropTarget: function(el) {
+ indicateDropTarget: function (el) {
if (this._lastDropTarget) {
this._lastDropTarget.classList.remove("drop-target");
}
if (!el) {
return;
}
@@ -1687,17 +1687,17 @@ MarkupView.prototype = {
target.classList.add("drop-target");
this._lastDropTarget = target;
}
},
/**
* Takes an element to mark it as indicator of dragging target's initial place
*/
- indicateDragTarget: function(el) {
+ indicateDragTarget: function (el) {
if (this._lastDragTarget) {
this._lastDragTarget.classList.remove("drag-target");
}
if (!el) {
return;
}
@@ -1766,17 +1766,17 @@ MarkupContainer.prototype = {
*
* @param {MarkupView} markupView
* The markup view that owns this container.
* @param {NodeFront} node
* The node to display.
* @param {String} templateID
* Which template to render for this container
*/
- initialize: function(markupView, node, templateID) {
+ initialize: function (markupView, node, templateID) {
this.markup = markupView;
this.node = node;
this.undo = this.markup.undo;
this.win = this.markup._frame.contentWindow;
// The template will fill the following properties
this.elt = null;
this.expander = null;
@@ -1799,21 +1799,21 @@ MarkupContainer.prototype = {
if (this.expander) {
this.expander.addEventListener("click", this._onToggle, false);
}
// Marking the node as shown or hidden
this.isDisplayed = this.node.isDisplayed;
},
- toString: function() {
+ toString: function () {
return "[MarkupContainer for " + this.node + "]";
},
- isPreviewable: function() {
+ isPreviewable: function () {
if (this.node.tagName && !this.node.isPseudoElement) {
let tagName = this.node.tagName.toLowerCase();
let srcAttr = this.editor.getAttributeElement("src");
let isImage = tagName === "img" && srcAttr;
let isCanvas = tagName === "canvas";
return isImage || isCanvas;
}
@@ -1855,48 +1855,48 @@ MarkupContainer.prototype = {
/**
* True if this is the root <html> element and can't be collapsed.
*/
get mustExpand() {
return this.node._parent === this.markup.walker.rootNode;
},
- updateExpander: function() {
+ updateExpander: function () {
if (!this.expander) {
return;
}
if (this.canExpand && !this.mustExpand) {
this.expander.style.visibility = "visible";
} else {
this.expander.style.visibility = "hidden";
}
},
/**
* If the node has children, return the list of containers for all these
* children.
*/
- getChildContainers: function() {
+ getChildContainers: function () {
if (!this.hasChildren) {
return null;
}
return [...this.children.children].map(node => node.container);
},
/**
* True if the node has been visually expanded in the tree.
*/
get expanded() {
return !this.elt.classList.contains("collapsed");
},
- setExpanded: function(value) {
+ setExpanded: function (value) {
if (!this.expander) {
return;
}
if (!this.canExpand) {
value = false;
}
if (this.mustExpand) {
@@ -1932,17 +1932,17 @@ MarkupContainer.prototype = {
this.elt.removeChild(this.closeTagLine);
this.closeTagLine = undefined;
}
this.elt.classList.add("collapsed");
this.expander.removeAttribute("open");
}
},
- parentContainer: function() {
+ parentContainer: function () {
return this.elt.parentNode ? this.elt.parentNode.container : null;
},
_isDragging: false,
_dragStartY: 0,
set isDragging(isDragging) {
this._isDragging = isDragging;
@@ -1959,29 +1959,29 @@ MarkupContainer.prototype = {
get isDragging() {
return this._isDragging;
},
/**
* Check if element is draggable.
*/
- isDraggable: function() {
+ isDraggable: function () {
let tagName = this.node.tagName && this.node.tagName.toLowerCase();
return !this.node.isPseudoElement &&
!this.node.isAnonymous &&
!this.node.isDocumentElement &&
tagName !== "body" &&
tagName !== "head" &&
this.win.getSelection().isCollapsed &&
this.node.parentNode().tagName !== null;
},
- _onMouseDown: function(event) {
+ _onMouseDown: function (event) {
let {target, button, metaKey, ctrlKey} = event;
let isLeftClick = button === 0;
let isMiddleClick = button === 1;
let isMetaClick = isLeftClick && (metaKey || ctrlKey);
// The "show more nodes" button already has its onclick, so early return.
if (target.nodeName === "button") {
return;
@@ -2035,17 +2035,17 @@ MarkupContainer.prototype = {
dropTargetNodes.nextSibling);
this.markup.emit("drop-completed");
}
}),
/**
* On mouse move, move the dragged element and indicate the drop target.
*/
- _onMouseMove: function(event) {
+ _onMouseMove: function (event) {
// If this is the first move after mousedown, only start dragging after the
// mouse has travelled a few pixels and then indicate the start position.
let initialDiff = Math.abs(event.pageY - this._dragStartY);
if (this._isPreDragging && initialDiff >= DRAG_DROP_MIN_INITIAL_DISTANCE) {
this._isPreDragging = false;
this.isDragging = true;
// If this is the last child, use the closing <div.tag-line> of parent as
@@ -2070,31 +2070,31 @@ MarkupContainer.prototype = {
let diff = y - this._dragStartY + this.win.scrollY;
this.elt.style.top = diff + "px";
let el = this.markup.doc.elementFromPoint(x, y);
this.markup.indicateDropTarget(el);
}
},
- cancelDragging: function() {
+ cancelDragging: function () {
if (!this.isDragging) {
return;
}
this._isPreDragging = false;
this.isDragging = false;
this.elt.style.removeProperty("top");
},
/**
* Temporarily flash the container to attract attention.
* Used for markup mutations.
*/
- flashMutation: function() {
+ flashMutation: function () {
if (!this.selected) {
flashElementOn(this.tagState, this.editor.elt);
if (this._flashMutationTimer) {
clearTimeout(this._flashMutationTimer);
this._flashMutationTimer = null;
}
this._flashMutationTimer = setTimeout(() => {
flashElementOff(this.tagState, this.editor.elt);
@@ -2156,51 +2156,51 @@ MarkupContainer.prototype = {
this.tagState.classList.remove("theme-selected");
}
},
/**
* Update the container's editor to the current state of the
* viewed node.
*/
- update: function() {
+ update: function () {
if (this.node.pseudoClassLocks.length) {
this.elt.classList.add("pseudoclass-locked");
} else {
this.elt.classList.remove("pseudoclass-locked");
}
if (this.editor.update) {
this.editor.update();
}
},
/**
* Try to put keyboard focus on the current editor.
*/
- focus: function() {
+ focus: function () {
let focusable = this.editor.elt.querySelector("[tabindex]");
if (focusable) {
focusable.focus();
}
},
- _onToggle: function(event) {
+ _onToggle: function (event) {
this.markup.navigate(this);
if (this.hasChildren) {
this.markup.setNodeExpanded(this.node, !this.expanded, event.altKey);
}
event.stopPropagation();
},
/**
* Get rid of event listeners and references, when the container is no longer
* needed
*/
- destroy: function() {
+ destroy: function () {
// Remove event listeners
this.elt.removeEventListener("mousedown", this._onMouseDown, false);
this.elt.removeEventListener("dblclick", this._onToggle, false);
if (this.win) {
this.win.removeEventListener("mouseup", this._onMouseUp, true);
this.win.removeEventListener("mousemove", this._onMouseMove, true);
}
@@ -2295,17 +2295,17 @@ function MarkupElementContainer(markupVi
} else {
throw new Error("Invalid node for MarkupElementContainer");
}
this.tagLine.appendChild(this.editor.elt);
}
MarkupElementContainer.prototype = Heritage.extend(MarkupContainer.prototype, {
- _buildEventTooltipContent: function(target, tooltip) {
+ _buildEventTooltipContent: function (target, tooltip) {
if (target.hasAttribute("data-event")) {
tooltip.hide(target);
this.node.getEventListenerInfo().then(listenerInfo => {
tooltip.setEventContent({
eventListenerInfos: listenerInfo,
toolbox: this.markup._inspector.toolbox
});
@@ -2329,17 +2329,17 @@ MarkupElementContainer.prototype = Herit
* { data, size: { naturalWidth, naturalHeight, resizeRatio } } where
* - data is the data-uri for the image preview.
* - size contains information about the original image size and if
* the preview has been resized.
*
* If this element is not previewable or the preview cannot be generated for
* some reason, the Promise is rejected.
*/
- _getPreview: function() {
+ _getPreview: function () {
if (!this.isPreviewable()) {
return promise.reject("_getPreview called on a non-previewable element.");
}
if (this.tooltipDataPromise) {
// A preview request is already pending. Re-use that request.
return this.tooltipDataPromise;
}
@@ -2367,17 +2367,17 @@ MarkupElementContainer.prototype = Herit
* the mouse hovers over a target in the markup-view.
* Checks if the target is indeed something we want to have an image tooltip
* preview over and, if so, inserts content into the tooltip.
*
* @return {Promise} that resolves when the content has been inserted or
* rejects if no preview is required. This promise is then used by
* Tooltip.js to decide if/when to show the tooltip
*/
- isImagePreviewTarget: function(target, tooltip) {
+ isImagePreviewTarget: function (target, tooltip) {
// Is this Element previewable.
if (!this.isPreviewable()) {
return promise.reject(false);
}
// If the Element has an src attribute, the tooltip is shown when hovering
// over the src url. If not, the tooltip is shown when hovering over the tag
// name.
@@ -2391,55 +2391,55 @@ MarkupElementContainer.prototype = Herit
// The preview is ready.
tooltip.setImageContent(data, size);
}, () => {
// Indicate the failure but show the tooltip anyway.
tooltip.setBrokenImageContent();
});
},
- copyImageDataUri: function() {
+ copyImageDataUri: function () {
// We need to send again a request to gettooltipData even if one was sent
// for the tooltip, because we want the full-size image
this.node.getImageData().then(data => {
data.data.string().then(str => {
clipboardHelper.copyString(str);
});
});
},
- setSingleTextChild: function(singleTextChild) {
+ setSingleTextChild: function (singleTextChild) {
this.singleTextChild = singleTextChild;
this.editor.updateTextEditor();
},
- clearSingleTextChild: function() {
+ clearSingleTextChild: function () {
this.singleTextChild = undefined;
this.editor.updateTextEditor();
},
/**
* Trigger new attribute field for input.
*/
- addAttribute: function() {
+ addAttribute: function () {
this.editor.newAttr.editMode();
},
/**
* Trigger attribute field for editing.
*/
- editAttribute: function(attrName) {
+ editAttribute: function (attrName) {
this.editor.attrElements.get(attrName).editMode();
},
/**
* Remove attribute from container.
* This is an undoable action.
*/
- removeAttribute: function(attrName) {
+ removeAttribute: function (attrName) {
let doMods = this.editor._startModifyingAttributes();
let undoMods = this.editor._startModifyingAttributes();
this.editor._saveAttribute(attrName, undoMods);
doMods.removeAttribute(attrName);
this.undo.do(() => {
doMods.apply();
}, () => {
undoMods.apply();
@@ -2457,32 +2457,32 @@ function RootContainer(markupView, node)
this.children = this.elt;
this.node = node;
this.toString = () => "[root container]";
}
RootContainer.prototype = {
hasChildren: true,
expanded: true,
- update: function() {},
- destroy: function() {},
+ update: function () {},
+ destroy: function () {},
/**
* If the node has children, return the list of containers for all these
* children.
*/
- getChildContainers: function() {
+ getChildContainers: function () {
return [...this.children.children].map(node => node.container);
},
/**
* Set the expanded state of the container node.
* @param {Boolean} value
*/
- setExpanded: function() {}
+ setExpanded: function () {}
};
/**
* Creates an editor for non-editable nodes.
*/
function GenericEditor(container, node) {
this.container = container;
this.markup = this.container.markup;
@@ -2497,24 +2497,24 @@ function GenericEditor(container, node)
this.elt.classList.add("comment");
this.tag.textContent = node.doctypeString;
} else {
this.tag.textContent = node.nodeName;
}
}
GenericEditor.prototype = {
- destroy: function() {
+ destroy: function () {
this.elt.remove();
},
/**
* Stub method for consistency with ElementEditor.
*/
- getInfoAtNode: function() {
+ getInfoAtNode: function () {
return null;
}
};
/**
* Creates a simple text editor node, used for TEXT and COMMENT
* nodes.
*
@@ -2574,17 +2574,17 @@ TextEditor.prototype = {
set selected(value) {
if (value === this._selected) {
return;
}
this._selected = value;
this.update();
},
- update: function() {
+ update: function () {
if (!this.selected || !this.node.incompleteValue) {
let text = this.node.shortValue;
if (this.node.incompleteValue) {
text += ELLIPSIS;
}
this.value.textContent = text;
} else {
let longstr = null;
@@ -2596,22 +2596,22 @@ TextEditor.prototype = {
if (this.selected) {
this.value.textContent = str;
this.markup.emit("text-expand");
}
}).then(null, console.error);
}
},
- destroy: function() {},
+ destroy: function () {},
/**
* Stub method for consistency with ElementEditor.
*/
- getInfoAtNode: function() {
+ getInfoAtNode: function () {
return null;
}
};
/**
* Creates an editor for an Element node.
*
* @param {MarkupContainer} container
@@ -2664,17 +2664,17 @@ function ElementEditor(container, node)
return;
}
let doMods = this._startModifyingAttributes();
let undoMods = this._startModifyingAttributes();
this._applyAttributes(val, null, doMods, undoMods);
this.container.undo.do(() => {
doMods.apply();
- }, function() {
+ }, function () {
undoMods.apply();
});
}
});
let tagName = this.getTagName(this.node);
this.tag.textContent = tagName;
this.closeTag.textContent = tagName;
@@ -2685,17 +2685,17 @@ function ElementEditor(container, node)
ElementEditor.prototype = {
set selected(value) {
if (this.textEditor) {
this.textEditor.selected = value;
}
},
- flashAttribute: function(attrName) {
+ flashAttribute: function (attrName) {
if (this.animationTimers[attrName]) {
clearTimeout(this.animationTimers[attrName]);
}
flashElementOn(this.getAttributeElement(attrName));
this.animationTimers[attrName] = setTimeout(() => {
flashElementOff(this.getAttributeElement(attrName));
@@ -2704,17 +2704,17 @@ ElementEditor.prototype = {
/**
* Returns the name of a node.
*
* @param {DOMNode} node
* The node to get the name of.
* @return {String} A tag name with correct case
*/
- getTagName: function(node) {
+ getTagName: function (node) {
// Check the node is a SVG element
if (node.namespaceURI === "http://www.w3.org/2000/svg") {
// nodeName is already in the correct case
return node.nodeName;
}
return node.nodeName.toLowerCase();
},
@@ -2722,17 +2722,17 @@ ElementEditor.prototype = {
/**
* Returns information about node in the editor.
*
* @param {DOMNode} node
* The node to get information from.
* @return {Object} An object literal with the following information:
* {type: "attribute", name: "rel", value: "index", el: node}
*/
- getInfoAtNode: function(node) {
+ getInfoAtNode: function (node) {
if (!node) {
return null;
}
let type = null;
let name = null;
let value = null;
@@ -2745,17 +2745,17 @@ ElementEditor.prototype = {
}
return {type, name, value, el: node};
},
/**
* Update the state of the editor from the node.
*/
- update: function() {
+ update: function () {
let nodeAttributes = this.node.attributes || [];
// Keep the data model in sync with attributes on the node.
let currentAttributes = new Set(nodeAttributes.map(a => a.name));
for (let name of this.attrElements.keys()) {
if (!currentAttributes.has(name)) {
this.removeAttribute(name);
}
@@ -2794,17 +2794,17 @@ ElementEditor.prototype = {
"inline-block" : "none";
this.updateTextEditor();
},
/**
* Update the inline text editor in case of a single text child node.
*/
- updateTextEditor: function() {
+ updateTextEditor: function () {
let node = this.node.singleTextChild;
if (this.textEditor && this.textEditor.node != node) {
this.elt.removeChild(this.textEditor.elt);
this.textEditor = null;
}
if (node && !this.textEditor) {
@@ -2816,47 +2816,47 @@ ElementEditor.prototype = {
this.elt.firstChild.nextSibling.nextSibling);
}
if (this.textEditor) {
this.textEditor.update();
}
},
- _startModifyingAttributes: function() {
+ _startModifyingAttributes: function () {
return this.node.startModifyingAttributes();
},
/**
* Get the element used for one of the attributes of this element.
*
* @param {String} attrName
* The name of the attribute to get the element for
* @return {DOMNode}
*/
- getAttributeElement: function(attrName) {
+ getAttributeElement: function (attrName) {
return this.attrList.querySelector(
".attreditor[data-attr=" + CSS.escape(attrName) + "] .attr-value");
},
/**
* Remove an attribute from the attrElements object and the DOM.
*
* @param {String} attrName
* The name of the attribute to remove
*/
- removeAttribute: function(attrName) {
+ removeAttribute: function (attrName) {
let attr = this.attrElements.get(attrName);
if (attr) {
this.attrElements.delete(attrName);
attr.remove();
}
},
- _createAttribute: function(attribute, before = null) {
+ _createAttribute: function (attribute, before = null) {
// Create the template editor, which will save some variables here.
let data = {
attrName: attribute.name,
};
this.template("attribute", data);
let {attr, inner, name, val} = data;
// Double quotes need to be handled specially to prevent DOMParser failing.
@@ -2983,46 +2983,46 @@ ElementEditor.prototype = {
*
* @param {String} value
* The user-entered value.
* @param {DOMNode} attrNode
* The attribute editor that created this
* set of attributes, used to place new attributes where the
* user put them.
*/
- _applyAttributes: function(value, attrNode, doMods, undoMods) {
+ _applyAttributes: function (value, attrNode, doMods, undoMods) {
let attrs = parseAttributeValues(value, this.doc);
for (let attr of attrs) {
// Create an attribute editor next to the current attribute if needed.
this._createAttribute(attr, attrNode ? attrNode.nextSibling : null);
this._saveAttribute(attr.name, undoMods);
doMods.setAttribute(attr.name, attr.value);
}
},
/**
* Saves the current state of the given attribute into an attribute
* modification list.
*/
- _saveAttribute: function(name, undoMods) {
+ _saveAttribute: function (name, undoMods) {
let node = this.node;
if (node.hasAttribute(name)) {
let oldValue = node.getAttribute(name);
undoMods.setAttribute(name, oldValue);
} else {
undoMods.removeAttribute(name);
}
},
/**
* Listen to mutations, and when the attribute list is regenerated
* try to focus on the attribute after the one that's being edited now.
* If the attribute order changes, go to the beginning of the attribute list.
*/
- refocusOnEdit: function(attrName, attrNode, direction) {
+ refocusOnEdit: function (attrName, attrNode, direction) {
// Only allow one refocus on attribute change at a time, so when there's
// more than 1 request in parallel, the last one wins.
if (this._editedAttributeObserver) {
this.markup._inspector.off("markupmutation",
this._editedAttributeObserver);
this._editedAttributeObserver = null;
}
@@ -3108,33 +3108,33 @@ ElementEditor.prototype = {
// Start listening for mutations until we find an attributes change
// that modifies this attribute.
this.markup._inspector.once("markupmutation", onMutations);
},
/**
* Called when the tag name editor has is done editing.
*/
- onTagEdit: function(newTagName, isCommit) {
+ onTagEdit: function (newTagName, isCommit) {
if (!isCommit ||
newTagName.toLowerCase() === this.node.tagName.toLowerCase() ||
!("editTagName" in this.markup.walker)) {
return;
}
// Changing the tagName removes the node. Make sure the replacing node gets
// selected afterwards.
this.markup.reselectOnRemoved(this.node, "edittagname");
this.markup.walker.editTagName(this.node, newTagName).then(null, () => {
// Failed to edit the tag name, cancel the reselection.
this.markup.cancelReselectOnRemoved();
});
},
- destroy: function() {
+ destroy: function () {
for (let key in this.animationTimers) {
clearTimeout(this.animationTimers[key]);
}
this.animationTimers = null;
}
};
function truncateString(str, maxLength) {
@@ -3257,14 +3257,14 @@ function map(value, oldMin, oldMax, newM
}
return newMin + (newMax - newMin) * ((value - oldMin) / ratio);
}
loader.lazyGetter(MarkupView.prototype, "strings", () => Services.strings.createBundle(
"chrome://devtools/locale/inspector.properties"
));
-XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function() {
+XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function () {
return Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper);
});
exports.MarkupView = MarkupView;
--- a/devtools/client/inspector/markup/test/actor_events_form.js
+++ b/devtools/client/inspector/markup/test/actor_events_form.js
@@ -11,45 +11,45 @@ const Events = require("sdk/event/core")
const {ActorClass, Actor, FrontClass, Front, method} =
require("devtools/server/protocol");
const {NodeActor} = require("devtools/server/actors/inspector");
var EventsFormActor = ActorClass({
typeName: "eventsFormActor",
- initialize: function() {
+ initialize: function () {
Actor.prototype.initialize.apply(this, arguments);
},
- attach: method(function() {
+ attach: method(function () {
Events.on(NodeActor, "form", this.onNodeActorForm);
}, {
request: {},
response: {}
}),
- detach: method(function() {
+ detach: method(function () {
Events.off(NodeActor, "form", this.onNodeActorForm);
}, {
request: {},
response: {}
}),
- onNodeActorForm: function(event) {
+ onNodeActorForm: function (event) {
let nodeActor = event.target;
if (nodeActor.rawNode.id == "container") {
let form = event.data;
form.setFormProperty("test-property", "test-value");
}
}
});
var EventsFormFront = FrontClass(EventsFormActor, {
- initialize: function(client, form) {
+ initialize: function (client, form) {
Front.prototype.initialize.apply(this, arguments);
this.actorID = form[EventsFormActor.prototype.typeName];
this.manage(this);
}
});
exports.EventsFormFront = EventsFormFront;
--- a/devtools/client/inspector/markup/test/browser_markup_load_01.js
+++ b/devtools/client/inspector/markup/test/browser_markup_load_01.js
@@ -8,17 +8,17 @@
// menu during a page reload doesn't cause the markup view to become empty.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1036324
const server = createTestHTTPServer();
// Register a slow image handler so we can simulate a long time between
// a reload and the load event firing.
server.registerContentType("gif", "image/gif");
-server.registerPathHandler("/slow.gif", function(metadata, response) {
+server.registerPathHandler("/slow.gif", function (metadata, response) {
info("Image has been requested");
response.processAsync();
setTimeout(() => {
info("Image is responding");
response.finish();
}, 500);
});
--- a/devtools/client/inspector/markup/test/browser_markup_tag_edit_07.js
+++ b/devtools/client/inspector/markup/test/browser_markup_tag_edit_07.js
@@ -84,51 +84,51 @@ var TEST_DATA = [{
}
}, {
desc: "Try to add long attribute with collapseAttributes == false" +
"to make sure it isn't collapsed in attribute editor.",
text: `data-long="${LONG_ATTRIBUTE}"`,
expectedAttributes: {
"data-long": LONG_ATTRIBUTE
},
- setUp: function(inspector) {
+ setUp: function (inspector) {
Services.prefs.setBoolPref("devtools.markup.collapseAttributes", false);
},
validate: (container, inspector) => {
let editor = container.editor;
let visibleAttrText = editor.attrElements
.get("data-long")
.querySelector(".attr-value")
.textContent;
is(visibleAttrText, LONG_ATTRIBUTE);
},
- tearDown: function(inspector) {
+ tearDown: function (inspector) {
Services.prefs.clearUserPref("devtools.markup.collapseAttributes");
}
}, {
desc: "Try to collapse attributes with collapseAttributeLength == 5",
text: `data-long="${LONG_ATTRIBUTE}"`,
expectedAttributes: {
"data-long": LONG_ATTRIBUTE
},
- setUp: function(inspector) {
+ setUp: function (inspector) {
Services.prefs.setIntPref("devtools.markup.collapseAttributeLength", 2);
},
validate: (container, inspector) => {
let firstChar = LONG_ATTRIBUTE[0];
let lastChar = LONG_ATTRIBUTE[LONG_ATTRIBUTE.length - 1];
let collapsed = firstChar + "\u2026" + lastChar;
let editor = container.editor;
let visibleAttrText = editor.attrElements
.get("data-long")
.querySelector(".attr-value")
.textContent;
is(visibleAttrText, collapsed);
},
- tearDown: function(inspector) {
+ tearDown: function (inspector) {
Services.prefs.clearUserPref("devtools.markup.collapseAttributeLength");
}
}];
add_task(function* () {
let {inspector, testActor} = yield openInspectorForURL(TEST_URL);
yield runAddAttributesTests(TEST_DATA, "div", inspector, testActor);
});
--- a/devtools/client/inspector/markup/test/browser_markup_tag_edit_11.js
+++ b/devtools/client/inspector/markup/test/browser_markup_tag_edit_11.js
@@ -11,17 +11,17 @@ const TEST_URL = "data:text/html;charset
add_task(function* () {
let isEditTagNameCalled = false;
let {inspector} = yield openInspectorForURL(TEST_URL);
// Overriding the editTagName walkerActor method here to check that it isn't
// called when blurring the tagname field.
- inspector.walker.editTagName = function() {
+ inspector.walker.editTagName = function () {
isEditTagNameCalled = true;
};
yield selectNode("div", inspector);
let container = yield getContainerForSelector("div", inspector);
let tagEditor = container.editor.tag;
info("Blurring the tagname field");
--- a/devtools/client/inspector/rules/models/element-style.js
+++ b/devtools/client/inspector/rules/models/element-style.js
@@ -12,17 +12,17 @@ const {Rule} = require("devtools/client/
const {promiseWarn} = require("devtools/client/inspector/shared/utils");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
loader.lazyGetter(this, "PSEUDO_ELEMENTS", () => {
return domUtils.getCSSPseudoElementNames();
});
-XPCOMUtils.defineLazyGetter(this, "domUtils", function() {
+XPCOMUtils.defineLazyGetter(this, "domUtils", function () {
return Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils);
});
/**
* ElementStyle is responsible for the following:
* Keeps track of which properties are overridden.
* Maintains a list of Rule objects for a given element.
*
@@ -59,47 +59,47 @@ function ElementStyle(element, ruleView,
this.store.disabled = new WeakMap();
}
}
ElementStyle.prototype = {
// The element we're looking at.
element: null,
- destroy: function() {
+ destroy: function () {
if (this.destroyed) {
return;
}
this.destroyed = true;
for (let rule of this.rules) {
if (rule.editor) {
rule.editor.destroy();
}
}
},
/**
* Called by the Rule object when it has been changed through the
* setProperty* methods.
*/
- _changed: function() {
+ _changed: function () {
if (this.onChanged) {
this.onChanged();
}
},
/**
* Refresh the list of rules to be displayed for the active element.
* Upon completion, this.rules[] will hold a list of Rule objects.
*
* Returns a promise that will be resolved when the elementStyle is
* ready.
*/
- populate: function() {
+ populate: function () {
let populated = this.pageStyle.getApplied(this.element, {
inherited: true,
matchedSelectors: true,
filter: this.showUserAgentStyles ? "ua" : undefined,
}).then(entries => {
if (this.destroyed) {
return promise.resolve(undefined);
}
@@ -142,34 +142,34 @@ ElementStyle.prototype = {
});
this.populated = populated;
return this.populated;
},
/**
* Put pseudo elements in front of others.
*/
- _sortRulesForPseudoElement: function() {
+ _sortRulesForPseudoElement: function () {
this.rules = this.rules.sort((a, b) => {
return (a.pseudoElement || "z") > (b.pseudoElement || "z");
});
},
/**
* Add a rule if it's one we care about. Filters out duplicates and
* inherited styles with no inherited properties.
*
* @param {Object} options
* Options for creating the Rule, see the Rule constructor.
* @param {Array} existingRules
* Rules to reuse if possible. If a rule is reused, then it
* it will be deleted from this array.
* @return {Boolean} true if we added the rule.
*/
- _maybeAddRule: function(options, existingRules) {
+ _maybeAddRule: function (options, existingRules) {
// If we've already included this domRule (for example, when a
// common selector is inherited), ignore it.
if (options.rule &&
this.rules.some(rule => rule.domRule === options.rule)) {
return false;
}
if (options.system) {
@@ -201,32 +201,32 @@ ElementStyle.prototype = {
this.rules.push(rule);
return true;
},
/**
* Calls markOverridden with all supported pseudo elements
*/
- markOverriddenAll: function() {
+ markOverriddenAll: function () {
this.markOverridden();
for (let pseudo of PSEUDO_ELEMENTS) {
this.markOverridden(pseudo);
}
},
/**
* Mark the properties listed in this.rules for a given pseudo element
* with an overridden flag if an earlier property overrides it.
*
* @param {String} pseudo
* Which pseudo element to flag as overridden.
* Empty string or undefined will default to no pseudo element.
*/
- markOverridden: function(pseudo = "") {
+ markOverridden: function (pseudo = "") {
// Gather all the text properties applied by these rules, ordered
// from more- to less-specific. Text properties from keyframes rule are
// excluded from being marked as overridden since a number of criteria such
// as time, and animation overlay are required to be check in order to
// determine if the property is overridden.
let textProps = [];
for (let rule of this.rules) {
if (rule.pseudoElement === pseudo && !rule.keyframes) {
@@ -315,17 +315,17 @@ ElementStyle.prototype = {
* state of its computed properties. Clears the _overriddenDirty state
* on all computed properties.
*
* @param {TextProperty} prop
* The text property to update.
* @return {Boolean} true if the TextProperty's overridden state (or any of
* its computed properties overridden state) changed.
*/
- _updatePropertyOverridden: function(prop) {
+ _updatePropertyOverridden: function (prop) {
let overridden = true;
let dirty = false;
for (let computedProp of prop.computed) {
if (!computedProp.overridden) {
overridden = false;
}
dirty = computedProp._overriddenDirty || dirty;
delete computedProp._overriddenDirty;
@@ -354,17 +354,17 @@ UserProperties.prototype = {
* @param {String} name
* The name of the property to get.
* @param {String} value
* Default value.
* @return {String}
* The property value if it has previously been set by the user, null
* otherwise.
*/
- getProperty: function(style, name, value) {
+ getProperty: function (style, name, value) {
let key = this.getKey(style);
let entry = this.map.get(key, null);
if (entry && name in entry) {
return entry[name];
}
return value;
},
@@ -374,17 +374,17 @@ UserProperties.prototype = {
*
* @param {CSSStyleDeclaration} style
* The CSSStyleDeclaration against which the property is to be mapped.
* @param {String} bame
* The name of the property to set.
* @param {String} userValue
* The value of the property to set.
*/
- setProperty: function(style, bame, userValue) {
+ setProperty: function (style, bame, userValue) {
let key = this.getKey(style, bame);
let entry = this.map.get(key, null);
if (entry) {
entry[bame] = userValue;
} else {
let props = {};
props[bame] = userValue;
@@ -395,24 +395,24 @@ UserProperties.prototype = {
/**
* Check whether a named property for a given CSSStyleDeclaration is stored.
*
* @param {CSSStyleDeclaration} style
* The CSSStyleDeclaration against which the property would be mapped.
* @param {String} name
* The name of the property to check.
*/
- contains: function(style, name) {
+ contains: function (style, name) {
let key = this.getKey(style, name);
let entry = this.map.get(key, null);
return !!entry && name in entry;
},
- getKey: function(style, name) {
+ getKey: function (style, name) {
return style.actorID + ":" + name;
},
- clear: function() {
+ clear: function () {
this.map.clear();
}
};
exports.ElementStyle = ElementStyle;
--- a/devtools/client/inspector/rules/models/rule.js
+++ b/devtools/client/inspector/rules/models/rule.js
@@ -12,21 +12,21 @@ const {CssLogic} = require("devtools/sha
const {ELEMENT_STYLE} = require("devtools/server/actors/styles");
const {TextProperty} =
require("devtools/client/inspector/rules/models/text-property");
const {promiseWarn} = require("devtools/client/inspector/shared/utils");
const {parseDeclarations} = require("devtools/client/shared/css-parsing-utils");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyGetter(this, "osString", function() {
+XPCOMUtils.defineLazyGetter(this, "osString", function () {
return Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
});
-XPCOMUtils.defineLazyGetter(this, "domUtils", function() {
+XPCOMUtils.defineLazyGetter(this, "domUtils", function () {
return Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils);
});
/**
* Rule is responsible for the following:
* Manages a single style declaration or rule.
* Applies changes to the properties in a rule.
* Maintains a list of TextProperty objects.
@@ -136,17 +136,17 @@ Rule.prototype = {
/**
* Get display name for this rule based on the original source
* for this rule's style sheet.
*
* @return {Promise}
* Promise which resolves with location as an object containing
* both the full and short version of the source string.
*/
- getOriginalSourceStrings: function() {
+ getOriginalSourceStrings: function () {
return this.domRule.getOriginalLocation().then(({href,
line, mediaText}) => {
let mediaString = mediaText ? " @" + mediaText : "";
let linePart = line > 0 ? (":" + line) : "";
let sourceStrings = {
full: (href || CssLogic.l10n("rule.sourceInline")) + linePart +
mediaString,
@@ -159,17 +159,17 @@ Rule.prototype = {
/**
* Returns true if the rule matches the creation options
* specified.
*
* @param {Object} options
* Creation options. See the Rule constructor for documentation.
*/
- matches: function(options) {
+ matches: function (options) {
return this.style === options.rule;
},
/**
* Create a new TextProperty to include in the rule.
*
* @param {String} name
* The text property name (such as "background" or "border-top").
@@ -177,17 +177,17 @@ Rule.prototype = {
* The property's value (not including priority).
* @param {String} priority
* The property's priority (either "important" or an empty string).
* @param {Boolean} enabled
* True if the property should be enabled.
* @param {TextProperty} siblingProp
* Optional, property next to which the new property will be added.
*/
- createProperty: function(name, value, priority, enabled, siblingProp) {
+ createProperty: function (name, value, priority, enabled, siblingProp) {
let prop = new TextProperty(this, name, value, priority, enabled);
let ind;
if (siblingProp) {
ind = this.textProps.indexOf(siblingProp) + 1;
this.textProps.splice(ind, 0, prop);
} else {
ind = this.textProps.length;
@@ -200,17 +200,17 @@ Rule.prototype = {
return prop;
},
/**
* Helper function for applyProperties that is called when the actor
* does not support as-authored styles. Store disabled properties
* in the element style's store.
*/
- _applyPropertiesNoAuthored: function(modifications) {
+ _applyPropertiesNoAuthored: function (modifications) {
this.elementStyle.markOverriddenAll();
let disabledProps = [];
for (let prop of this.textProps) {
if (prop.invisible) {
continue;
}
@@ -264,17 +264,17 @@ Rule.prototype = {
});
},
/**
* A helper for applyProperties that applies properties in the "as
* authored" case; that is, when the StyleRuleActor supports
* setRuleText.
*/
- _applyPropertiesAuthored: function(modifications) {
+ _applyPropertiesAuthored: function (modifications) {
return modifications.apply().then(() => {
// The rewriting may have required some other property values to
// change, e.g., to insert some needed terminators. Update the
// relevant properties here.
for (let index in modifications.changedDeclarations) {
let newValue = modifications.changedDeclarations[index];
this.textProps[index].noticeNewValue(newValue);
}
@@ -295,17 +295,17 @@ Rule.prototype = {
* when the edit has completed.
*
* @param {Function} modifier a function that takes a RuleModificationList
* (or RuleRewriter) as an argument and that modifies it
* to apply the desired edit
* @return {Promise} a promise which will resolve when the edit
* is complete
*/
- applyProperties: function(modifier) {
+ applyProperties: function (modifier) {
// If there is already a pending modification, we have to wait
// until it settles before applying the next modification.
let resultPromise =
promise.resolve(this._applyingModifications).then(() => {
let modifications = this.style.startModifyingProperties();
modifier(modifications);
if (this.style.canSetRuleText) {
return this._applyPropertiesAuthored(modifications);
@@ -327,17 +327,17 @@ Rule.prototype = {
/**
* Renames a property.
*
* @param {TextProperty} property
* The property to rename.
* @param {String} name
* The new property name (such as "background" or "border-top").
*/
- setPropertyName: function(property, name) {
+ setPropertyName: function (property, name) {
if (name === property.name) {
return;
}
let oldName = property.name;
property.name = name;
let index = this.textProps.indexOf(property);
this.applyProperties((modifications) => {
@@ -350,17 +350,17 @@ Rule.prototype = {
*
* @param {TextProperty} property
* The property to manipulate.
* @param {String} value
* The property's value (not including priority).
* @param {String} priority
* The property's priority (either "important" or an empty string).
*/
- setPropertyValue: function(property, value, priority) {
+ setPropertyValue: function (property, value, priority) {
if (value === property.value && priority === property.priority) {
return;
}
property.value = value;
property.priority = priority;
let index = this.textProps.indexOf(property);
@@ -375,17 +375,17 @@ Rule.prototype = {
*
* @param {TextProperty} property
* The property which value will be previewed
* @param {String} value
* The value to be used for the preview
* @param {String} priority
* The property's priority (either "important" or an empty string).
*/
- previewPropertyValue: function(property, value, priority) {
+ previewPropertyValue: function (property, value, priority) {
let modifications = this.style.startModifyingProperties();
modifications.setProperty(this.textProps.indexOf(property),
property.name, value, priority);
modifications.apply().then(() => {
// Ensure dispatching a ruleview-changed event
// also for previews
this.elementStyle._changed();
});
@@ -393,17 +393,17 @@ Rule.prototype = {
/**
* Disables or enables given TextProperty.
*
* @param {TextProperty} property
* The property to enable/disable
* @param {Boolean} value
*/
- setPropertyEnabled: function(property, value) {
+ setPropertyEnabled: function (property, value) {
if (property.enabled === !!value) {
return;
}
property.enabled = !!value;
let index = this.textProps.indexOf(property);
this.applyProperties((modifications) => {
modifications.setPropertyEnabled(index, property.name, property.enabled);
});
@@ -411,31 +411,31 @@ Rule.prototype = {
/**
* Remove a given TextProperty from the rule and update the rule
* accordingly.
*
* @param {TextProperty} property
* The property to be removed
*/
- removeProperty: function(property) {
+ removeProperty: function (property) {
let index = this.textProps.indexOf(property);
this.textProps.splice(index, 1);
// Need to re-apply properties in case removing this TextProperty
// exposes another one.
this.applyProperties((modifications) => {
modifications.removeProperty(index, property.name);
});
},
/**
* Get the list of TextProperties from the style. Needs
* to parse the style's authoredText.
*/
- _getTextProperties: function() {
+ _getTextProperties: function () {
let textProps = [];
let store = this.elementStyle.store;
let props = parseDeclarations(this.style.authoredText, true);
for (let prop of props) {
let name = prop.name;
// If the authored text has an invalid property, it will show up
// as nameless. Skip these as we don't currently have a good
// way to display them.
@@ -456,17 +456,17 @@ Rule.prototype = {
}
return textProps;
},
/**
* Return the list of disabled properties from the store for this rule.
*/
- _getDisabledProperties: function() {
+ _getDisabledProperties: function () {
let store = this.elementStyle.store;
// Include properties from the disabled property store, if any.
let disabledProps = store.disabled.get(this.style);
if (!disabledProps) {
return [];
}
@@ -482,17 +482,17 @@ Rule.prototype = {
return textProps;
},
/**
* Reread the current state of the rules and rebuild text
* properties as needed.
*/
- refresh: function(options) {
+ refresh: function (options) {
this.matchedSelectors = options.matchedSelectors || [];
let newTextProps = this._getTextProperties();
// Update current properties for each property present on the style.
// This will mark any touched properties with _visited so we
// can detect properties that weren't touched (because they were
// removed from the style).
// Also keep track of properties that didn't exist in the current set
@@ -543,17 +543,17 @@ Rule.prototype = {
* If no existing properties match the property, nothing happens.
*
* @param {TextProperty} newProp
* The current version of the property, as parsed from the
* authoredText in Rule._getTextProperties().
* @return {Boolean} true if a property was updated, false if no properties
* were updated.
*/
- _updateTextProperty: function(newProp) {
+ _updateTextProperty: function (newProp) {
let match = { rank: 0, prop: null };
for (let prop of this.textProps) {
if (prop.name !== newProp.name) {
continue;
}
// Mark this property visited.
@@ -608,17 +608,17 @@ Rule.prototype = {
* begin editing the previous property value or focus the selector editor if
* this is the first element in the property list.
*
* @param {TextProperty} textProperty
* The text property that will be left to focus on a sibling.
* @param {Number} direction
* The move focus direction number.
*/
- editClosestTextProperty: function(textProperty, direction) {
+ editClosestTextProperty: function (textProperty, direction) {
let index = this.textProps.indexOf(textProperty);
if (direction === Ci.nsIFocusManager.MOVEFOCUS_FORWARD) {
for (++index; index < this.textProps.length; ++index) {
if (!this.textProps[index].invisible) {
break;
}
}
@@ -639,17 +639,17 @@ Rule.prototype = {
this.textProps[index].editor.valueSpan.click();
}
}
},
/**
* Return a string representation of the rule.
*/
- stringifyRule: function() {
+ stringifyRule: function () {
let selectorText = this.selectorText;
let cssText = "";
let terminator = osString === "WINNT" ? "\r\n" : "\n";
for (let textProp of this.textProps) {
if (!textProp.invisible) {
cssText += "\t" + textProp.stringifyProperty() + terminator;
}
@@ -658,17 +658,17 @@ Rule.prototype = {
return selectorText + " {" + terminator + cssText + "}";
},
/**
* See whether this rule has any non-invisible properties.
* @return {Boolean} true if there is any visible property, or false
* if all properties are invisible
*/
- hasAnyVisibleProperties: function() {
+ hasAnyVisibleProperties: function () {
for (let prop of this.textProps) {
if (!prop.invisible) {
return true;
}
}
return false;
}
};
--- a/devtools/client/inspector/rules/models/text-property.js
+++ b/devtools/client/inspector/rules/models/text-property.js
@@ -6,17 +6,17 @@
"use strict";
const {Cc, Ci, Cu} = require("chrome");
const {escapeCSSComment} = require("devtools/client/shared/css-parsing-utils");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyGetter(this, "domUtils", function() {
+XPCOMUtils.defineLazyGetter(this, "domUtils", function () {
return Cc["@mozilla.org/inspector/dom-utils;1"].getService(Ci.inIDOMUtils);
});
/**
* TextProperty is responsible for the following:
* Manages a single property from the authoredText attribute of the
* relevant declaration.
* Maintains a list of computed properties that come from this
@@ -51,26 +51,26 @@ function TextProperty(rule, name, value,
this.updateComputed();
}
TextProperty.prototype = {
/**
* Update the editor associated with this text property,
* if any.
*/
- updateEditor: function() {
+ updateEditor: function () {
if (this.editor) {
this.editor.update();
}
},
/**
* Update the list of computed properties for this text property.
*/
- updateComputed: function() {
+ updateComputed: function () {
if (!this.name) {
return;
}
// This is a bit funky. To get the list of computed properties
// for this text property, we'll set the property on a dummy element
// and see what the computed style looks like.
let dummyElement = this.rule.elementStyle.ruleView.dummyElement;
@@ -102,77 +102,77 @@ TextProperty.prototype = {
/**
* Set all the values from another TextProperty instance into
* this TextProperty instance.
*
* @param {TextProperty} prop
* The other TextProperty instance.
*/
- set: function(prop) {
+ set: function (prop) {
let changed = false;
for (let item of ["name", "value", "priority", "enabled"]) {
if (this[item] !== prop[item]) {
this[item] = prop[item];
changed = true;
}
}
if (changed) {
this.updateEditor();
}
},
- setValue: function(value, priority, force = false) {
+ setValue: function (value, priority, force = false) {
let store = this.rule.elementStyle.store;
if (this.editor && value !== this.editor.committed.value || force) {
store.userProperties.setProperty(this.rule.style, this.name, value);
}
this.rule.setPropertyValue(this, value, priority);
this.updateEditor();
},
/**
* Called when the property's value has been updated externally, and
* the property and editor should update.
*/
- noticeNewValue: function(value) {
+ noticeNewValue: function (value) {
if (value !== this.value) {
this.value = value;
this.updateEditor();
}
},
- setName: function(name) {
+ setName: function (name) {
let store = this.rule.elementStyle.store;
if (name !== this.name) {
store.userProperties.setProperty(this.rule.style, name,
this.editor.committed.value);
}
this.rule.setPropertyName(this, name);
this.updateEditor();
},
- setEnabled: function(value) {
+ setEnabled: function (value) {
this.rule.setPropertyEnabled(this, value);
this.updateEditor();
},
- remove: function() {
+ remove: function () {
this.rule.removeProperty(this);
},
/**
* Return a string representation of the rule property.
*/
- stringifyProperty: function() {
+ stringifyProperty: function () {
// Get the displayed property value
let declaration = this.name + ": " + this.editor.valueSpan.textContent +
";";
// Comment out property declarations that are not enabled
if (!this.enabled) {
declaration = "/* " + escapeCSSComment(declaration) + " */";
}
@@ -180,17 +180,17 @@ TextProperty.prototype = {
return declaration;
},
/**
* See whether this property's name is known.
*
* @return {Boolean} true if the property name is known, false otherwise.
*/
- isKnownProperty: function() {
+ isKnownProperty: function () {
try {
// If the property name is invalid, the cssPropertyIsShorthand
// will throw an exception. But if it is valid, no exception will
// be thrown; so we just ignore the return value.
domUtils.cssPropertyIsShorthand(this.name);
return true;
} catch (e) {
return false;
@@ -198,14 +198,14 @@ TextProperty.prototype = {
},
/**
* Validate this property. Does it make sense for this value to be assigned
* to this property name? This does not apply the property value
*
* @return {Boolean} true if the property value is valid, false otherwise.
*/
- isValid: function() {
+ isValid: function () {
return domUtils.cssPropertyIsValid(this.name, this.value);
}
};
exports.TextProperty = TextProperty;
--- a/devtools/client/inspector/rules/rules.js
+++ b/devtools/client/inspector/rules/rules.js
@@ -31,27 +31,27 @@ Cu.import("resource://gre/modules/XPCOMU
loader.lazyRequireGetter(this, "overlays",
"devtools/client/inspector/shared/style-inspector-overlays");
loader.lazyRequireGetter(this, "EventEmitter",
"devtools/shared/event-emitter");
loader.lazyRequireGetter(this, "StyleInspectorMenu",
"devtools/client/inspector/shared/style-inspector-menu");
-XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function() {
+XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function () {
return Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper);
});
-XPCOMUtils.defineLazyGetter(this, "_strings", function() {
+XPCOMUtils.defineLazyGetter(this, "_strings", function () {
return Services.strings.createBundle(
"chrome://devtools-shared/locale/styleinspector.properties");
});
-loader.lazyGetter(this, "AutocompletePopup", function() {
+loader.lazyGetter(this, "AutocompletePopup", function () {
return require("devtools/client/shared/autocomplete-popup").AutocompletePopup;
});
const HTML_NS = "http://www.w3.org/1999/xhtml";
const PREF_UA_STYLES = "devtools.inspector.showUserAgentStyles";
const PREF_DEFAULT_COLOR_UNIT = "devtools.defaultColorUnit";
const PREF_ENABLE_MDN_DOCS_TOOLTIP =
"devtools.inspector.mdnDocsTooltip.enabled";
@@ -293,17 +293,17 @@ CssRuleView.prototype = {
*
* @param {DOMNode} selectorIcon
* The icon that was clicked to toggle the selector. The
* class 'highlighted' will be added when the selector is
* highlighted.
* @param {String} selector
* The selector used to find nodes in the page.
*/
- toggleSelectorHighlighter: function(selectorIcon, selector) {
+ toggleSelectorHighlighter: function (selectorIcon, selector) {
if (this.lastSelectorIcon) {
this.lastSelectorIcon.classList.remove("highlighted");
}
selectorIcon.classList.remove("highlighted");
this.unhighlightSelector().then(() => {
if (selector !== this.highlightedSelector) {
this.highlightedSelector = selector;
@@ -349,17 +349,17 @@ CssRuleView.prototype = {
* @param {DOMNode} node
* The node which we want information about
* @return {Object} The type information object contains the following props:
* - type {String} One of the VIEW_NODE_XXX_TYPE const in
* style-inspector-overlays
* - value {Object} Depends on the type of the node
* returns null of the node isn't anything we care about
*/
- getNodeInfo: function(node) {
+ getNodeInfo: function (node) {
if (!node) {
return null;
}
let type, value;
let classes = node.classList;
let prop = getParentTextProperty(node);
@@ -418,52 +418,52 @@ CssRuleView.prototype = {
return {type, value};
},
/**
* Retrieve the RuleEditor instance that should be stored on
* the offset parent of the node
*/
- _getRuleEditorForNode: function(node) {
+ _getRuleEditorForNode: function (node) {
if (!node.offsetParent) {
// some nodes don't have an offsetParent, but their parentNode does
node = node.parentNode;
}
return node.offsetParent._ruleEditor;
},
/**
* Context menu handler.
*/
- _onContextMenu: function(event) {
+ _onContextMenu: function (event) {
this._contextmenu.show(event);
},
/**
* Callback for copy event. Copy the selected text.
*
* @param {Event} event
* copy event object.
*/
- _onCopy: function(event) {
+ _onCopy: function (event) {
if (event) {
this.copySelection(event.target);
event.preventDefault();
}
},
/**
* Copy the current selection. The current target is necessary
* if the selection is inside an input or a textarea
*
* @param {DOMNode} target
* DOMNode target of the copy action
*/
- copySelection: function(target) {
+ copySelection: function (target) {
try {
let text = "";
let nodeName = target && target.nodeName;
if (nodeName === "input" || nodeName == "textarea") {
let start = Math.min(target.selectionStart, target.selectionEnd);
let end = Math.max(target.selectionStart, target.selectionEnd);
let count = end - start;
@@ -485,17 +485,17 @@ CssRuleView.prototype = {
console.error(e);
}
},
/**
* A helper for _onAddRule that handles the case where the actor
* does not support as-authored styles.
*/
- _onAddNewRuleNonAuthored: function() {
+ _onAddNewRuleNonAuthored: function () {
let elementStyle = this._elementStyle;
let element = elementStyle.element;
let rules = elementStyle.rules;
let pseudoClasses = element.pseudoClassLocks;
this.pageStyle.addNewRule(element, pseudoClasses).then(options => {
let newRule = new Rule(elementStyle, options);
rules.push(newRule);
@@ -519,17 +519,17 @@ CssRuleView.prototype = {
editor.selectorText.click();
elementStyle._changed();
});
},
/**
* Add a new rule to the current element.
*/
- _onAddRule: function() {
+ _onAddRule: function () {
let elementStyle = this._elementStyle;
let element = elementStyle.element;
let client = this.inspector.toolbox._target.client;
let pseudoClasses = element.pseudoClassLocks;
if (!client.traits.addNewRule) {
return;
}
@@ -557,78 +557,78 @@ CssRuleView.prototype = {
}
}
});
},
/**
* Disables add rule button when needed
*/
- refreshAddRuleButtonState: function() {
+ refreshAddRuleButtonState: function () {
let shouldBeDisabled = !this._viewedElement ||
!this.inspector.selection.isElementNode() ||
this.inspector.selection.isAnonymousNode();
this.addRuleButton.disabled = shouldBeDisabled;
},
- setPageStyle: function(pageStyle) {
+ setPageStyle: function (pageStyle) {
this.pageStyle = pageStyle;
},
/**
* Return {Boolean} true if the rule view currently has an input
* editor visible.
*/
get isEditing() {
return this.tooltips.isEditing ||
this.element.querySelectorAll(".styleinspector-propertyeditor")
.length > 0;
},
- _handlePrefChange: function(pref) {
+ _handlePrefChange: function (pref) {
if (pref === PREF_UA_STYLES) {
this.showUserAgentStyles = Services.prefs.getBoolPref(pref);
}
// Reselect the currently selected element
let refreshOnPrefs = [PREF_UA_STYLES, PREF_DEFAULT_COLOR_UNIT];
if (refreshOnPrefs.indexOf(pref) > -1) {
this.selectElement(this._viewedElement, true);
}
},
/**
* Update source links when pref for showing original sources changes
*/
- _onSourcePrefChanged: function() {
+ _onSourcePrefChanged: function () {
if (this._elementStyle && this._elementStyle.rules) {
for (let rule of this._elementStyle.rules) {
if (rule.editor) {
rule.editor.updateSourceLink();
}
}
this.inspector.emit("rule-view-sourcelinks-updated");
}
},
/**
* Set the filter style search value.
* @param {String} value
* The search value.
*/
- setFilterStyles: function(value = "") {
+ setFilterStyles: function (value = "") {
this.searchField.value = value;
this.searchField.focus();
this._onFilterStyles();
},
/**
* Called when the user enters a search term in the filter style search box.
*/
- _onFilterStyles: function() {
+ _onFilterStyles: function () {
if (this._filterChangedTimeout) {
clearTimeout(this._filterChangedTimeout);
}
let filterTimeout = (this.searchValue.length > 0) ?
FILTER_CHANGED_TIMEOUT : 0;
this.searchClearButton.hidden = this.searchValue.length === 0;
@@ -700,51 +700,51 @@ CssRuleView.prototype = {
this._filterChangeTimeout = null;
}, filterTimeout);
},
/**
* Handle the search box's keypress event. If the escape key is pressed,
* clear the search box field.
*/
- _onFilterKeyPress: function(event) {
+ _onFilterKeyPress: function (event) {
if (event.keyCode === Ci.nsIDOMKeyEvent.DOM_VK_ESCAPE &&
this._onClearSearch()) {
event.preventDefault();
event.stopPropagation();
}
},
/**
* Context menu handler for filter style search box.
*/
- _onFilterTextboxContextMenu: function(event) {
+ _onFilterTextboxContextMenu: function (event) {
try {
this.styleWindow.focus();
let contextmenu = this.inspector.toolbox.textboxContextMenuPopup;
contextmenu.openPopupAtScreen(event.screenX, event.screenY, true);
} catch (e) {
console.error(e);
}
},
/**
* Called when the user clicks on the clear button in the filter style search
* box. Returns true if the search box is cleared and false otherwise.
*/
- _onClearSearch: function() {
+ _onClearSearch: function () {
if (this.searchField.value) {
this.setFilterStyles("");
return true;
}
return false;
},
- destroy: function() {
+ destroy: function () {
this.isDestroyed = true;
this.clear();
this._dummyElement = null;
this.dummyElementPromise = null;
gDummyPromise = null;
this._prefObserver.off(PREF_ORIG_SOURCES, this._onSourcePrefChanged);
@@ -803,36 +803,36 @@ CssRuleView.prototype = {
this.popup.destroy();
},
/**
* Mark the view as selecting an element, disabling all interaction, and
* visually clearing the view after a few milliseconds to avoid confusion
* about which element's styles the rule view shows.
*/
- _startSelectingElement: function() {
+ _startSelectingElement: function () {
this.element.classList.add("non-interactive");
},
/**
* Mark the view as no longer selecting an element, re-enabling interaction.
*/
- _stopSelectingElement: function() {
+ _stopSelectingElement: function () {
this.element.classList.remove("non-interactive");
},
/**
* Update the view with a new selected element.
*
* @param {NodeActor} element
* The node whose style rules we'll inspect.
* @param {Boolean} allowRefresh
* Update the view even if the element is the same as last time.
*/
- selectElement: function(element, allowRefresh = false) {
+ selectElement: function (element, allowRefresh = false) {
let refresh = (this._viewedElement === element);
if (refresh && !allowRefresh) {
return promise.resolve(undefined);
}
if (this.popup.isOpen) {
this.popup.hidePopup();
}
@@ -892,17 +892,17 @@ CssRuleView.prototype = {
}
console.error(e);
});
},
/**
* Update the rules for the currently highlighted element.
*/
- refreshPanel: function() {
+ refreshPanel: function () {
// Ignore refreshes during editing or when no element is selected.
if (this.isEditing || !this._elementStyle) {
return promise.resolve(undefined);
}
// Repopulate the element style once the current modifications are done.
let promises = [];
for (let rule of this._elementStyle.rules) {
@@ -915,26 +915,26 @@ CssRuleView.prototype = {
return this._populate();
});
},
/**
* Clear the pseudo class options panel by removing the checked and disabled
* attributes for each checkbox.
*/
- clearPseudoClassPanel: function() {
+ clearPseudoClassPanel: function () {
this.hoverCheckbox.checked = this.hoverCheckbox.disabled = false;
this.activeCheckbox.checked = this.activeCheckbox.disabled = false;
this.focusCheckbox.checked = this.focusCheckbox.disabled = false;
},
/**
* Update the pseudo class options for the currently highlighted element.
*/
- refreshPseudoClassPanel: function() {
+ refreshPseudoClassPanel: function () {
if (!this._elementStyle || !this.inspector.selection.isElementNode()) {
this.hoverCheckbox.disabled = true;
this.activeCheckbox.disabled = true;
this.focusCheckbox.disabled = true;
return;
}
for (let pseudoClassLock of this._elementStyle.element.pseudoClassLocks) {
@@ -950,17 +950,17 @@ CssRuleView.prototype = {
case ":focus": {
this.focusCheckbox.checked = true;
break;
}
}
}
},
- _populate: function() {
+ _populate: function () {
let elementStyle = this._elementStyle;
return this._elementStyle.populate().then(() => {
if (this._elementStyle !== elementStyle || this.isDestroyed) {
return null;
}
this._clearRules();
let onEditorsReady = this._createEditors();
@@ -971,38 +971,38 @@ CssRuleView.prototype = {
this.emit("ruleview-refreshed");
}, e => console.error(e));
}).then(null, promiseWarn);
},
/**
* Show the user that the rule view has no node selected.
*/
- _showEmpty: function() {
+ _showEmpty: function () {
if (this.styleDocument.getElementById("noResults") > 0) {
return;
}
createChild(this.element, "div", {
id: "noResults",
textContent: CssLogic.l10n("rule.empty")
});
},
/**
* Clear the rules.
*/
- _clearRules: function() {
+ _clearRules: function () {
this.element.innerHTML = "";
},
/**
* Clear the rule view.
*/
- clear: function(clearDom = true) {
+ clear: function (clearDom = true) {
this.lastSelectorIcon = null;
if (clearDom) {
this._clearRules();
}
this._viewedElement = null;
if (this._elementStyle) {
@@ -1010,17 +1010,17 @@ CssRuleView.prototype = {
this._elementStyle = null;
}
},
/**
* Called when the user has made changes to the ElementStyle.
* Emits an event that clients can listen to.
*/
- _changed: function() {
+ _changed: function () {
this.emit("ruleview-changed");
},
/**
* Text for header that shows above rules for this element
*/
get selectedElementLabel() {
if (this._selectedElementLabel) {
@@ -1053,17 +1053,17 @@ CssRuleView.prototype = {
* Creates an expandable container in the rule view
*
* @param {String} label
* The label for the container header
* @param {Boolean} isPseudo
* Whether or not the container will hold pseudo element rules
* @return {DOMNode} The container element
*/
- createExpandableContainer: function(label, isPseudo = false) {
+ createExpandableContainer: function (label, isPseudo = false) {
let header = this.styleDocument.createElementNS(HTML_NS, "div");
header.className = this._getRuleViewHeaderClassName(true);
header.textContent = label;
let twisty = this.styleDocument.createElementNS(HTML_NS, "span");
twisty.className = "ruleview-expander theme-twisty";
twisty.setAttribute("open", "true");
@@ -1100,17 +1100,17 @@ CssRuleView.prototype = {
* Clickable toggle DOM Node
* @param {DOMNode} container
* Expandable container DOM Node
* @param {Boolean} isPseudo
* Whether or not the container will hold pseudo element rules
* @param {Boolean} showPseudo
* Whether or not pseudo element rules should be displayed
*/
- _toggleContainerVisibility: function(twisty, container, isPseudo,
+ _toggleContainerVisibility: function (twisty, container, isPseudo,
showPseudo) {
let isOpen = twisty.getAttribute("open");
if (isPseudo) {
this._showPseudoElements = !!showPseudo;
Services.prefs.setBoolPref("devtools.inspector.show_pseudo_elements",
this.showPseudoElements);
@@ -1123,26 +1123,26 @@ CssRuleView.prototype = {
if (isOpen) {
twisty.removeAttribute("open");
} else {
twisty.setAttribute("open", "true");
}
},
- _getRuleViewHeaderClassName: function(isPseudo) {
+ _getRuleViewHeaderClassName: function (isPseudo) {
let baseClassName = "theme-gutter ruleview-header";
return isPseudo ? baseClassName + " ruleview-expandable-header" :
baseClassName;
},
/**
* Creates editor UI for each of the rules in _elementStyle.
*/
- _createEditors: function() {
+ _createEditors: function () {
// Run through the current list of rules, attaching
// their editors in order. Create editors if needed.
let lastInheritedSource = "";
let lastKeyframes = null;
let seenPseudoElement = false;
let seenNormalElement = false;
let seenSearchTerm = false;
let container = null;
@@ -1222,17 +1222,17 @@ CssRuleView.prototype = {
* Highlight rules that matches the filter search value and returns a
* boolean indicating whether or not rules were highlighted.
*
* @param {Rule} rule
* The rule object we're highlighting if its rule selectors or
* property values match the search value.
* @return {Boolean} true if the rule was highlighted, false otherwise.
*/
- highlightRule: function(rule) {
+ highlightRule: function (rule) {
let isRuleSelectorHighlighted = this._highlightRuleSelector(rule);
let isStyleSheetHighlighted = this._highlightStyleSheet(rule);
let isHighlighted = isRuleSelectorHighlighted || isStyleSheetHighlighted;
// Highlight search matches in the rule properties
for (let textProp of rule.textProps) {
if (!textProp.invisible && this._highlightProperty(textProp.editor)) {
isHighlighted = true;
@@ -1246,17 +1246,17 @@ CssRuleView.prototype = {
* Highlights the rule selector that matches the filter search value and
* returns a boolean indicating whether or not the selector was highlighted.
*
* @param {Rule} rule
* The Rule object.
* @return {Boolean} true if the rule selector was highlighted,
* false otherwise.
*/
- _highlightRuleSelector: function(rule) {
+ _highlightRuleSelector: function (rule) {
let isSelectorHighlighted = false;
let selectorNodes = [...rule.editor.selectorText.childNodes];
if (rule.domRule.type === Ci.nsIDOMCSSRule.KEYFRAME_RULE) {
selectorNodes = [rule.editor.selectorText];
} else if (rule.domRule.type === ELEMENT_STYLE) {
selectorNodes = [];
}
@@ -1279,17 +1279,17 @@ CssRuleView.prototype = {
/**
* Highlights the stylesheet source that matches the filter search value and
* returns a boolean indicating whether or not the stylesheet source was
* highlighted.
*
* @return {Boolean} true if the stylesheet source was highlighted, false
* otherwise.
*/
- _highlightStyleSheet: function(rule) {
+ _highlightStyleSheet: function (rule) {
let styleSheetSource = rule.title.toLowerCase();
let isStyleSheetHighlighted = this.searchData.strictSearchValue ?
styleSheetSource === this.searchData.strictSearchValue :
styleSheetSource.includes(this.searchValue);
if (isStyleSheetHighlighted) {
rule.editor.source.classList.add("ruleview-highlight");
}
@@ -1302,17 +1302,17 @@ CssRuleView.prototype = {
* filter search value and returns a boolean indicating whether or not the
* property or computed property was highlighted.
*
* @param {TextPropertyEditor} editor
* The rule property TextPropertyEditor object.
* @return {Boolean} true if the property or computed property was
* highlighted, false otherwise.
*/
- _highlightProperty: function(editor) {
+ _highlightProperty: function (editor) {
let isPropertyHighlighted = this._highlightRuleProperty(editor);
let isComputedHighlighted = this._highlightComputedProperty(editor);
// Expand the computed list if a computed property is highlighted and the
// property rule is not highlighted
if (!isPropertyHighlighted && isComputedHighlighted &&
!editor.computed.hasAttribute("user-open")) {
editor.expandForFilter();
@@ -1323,17 +1323,17 @@ CssRuleView.prototype = {
/**
* Called when TextPropertyEditor is updated and updates the rule property
* highlight.
*
* @param {TextPropertyEditor} editor
* The rule property TextPropertyEditor object.
*/
- _updatePropertyHighlight: function(editor) {
+ _updatePropertyHighlight: function (editor) {
if (!this.searchValue || !this.searchData) {
return;
}
this._clearHighlight(editor.element);
if (this._highlightProperty(editor)) {
this.searchField.classList.remove("devtools-style-searchbox-no-match");
@@ -1345,17 +1345,17 @@ CssRuleView.prototype = {
* and returns a boolean indicating whether or not the property was
* highlighted.
*
* @param {TextPropertyEditor} editor
* The rule property TextPropertyEditor object.
* @return {Boolean} true if the rule property was highlighted,
* false otherwise.
*/
- _highlightRuleProperty: function(editor) {
+ _highlightRuleProperty: function (editor) {
// Get the actual property value displayed in the rule view
let propertyName = editor.prop.name.toLowerCase();
let propertyValue = editor.valueSpan.textContent.toLowerCase();
return this._highlightMatches(editor.container, propertyName,
propertyValue);
},
@@ -1364,17 +1364,17 @@ CssRuleView.prototype = {
* returns a boolean indicating whether or not the computed property was
* highlighted.
*
* @param {TextPropertyEditor} editor
* The rule property TextPropertyEditor object.
* @return {Boolean} true if the computed property was highlighted, false
* otherwise.
*/
- _highlightComputedProperty: function(editor) {
+ _highlightComputedProperty: function (editor) {
let isComputedHighlighted = false;
// Highlight search matches in the computed list of properties
editor._populateComputed();
for (let computed of editor.prop.computed) {
if (computed.element) {
// Get the actual property value displayed in the computed list
let computedName = computed.name.toLowerCase();
@@ -1397,17 +1397,17 @@ CssRuleView.prototype = {
* The node to highlight if search terms match
* @param {String} propertyName
* The property name of a rule
* @param {String} propertyValue
* The property value of a rule
* @return {Boolean} true if the given search terms match the property, false
* otherwise.
*/
- _highlightMatches: function(element, propertyName, propertyValue) {
+ _highlightMatches: function (element, propertyName, propertyValue) {
let {
searchPropertyName,
searchPropertyValue,
searchPropertyMatch,
strictSearchPropertyName,
strictSearchPropertyValue,
strictSearchAllValues,
} = this.searchData;
@@ -1442,32 +1442,32 @@ CssRuleView.prototype = {
return matches;
},
/**
* Clear all search filter highlights in the panel, and close the computed
* list if toggled opened
*/
- _clearHighlight: function(element) {
+ _clearHighlight: function (element) {
for (let el of element.querySelectorAll(".ruleview-highlight")) {
el.classList.remove("ruleview-highlight");
}
for (let computed of element.querySelectorAll(
".ruleview-computedlist[filter-open]")) {
computed.parentNode._textPropertyEditor.collapseForFilter();
}
},
/**
* Called when the pseudo class panel button is clicked and toggles
* the display of the pseudo class panel.
*/
- _onTogglePseudoClassPanel: function() {
+ _onTogglePseudoClassPanel: function () {
if (this.pseudoClassPanel.hidden) {
this.pseudoClassToggle.setAttribute("checked", "true");
this.hoverCheckbox.setAttribute("tabindex", "0");
this.activeCheckbox.setAttribute("tabindex", "0");
this.focusCheckbox.setAttribute("tabindex", "0");
} else {
this.pseudoClassToggle.removeAttribute("checked");
this.hoverCheckbox.setAttribute("tabindex", "-1");
@@ -1477,35 +1477,35 @@ CssRuleView.prototype = {
this.pseudoClassPanel.hidden = !this.pseudoClassPanel.hidden;
},
/**
* Called when a pseudo class checkbox is clicked and toggles
* the pseudo class for the current selected element.
*/
- _onTogglePseudoClass: function(event) {
+ _onTogglePseudoClass: function (event) {
let target = event.currentTarget;
this.inspector.togglePseudoClass(target.value);
},
/**
* Handle the keydown event in the rule view.
*/
- _onKeydown: function(event) {
+ _onKeydown: function (event) {
if (this.element.classList.contains("non-interactive") &&
(event.code === "Enter" || event.code === " ")) {
event.preventDefault();
}
},
/**
* Handle the keypress event in the rule view.
*/
- _onKeypress: function(event) {
+ _onKeypress: function (event) {
if (!event.target.closest("#sidebar-panel-ruleview")) {
return;
}
let isOSX = Services.appinfo.OS === "Darwin";
if (((isOSX && event.metaKey && !event.ctrlKey && !event.altKey) ||
(!isOSX && event.ctrlKey && !event.metaKey && !event.altKey)) &&
@@ -1616,24 +1616,24 @@ function RuleViewTool(inspector, window)
this.inspector.pageStyle.on("stylesheet-updated", this.refresh);
this.inspector.walker.on("mutations", this.onMutations);
this.inspector.walker.on("resize", this.onResized);
this.onSelected();
}
RuleViewTool.prototype = {
- isSidebarActive: function() {
+ isSidebarActive: function () {
if (!this.view) {
return false;
}
return this.inspector.sidebar.getCurrentTabID() == "ruleview";
},
- onSelected: function(event) {
+ onSelected: function (event) {
// Ignore the event if the view has been destroyed, or if it's inactive.
// But only if the current selection isn't null. If it's been set to null,
// let the update go through as this is needed to empty the view on
// navigation.
if (!this.view) {
return;
}
@@ -1653,37 +1653,37 @@ RuleViewTool.prototype = {
if (!event || event == "new-node-front") {
let done = this.inspector.updating("rule-view");
this.view.selectElement(this.inspector.selection.nodeFront)
.then(done, done);
}
},
- refresh: function() {
+ refresh: function () {
if (this.isSidebarActive()) {
this.view.refreshPanel();
}
},
- clearUserProperties: function() {
+ clearUserProperties: function () {
if (this.view && this.view.store && this.view.store.userProperties) {
this.view.store.userProperties.clear();
}
},
- onPanelSelected: function() {
+ onPanelSelected: function () {
if (this.inspector.selection.nodeFront === this.view.viewedElement) {
this.refresh();
} else {
this.onSelected();
}
},
- onLinkClicked: function(e, rule) {
+ onLinkClicked: function (e, rule) {
let sheet = rule.parentStyleSheet;
// Chrome stylesheets are not listed in the style editor, so show
// these sheets in the view source window instead.
if (!sheet || sheet.isSystem) {
let href = rule.nodeHref || rule.href;
let toolbox = gDevTools.getToolbox(this.inspector.target);
toolbox.viewSource(href, rule.line);
@@ -1692,56 +1692,56 @@ RuleViewTool.prototype = {
let location = promise.resolve(rule.location);
if (Services.prefs.getBoolPref(PREF_ORIG_SOURCES)) {
location = rule.getOriginalLocation();
}
location.then(({ source, href, line, column }) => {
let target = this.inspector.target;
if (Tools.styleEditor.isTargetSupported(target)) {
- gDevTools.showToolbox(target, "styleeditor").then(function(toolbox) {
+ gDevTools.showToolbox(target, "styleeditor").then(function (toolbox) {
let url = source || href;
toolbox.getCurrentPanel().selectStyleSheet(url, line, column);
});
}
return;
});
},
- onPropertyChanged: function() {
+ onPropertyChanged: function () {
this.inspector.markDirty();
},
- onViewRefreshed: function() {
+ onViewRefreshed: function () {
this.inspector.emit("rule-view-refreshed");
},
/**
* When markup mutations occur, if an attribute of the selected node changes,
* we need to refresh the view as that might change the node's styles.
*/
- onMutations: function(mutations) {
+ onMutations: function (mutations) {
for (let {type, target} of mutations) {
if (target === this.inspector.selection.nodeFront &&
type === "attributes") {
this.refresh();
break;
}
}
},
/**
* When the window gets resized, this may cause media-queries to match, and
* therefore, different styles may apply.
*/
- onResized: function() {
+ onResized: function () {
this.refresh();
},
- destroy: function() {
+ destroy: function () {
this.inspector.walker.off("mutations", this.onMutations);
this.inspector.walker.off("resize", this.onResized);
this.inspector.selection.off("detached", this.onSelected);
this.inspector.selection.off("pseudoclass", this.refresh);
this.inspector.selection.off("new-node-front", this.onSelected);
this.inspector.target.off("navigate", this.clearUserProperties);
this.inspector.sidebar.off("ruleview-selected", this.onPanelSelected);
if (this.inspector.pageStyle) {
--- a/devtools/client/inspector/rules/test/browser_rules_copy_styles.js
+++ b/devtools/client/inspector/rules/test/browser_rules_copy_styles.js
@@ -4,17 +4,17 @@
"use strict";
/**
* Tests the behaviour of the copy styles context menu items in the rule
* view.
*/
-XPCOMUtils.defineLazyGetter(this, "osString", function() {
+XPCOMUtils.defineLazyGetter(this, "osString", function () {
return Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
});
const TEST_URI = URL_ROOT + "doc_copystyles.html";
add_task(function* () {
yield addTab(TEST_URI);
let { inspector, view } = yield openRuleView();
--- a/devtools/client/inspector/rules/test/browser_rules_eyedropper.js
+++ b/devtools/client/inspector/rules/test/browser_rules_eyedropper.js
@@ -2,17 +2,17 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// So we can test collecting telemetry on the eyedropper
var oldCanRecord = Services.telemetry.canRecordExtended;
Services.telemetry.canRecordExtended = true;
-registerCleanupFunction(function() {
+registerCleanupFunction(function () {
Services.telemetry.canRecordExtended = oldCanRecord;
});
const EXPECTED_TELEMETRY = {
"DEVTOOLS_PICKER_EYEDROPPER_OPENED_COUNT": 2,
"DEVTOOLS_PICKER_EYEDROPPER_OPENED_PER_USER_FLAG": 1
};
const TEST_URI = `
--- a/devtools/client/inspector/rules/test/browser_rules_select-and-copy-styles.js
+++ b/devtools/client/inspector/rules/test/browser_rules_select-and-copy-styles.js
@@ -1,17 +1,17 @@
/* 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";
// Tests that properties can be selected and copied from the rule view
-XPCOMUtils.defineLazyGetter(this, "osString", function() {
+XPCOMUtils.defineLazyGetter(this, "osString", function () {
return Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
});
const TEST_URI = `
<style type="text/css">
html {
color: #000000;
}
--- a/devtools/client/inspector/rules/test/browser_rules_selector-highlighter_02.js
+++ b/devtools/client/inspector/rules/test/browser_rules_selector-highlighter_02.js
@@ -26,22 +26,22 @@ add_task(function* () {
yield addTab("data:text/html;charset=utf-8," + encodeURIComponent(TEST_URI));
let {inspector, view} = yield openRuleView();
// Mock the highlighter front to get the reference of the NodeFront
let HighlighterFront = {
isShown: false,
nodeFront: null,
options: null,
- show: function(nodeFront, options) {
+ show: function (nodeFront, options) {
this.nodeFront = nodeFront;
this.options = options;
this.isShown = true;
},
- hide: function() {
+ hide: function () {
this.nodeFront = null;
this.options = null;
this.isShown = false;
}
};
// Inject the mock highlighter in the rule-view
view.selectorHighlighter = HighlighterFront;
--- a/devtools/client/inspector/rules/test/browser_rules_selector-highlighter_03.js
+++ b/devtools/client/inspector/rules/test/browser_rules_selector-highlighter_03.js
@@ -21,20 +21,20 @@ const TEST_URI = `
add_task(function* () {
yield addTab("data:text/html;charset=utf-8," + encodeURIComponent(TEST_URI));
let {inspector, view} = yield openRuleView();
// Mock the highlighter front.
let HighlighterFront = {
isShown: false,
- show: function() {
+ show: function () {
this.isShown = true;
},
- hide: function() {
+ hide: function () {
this.isShown = false;
}
};
// Inject the mock highlighter in the rule-view
view.selectorHighlighter = HighlighterFront;
info("Select .node-1 and click on the .node-1 selector icon");
--- a/devtools/client/inspector/rules/test/doc_cssom.html
+++ b/devtools/client/inspector/rules/test/doc_cssom.html
@@ -1,17 +1,17 @@
<!-- Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ -->
<html>
<head>
<title>CSSOM test</title>
<script>
"use strict";
- window.onload = function() {
+ window.onload = function () {
let x = document.styleSheets[0];
x.insertRule("div { color: seagreen; }", 1);
};
</script>
<style>
span { }
</style>
--- a/devtools/client/inspector/rules/test/doc_frame_script.js
+++ b/devtools/client/inspector/rules/test/doc_frame_script.js
@@ -26,17 +26,17 @@ var promise = require("promise");
* Get a value for a given property name in a css rule in a stylesheet, given
* their indexes
* @param {Object} data Expects a data object with the following properties
* - {Number} styleSheetIndex
* - {Number} ruleIndex
* - {String} name
* @return {String} The value, if found, null otherwise
*/
-addMessageListener("Test:GetRulePropertyValue", function(msg) {
+addMessageListener("Test:GetRulePropertyValue", function (msg) {
let {name, styleSheetIndex, ruleIndex} = msg.data;
let value = null;
dumpn("Getting the value for property name " + name + " in sheet " +
styleSheetIndex + " and rule " + ruleIndex);
let sheet = content.document.styleSheets[styleSheetIndex];
if (sheet) {
@@ -51,17 +51,17 @@ addMessageListener("Test:GetRuleProperty
/**
* Get information about all the stylesheets that contain rules that apply to
* a given node. The information contains the sheet href and whether or not the
* sheet is a content sheet or not
* @param {Object} objects Expects a 'target' CPOW object
* @return {Array} A list of stylesheet info objects
*/
-addMessageListener("Test:GetStyleSheetsInfoForNode", function(msg) {
+addMessageListener("Test:GetStyleSheetsInfoForNode", function (msg) {
let target = msg.objects.target;
let sheets = [];
let domUtils = Cc["@mozilla.org/inspector/dom-utils;1"]
.getService(Ci.inIDOMUtils);
let domRules = domUtils.getCSSStyleRules(target);
for (let i = 0, n = domRules.Count(); i < n; i++) {
@@ -78,34 +78,34 @@ addMessageListener("Test:GetStyleSheetsI
/**
* Get the property value from the computed style for an element.
* @param {Object} data Expects a data object with the following properties
* - {String} selector: The selector used to obtain the element.
* - {String} pseudo: pseudo id to query, or null.
* - {String} name: name of the property
* @return {String} The value, if found, null otherwise
*/
-addMessageListener("Test:GetComputedStylePropertyValue", function(msg) {
+addMessageListener("Test:GetComputedStylePropertyValue", function (msg) {
let {selector, pseudo, name} = msg.data;
let element = content.document.querySelector(selector);
let value = content.document.defaultView.getComputedStyle(element, pseudo)
.getPropertyValue(name);
sendAsyncMessage("Test:GetComputedStylePropertyValue", value);
});
/**
* Wait the property value from the computed style for an element and
* compare it with the expected value
* @param {Object} data Expects a data object with the following properties
* - {String} selector: The selector used to obtain the element.
* - {String} pseudo: pseudo id to query, or null.
* - {String} name: name of the property
* - {String} expected: the expected value for property
*/
-addMessageListener("Test:WaitForComputedStylePropertyValue", function(msg) {
+addMessageListener("Test:WaitForComputedStylePropertyValue", function (msg) {
let {selector, pseudo, name, expected} = msg.data;
let element = content.document.querySelector(selector);
waitForSuccess(() => {
let value = content.document.defaultView.getComputedStyle(element, pseudo)
.getPropertyValue(name);
return value === expected;
}).then(() => {
--- a/devtools/client/inspector/rules/test/head.js
+++ b/devtools/client/inspector/rules/test/head.js
@@ -27,17 +27,17 @@ registerCleanupFunction(() => {
/**
* The rule-view tests rely on a frame-script to be injected in the content test
* page. So override the shared-head's addTab to load the frame script after the
* tab was added.
* FIXME: Refactor the rule-view tests to use the testActor instead of a frame
* script, so they can run on remote targets too.
*/
var _addTab = addTab;
-addTab = function(url) {
+addTab = function (url) {
return _addTab(url).then(tab => {
info("Loading the helper frame script " + FRAME_SCRIPT_URL);
let browser = tab.linkedBrowser;
browser.messageManager.loadFrameScript(FRAME_SCRIPT_URL, false);
return tab;
});
};
--- a/devtools/client/inspector/rules/views/rule-editor.js
+++ b/devtools/client/inspector/rules/views/rule-editor.js
@@ -24,17 +24,17 @@ const {
SELECTOR_ATTRIBUTE,
SELECTOR_ELEMENT,
SELECTOR_PSEUDO_CLASS
} = require("devtools/client/shared/css-parsing-utils");
const promise = require("promise");
const Services = require("Services");
const EventEmitter = require("devtools/shared/event-emitter");
-XPCOMUtils.defineLazyGetter(this, "_strings", function() {
+XPCOMUtils.defineLazyGetter(this, "_strings", function () {
return Services.strings.createBundle(
"chrome://devtools-shared/locale/styleinspector.properties");
});
const HTML_NS = "http://www.w3.org/1999/xhtml";
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
/**
@@ -72,48 +72,48 @@ function RuleEditor(ruleView, rule) {
this._locationChanged = this._locationChanged.bind(this);
this.rule.domRule.on("location-changed", this._locationChanged);
this._create();
}
RuleEditor.prototype = {
- destroy: function() {
+ destroy: function () {
this.rule.domRule.off("location-changed");
},
get isSelectorEditable() {
let toolbox = this.ruleView.inspector.toolbox;
let trait = this.isEditable &&
toolbox.target.client.traits.selectorEditable &&
this.rule.domRule.type !== ELEMENT_STYLE &&
this.rule.domRule.type !== Ci.nsIDOMCSSRule.KEYFRAME_RULE;
// Do not allow editing anonymousselectors until we can
// detect mutations on pseudo elements in Bug 1034110.
return trait && !this.rule.elementStyle.element.isAnonymous;
},
- _create: function() {
+ _create: function () {
this.element = this.doc.createElementNS(HTML_NS, "div");
this.element.className = "ruleview-rule theme-separator";
this.element.setAttribute("uneditable", !this.isEditable);
this.element.setAttribute("unmatched", this.rule.isUnmatched);
this.element._ruleEditor = this;
// Give a relative position for the inplace editor's measurement
// span to be placed absolutely against.
this.element.style.position = "relative";
// Add the source link.
this.source = createChild(this.element, "div", {
class: "ruleview-rule-source theme-link"
});
- this.source.addEventListener("click", function() {
+ this.source.addEventListener("click", function () {
if (this.source.hasAttribute("unselectable")) {
return;
}
let rule = this.rule.domRule;
this.ruleView.emit("ruleview-linked-clicked", rule);
}.bind(this));
let sourceLabel = this.doc.createElementNS(XUL_NS, "label");
sourceLabel.setAttribute("crop", "center");
@@ -206,21 +206,21 @@ RuleEditor.prototype = {
});
}
},
/**
* Event handler called when a property changes on the
* StyleRuleActor.
*/
- _locationChanged: function() {
+ _locationChanged: function () {
this.updateSourceLink();
},
- updateSourceLink: function() {
+ updateSourceLink: function () {
let sourceLabel = this.element.querySelector(".ruleview-rule-source-label");
let title = this.rule.title;
let sourceHref = (this.rule.sheet && this.rule.sheet.href) ?
this.rule.sheet.href : title;
let sourceLine = this.rule.ruleLine > 0 ? ":" + this.rule.ruleLine : "";
sourceLabel.setAttribute("tooltiptext", sourceHref + sourceLine);
@@ -262,17 +262,17 @@ RuleEditor.prototype = {
this.emit("source-link-updated");
});
}
},
/**
* Update the rule editor with the contents of the rule.
*/
- populate: function() {
+ populate: function () {
// Clear out existing viewers.
while (this.selectorText.hasChildNodes()) {
this.selectorText.removeChild(this.selectorText.lastChild);
}
// If selector text comes from a css rule, highlight selectors that
// actually match. For custom selector text (such as for the 'element'
// style, just show the text directly.
@@ -345,17 +345,17 @@ RuleEditor.prototype = {
* Property priority.
* @param {Boolean} enabled
* True if the property should be enabled.
* @param {TextProperty} siblingProp
* Optional, property next to which the new property will be added.
* @return {TextProperty}
* The new property
*/
- addProperty: function(name, value, priority, enabled, siblingProp) {
+ addProperty: function (name, value, priority, enabled, siblingProp) {
let prop = this.rule.createProperty(name, value, priority, enabled,
siblingProp);
let index = this.rule.textProps.indexOf(prop);
let editor = new TextPropertyEditor(this, prop);
// Insert this node before the DOM node that is currently at its new index
// in the property list. There is currently one less node in the DOM than
// in the property list, so this causes it to appear after siblingProp.
@@ -377,17 +377,17 @@ RuleEditor.prototype = {
* {
* name: {string},
* value: {string},
* priority: {string}
* }
* @param {TextProperty} siblingProp
* Optional, the property next to which all new props should be added.
*/
- addProperties: function(properties, siblingProp) {
+ addProperties: function (properties, siblingProp) {
if (!properties || !properties.length) {
return;
}
let lastProp = siblingProp;
for (let p of properties) {
let isCommented = Boolean(p.commentOffsets);
let enabled = !isCommented;
@@ -403,17 +403,17 @@ RuleEditor.prototype = {
}
},
/**
* Create a text input for a property name. If a non-empty property
* name is given, we'll create a real TextProperty and add it to the
* rule.
*/
- newProperty: function() {
+ newProperty: function () {
// If we're already creating a new property, ignore this.
if (!this.closeBrace.hasAttribute("tabindex")) {
return;
}
// While we're editing a new property, it doesn't make sense to
// start a second new property editor, so disable focusing the
// close brace for now.
@@ -447,17 +447,17 @@ RuleEditor.prototype = {
/**
* Called when the new property input has been dismissed.
*
* @param {String} value
* The value in the editor.
* @param {Boolean} commit
* True if the value should be committed.
*/
- _onNewProperty: function(value, commit) {
+ _onNewProperty: function (value, commit) {
if (!value || !commit) {
return;
}
// parseDeclarations allows for name-less declarations, but in the present
// case, we're creating a new declaration, it doesn't make sense to accept
// these entries
this.multipleAddedProperties =
@@ -469,17 +469,17 @@ RuleEditor.prototype = {
},
/**
* Called when the new property editor is destroyed.
* This is where the properties (type TextProperty) are actually being
* added, since we want to wait until after the inplace editor `destroy`
* event has been fired to keep consistent UI state.
*/
- _newPropertyDestroy: function() {
+ _newPropertyDestroy: function () {
// We're done, make the close brace focusable again.
this.closeBrace.setAttribute("tabindex", "0");
this.propertyList.removeChild(this.newPropItem);
delete this.newPropItem;
delete this.newPropSpan;
// If properties were added, we want to focus the proper element.
@@ -497,17 +497,17 @@ RuleEditor.prototype = {
*
* @param {String} value
* The value contained in the editor.
* @param {Boolean} commit
* True if the change should be applied.
* @param {Number} direction
* The move focus direction number.
*/
- _onSelectorDone: function(value, commit, direction) {
+ _onSelectorDone: function (value, commit, direction) {
if (!commit || this.isEditing || value === "" ||
value === this.rule.selectorText) {
return;
}
let ruleView = this.ruleView;
let elementStyle = ruleView._elementStyle;
let element = elementStyle.element;
@@ -561,17 +561,17 @@ RuleEditor.prototype = {
/**
* Handle moving the focus change after a tab or return keypress in the
* selector inplace editor.
*
* @param {Number} direction
* The move focus direction number.
*/
- _moveSelectorFocus: function(direction) {
+ _moveSelectorFocus: function (direction) {
if (!direction || direction === Ci.nsIFocusManager.MOVEFOCUS_BACKWARD) {
return;
}
if (this.rule.textProps.length > 0) {
this.rule.textProps[0].editor.nameSpan.click();
} else {
this.propertyList.click();
--- a/devtools/client/inspector/rules/views/text-property-editor.js
+++ b/devtools/client/inspector/rules/views/text-property-editor.js
@@ -76,17 +76,17 @@ TextPropertyEditor.prototype = {
*/
get rule() {
return this.prop.rule;
},
/**
* Create the property editor's DOM.
*/
- _create: function() {
+ _create: function () {
this.element = this.doc.createElementNS(HTML_NS, "li");
this.element.classList.add("ruleview-property");
this.element._textPropertyEditor = this;
this.container = createChild(this.element, "div", {
class: "ruleview-propertycontainer"
});
@@ -274,27 +274,27 @@ TextPropertyEditor.prototype = {
/**
* Resolve a URI based on the rule stylesheet
*
* @param {String} relativePath
* the path to resolve
* @return {String} the resolved path.
*/
- resolveURI: function(relativePath) {
+ resolveURI: function (relativePath) {
if (this.sheetURI) {
relativePath = this.sheetURI.resolve(relativePath);
}
return relativePath;
},
/**
* Populate the span based on changes to the TextProperty.
*/
- update: function() {
+ update: function () {
if (this.ruleView.isDestroyed) {
return;
}
if (this.prop.enabled) {
this.enable.style.removeProperty("visibility");
this.enable.setAttribute("checked", "");
} else {
@@ -418,41 +418,41 @@ TextPropertyEditor.prototype = {
// Populate the computed styles.
this._updateComputed();
// Update the rule property highlight.
this.ruleView._updatePropertyHighlight(this);
},
- _onStartEditing: function() {
+ _onStartEditing: function () {
this.element.classList.remove("ruleview-overridden");
this.enable.style.visibility = "hidden";
},
/**
* Update the indicator for computed styles. The computed styles themselves
* are populated on demand, when they become visible.
*/
- _updateComputed: function() {
+ _updateComputed: function () {
this.computed.innerHTML = "";
let showExpander = this.prop.computed.some(c => c.name !== this.prop.name);
this.expander.style.visibility = showExpander ? "visible" : "hidden";
this._populatedComputed = false;
if (this.expander.hasAttribute("open")) {
this._populateComputed();
}
},
/**
* Populate the list of computed styles.
*/
- _populateComputed: function() {
+ _populateComputed: function () {
if (this._populatedComputed) {
return;
}
this._populatedComputed = true;
for (let computed of this.prop.computed) {
// Don't bother to duplicate information already
// shown in the text property.
@@ -497,17 +497,17 @@ TextPropertyEditor.prototype = {
// styles
computed.element = li;
}
},
/**
* Handles clicks on the disabled property.
*/
- _onEnableClicked: function(event) {
+ _onEnableClicked: function (event) {
let checked = this.enable.hasAttribute("checked");
if (checked) {
this.enable.removeAttribute("checked");
} else {
this.enable.setAttribute("checked", "");
}
this.prop.setEnabled(!checked);
event.stopPropagation();
@@ -515,17 +515,17 @@ TextPropertyEditor.prototype = {
/**
* Handles clicks on the computed property expander. If the computed list is
* open due to user expanding or style filtering, collapse the computed list
* and close the expander. Otherwise, add user-open attribute which is used to
* expand the computed list and tracks whether or not the computed list is
* expanded by manually by the user.
*/
- _onExpandClicked: function(event) {
+ _onExpandClicked: function (event) {
if (this.computed.hasAttribute("filter-open") ||
this.computed.hasAttribute("user-open")) {
this.expander.removeAttribute("open");
this.computed.removeAttribute("filter-open");
this.computed.removeAttribute("user-open");
} else {
this.expander.setAttribute("open", "true");
this.computed.setAttribute("user-open", "");
@@ -535,28 +535,28 @@ TextPropertyEditor.prototype = {
event.stopPropagation();
},
/**
* Expands the computed list when a computed property is matched by the style
* filtering. The filter-open attribute is used to track whether or not the
* computed list was toggled opened by the filter.
*/
- expandForFilter: function() {
+ expandForFilter: function () {
if (!this.computed.hasAttribute("user-open")) {
this.expander.setAttribute("open", "true");
this.computed.setAttribute("filter-open", "");
this._populateComputed();
}
},
/**
* Collapses the computed list that was expanded by style filtering.
*/
- collapseForFilter: function() {
+ collapseForFilter: function () {
this.computed.removeAttribute("filter-open");
if (!this.computed.hasAttribute("user-open")) {
this.expander.removeAttribute("open");
}
},
/**
@@ -566,17 +566,17 @@ TextPropertyEditor.prototype = {
*
* @param {String} value
* The value contained in the editor.
* @param {Boolean} commit
* True if the change should be applied.
* @param {Number} direction
* The move focus direction number.
*/
- _onNameDone: function(value, commit, direction) {
+ _onNameDone: function (value, commit, direction) {
let isNameUnchanged = (!commit && !this.ruleEditor.isEditing) ||
this.committed.name === value;
if (this.prop.value && isNameUnchanged) {
return;
}
// Remove a property if the name is empty
if (!value.trim()) {
@@ -614,17 +614,17 @@ TextPropertyEditor.prototype = {
/**
* Remove property from style and the editors from DOM.
* Begin editing next or previous available property given the focus
* direction.
*
* @param {Number} direction
* The move focus direction number.
*/
- remove: function(direction) {
+ remove: function (direction) {
if (this._colorSwatchSpans && this._colorSwatchSpans.length) {
for (let span of this._colorSwatchSpans) {
this.ruleView.tooltips.colorPicker.removeSwatch(span);
span.off("unit-change", this._onSwatchCommit);
}
}
if (this.angleSwatchSpans && this.angleSwatchSpans.length) {
@@ -646,17 +646,17 @@ TextPropertyEditor.prototype = {
*
* @param {String} value
* The value contained in the editor.
* @param {Boolean} commit
* True if the change should be applied.
* @param {Number} direction
* The move focus direction number.
*/
- _onValueDone: function(value = "", commit, direction) {
+ _onValueDone: function (value = "", commit, direction) {
let parsedProperties = this._getValueAndExtraProperties(value);
let val = parseSingleValue(parsedProperties.firstValue);
let isValueUnchanged = (!commit && !this.ruleEditor.isEditing) ||
!parsedProperties.propertiesToAdd.length &&
this.committed.value === val.value &&
this.committed.priority === val.priority;
// If the value is not empty and unchanged, revert the property back to
// its original value and enabled or disabled state
@@ -692,33 +692,33 @@ TextPropertyEditor.prototype = {
}
}, 0);
}
},
/**
* Called when the swatch editor wants to commit a value change.
*/
- _onSwatchCommit: function() {
+ _onSwatchCommit: function () {
this._onValueDone(this.valueSpan.textContent, true);
this.update();
},
/**
* Called when the swatch editor wants to preview a value change.
*/
- _onSwatchPreview: function() {
+ _onSwatchPreview: function () {
this._previewValue(this.valueSpan.textContent);
},
/**
* Called when the swatch editor closes from an ESC. Revert to the original
* value of this property before editing.
*/
- _onSwatchRevert: function() {
+ _onSwatchRevert: function () {
this._previewValue(this.prop.value, true);
this.update();
},
/**
* Parse a value string and break it into pieces, starting with the
* first value, and into an array of additional properties (if any).
*
@@ -728,17 +728,17 @@ TextPropertyEditor.prototype = {
* @param {String} value
* The string to parse
* @return {Object} An object with the following properties:
* firstValue: A string containing a simple value, like
* "red" or "100px!important"
* propertiesToAdd: An array with additional properties, following the
* parseDeclarations format of {name,value,priority}
*/
- _getValueAndExtraProperties: function(value) {
+ _getValueAndExtraProperties: function (value) {
// The inplace editor will prevent manual typing of multiple properties,
// but we need to deal with the case during a paste event.
// Adding multiple properties inside of value editor sets value with the
// first, then adds any more onto the property list (below this property).
let firstValue = value;
let propertiesToAdd = [];
let properties = parseDeclarations(value);
@@ -768,17 +768,17 @@ TextPropertyEditor.prototype = {
/**
* Live preview this property, without committing changes.
*
* @param {String} value
* The value to set the current property to.
* @param {Boolean} reverting
* True if we're reverting the previously previewed value
*/
- _previewValue: function(value, reverting = false) {
+ _previewValue: function (value, reverting = false) {
// Since function call is throttled, we need to make sure we are still
// editing, and any selector modifications have been completed
if (!reverting && (!this.editing || this.ruleEditor.isEditing)) {
return;
}
let val = parseSingleValue(value);
this.ruleEditor.rule.previewPropertyValue(this.prop, val.value,
@@ -786,14 +786,14 @@ TextPropertyEditor.prototype = {
},
/**
* Validate this property. Does it make sense for this value to be assigned
* to this property name? This does not apply the property value
*
* @return {Boolean} true if the property value is valid, false otherwise.
*/
- isValid: function() {
+ isValid: function () {
return this.prop.isValid();
}
};
exports.TextPropertyEditor = TextPropertyEditor;
--- a/devtools/client/inspector/shared/dom-node-preview.js
+++ b/devtools/client/inspector/shared/dom-node-preview.js
@@ -34,17 +34,17 @@ function DomNodePreview(inspector, optio
this.onHighlighterLocked = this.onHighlighterLocked.bind(this);
EventEmitter.decorate(this);
}
exports.DomNodePreview = DomNodePreview;
DomNodePreview.prototype = {
- init: function(containerEl) {
+ init: function (containerEl) {
let document = containerEl.ownerDocument;
// Init the markup for displaying the target node.
this.el = createNode({
parent: containerEl,
attributes: {
"class": "animation-target"
}
@@ -168,40 +168,40 @@ DomNodePreview.prototype = {
if (!this.options.compact) {
this.classEl.appendChild(document.createTextNode("\""));
this.previewEl.appendChild(document.createTextNode(">"));
}
this.startListeners();
},
- startListeners: function() {
+ startListeners: function () {
// Init events for highlighting and selecting the node.
this.previewEl.addEventListener("mouseover", this.onPreviewMouseOver);
this.previewEl.addEventListener("mouseout", this.onPreviewMouseOut);
this.previewEl.addEventListener("click", this.onSelectElClick);
this.highlightNodeEl.addEventListener("click", this.onHighlightElClick);
// Start to listen for markupmutation events.
this.inspector.on("markupmutation", this.onMarkupMutations);
// Listen to the target node highlighter.
HighlighterLock.on("highlighted", this.onHighlighterLocked);
},
- stopListeners: function() {
+ stopListeners: function () {
HighlighterLock.off("highlighted", this.onHighlighterLocked);
this.inspector.off("markupmutation", this.onMarkupMutations);
this.previewEl.removeEventListener("mouseover", this.onPreviewMouseOver);
this.previewEl.removeEventListener("mouseout", this.onPreviewMouseOut);
this.previewEl.removeEventListener("click", this.onSelectElClick);
this.highlightNodeEl.removeEventListener("click", this.onHighlightElClick);
},
- destroy: function() {
+ destroy: function () {
HighlighterLock.unhighlight().catch(e => console.error(e));
this.stopListeners();
this.el.remove();
this.el = this.tagNameEl = this.idEl = this.classEl = this.pseudoEl = null;
this.highlightNodeEl = this.previewEl = null;
this.nodeFront = this.inspector = null;
@@ -209,40 +209,40 @@ DomNodePreview.prototype = {
get highlighterUtils() {
if (this.inspector && this.inspector.toolbox) {
return this.inspector.toolbox.highlighterUtils;
}
return null;
},
- onPreviewMouseOver: function() {
+ onPreviewMouseOver: function () {
if (!this.nodeFront || !this.highlighterUtils) {
return;
}
this.highlighterUtils.highlightNodeFront(this.nodeFront)
.catch(e => console.error(e));
},
- onPreviewMouseOut: function() {
+ onPreviewMouseOut: function () {
if (!this.nodeFront || !this.highlighterUtils) {
return;
}
this.highlighterUtils.unhighlight()
.catch(e => console.error(e));
},
- onSelectElClick: function() {
+ onSelectElClick: function () {
if (!this.nodeFront) {
return;
}
this.inspector.selection.setNodeFront(this.nodeFront, "dom-node-preview");
},
- onHighlightElClick: function(e) {
+ onHighlightElClick: function (e) {
e.stopPropagation();
let classList = this.highlightNodeEl.classList;
let isHighlighted = classList.contains("selected");
if (isHighlighted) {
classList.remove("selected");
HighlighterLock.unhighlight().then(() => {
@@ -251,37 +251,37 @@ DomNodePreview.prototype = {
} else {
classList.add("selected");
HighlighterLock.highlight(this).then(() => {
this.emit("target-highlighter-locked");
}, error => console.error(error));
}
},
- onHighlighterLocked: function(e, domNodePreview) {
+ onHighlighterLocked: function (e, domNodePreview) {
if (domNodePreview !== this) {
this.highlightNodeEl.classList.remove("selected");
}
},
- onMarkupMutations: function(e, mutations) {
+ onMarkupMutations: function (e, mutations) {
if (!this.nodeFront) {
return;
}
for (let {target} of mutations) {
if (target === this.nodeFront) {
// Re-render with the same nodeFront to update the output.
this.render(this.nodeFront);
break;
}
}
},
- render: function(nodeFront) {
+ render: function (nodeFront) {
this.nodeFront = nodeFront;
let {tagName, attributes} = nodeFront;
if (nodeFront.isPseudoElement) {
this.pseudoEl.textContent = nodeFront.isBeforePseudoElement
? "::before"
: "::after";
this.pseudoEl.style.display = "inline";
--- a/devtools/client/inspector/shared/style-inspector-menu.js
+++ b/devtools/client/inspector/shared/style-inspector-menu.js
@@ -59,29 +59,29 @@ function StyleInspectorMenu(view, option
}
module.exports = StyleInspectorMenu;
StyleInspectorMenu.prototype = {
/**
* Display the style inspector context menu
*/
- show: function(event) {
+ show: function (event) {
try {
// In the sidebar we do not have this.styleDocument.popupNode
// so we need to save the node ourselves.
this.styleDocument.popupNode = event.explicitOriginalTarget;
this.styleWindow.focus();
this._menupopup.openPopupAtScreen(event.screenX, event.screenY, true);
} catch (e) {
console.error(e);
}
},
- _createContextMenu: function() {
+ _createContextMenu: function () {
this._menupopup = this.styleDocument.createElementNS(XUL_NS, "menupopup");
this._menupopup.addEventListener("popupshowing", this._updateMenuItems);
this._menupopup.id = "computed-view-context-menu";
let parentDocument = this.styleWindow.parent.document;
let popupset = parentDocument.documentElement.querySelector("popupset");
if (!popupset) {
popupset = parentDocument.createElementNS(XUL_NS, "popupset");
@@ -89,17 +89,17 @@ StyleInspectorMenu.prototype = {
}
popupset.appendChild(this._menupopup);
this._createContextMenuItems();
},
/**
* Create all context menu items
*/
- _createContextMenuItems: function() {
+ _createContextMenuItems: function () {
this.menuitemCopy = this._createContextMenuItem({
label: "styleinspector.contextmenu.copy",
accesskey: "styleinspector.contextmenu.copy.accessKey",
command: this._onCopy
});
this.menuitemCopyLocation = this._createContextMenuItem({
label: "styleinspector.contextmenu.copyLocation",
@@ -182,17 +182,17 @@ StyleInspectorMenu.prototype = {
type: "checkbox"
});
},
/**
* Create a single context menu item based on the provided configuration
* Returns the created menu item element
*/
- _createContextMenuItem: function(attributes) {
+ _createContextMenuItem: function (attributes) {
let ownerDocument = this._menupopup.ownerDocument;
let item = ownerDocument.createElementNS(XUL_NS, "menuitem");
item.setAttribute("label", _strings.GetStringFromName(attributes.label));
if (attributes.accesskey) {
item.setAttribute("accesskey",
_strings.GetStringFromName(attributes.accesskey));
}
@@ -201,27 +201,27 @@ StyleInspectorMenu.prototype = {
if (attributes.type) {
item.setAttribute("type", attributes.type);
}
this._menupopup.appendChild(item);
return item;
},
- _createMenuSeparator: function() {
+ _createMenuSeparator: function () {
let ownerDocument = this._menupopup.ownerDocument;
let separator = ownerDocument.createElementNS(XUL_NS, "menuseparator");
this._menupopup.appendChild(separator);
},
/**
* Update the context menu. This means enabling or disabling menuitems as
* appropriate.
*/
- _updateMenuItems: function() {
+ _updateMenuItems: function () {
this._updateCopyMenuItems();
let showOrig = Services.prefs.getBoolPref(PREF_ORIG_SOURCES);
this.menuitemSources.setAttribute("checked", showOrig);
let enableMdnDocsTooltip =
Services.prefs.getBoolPref(PREF_ENABLE_MDN_DOCS_TOOLTIP);
this.menuitemShowMdnDocs.hidden = !(enableMdnDocsTooltip &&
@@ -231,17 +231,17 @@ StyleInspectorMenu.prototype = {
this.menuitemAddRule.disabled = !this.isRuleView ||
this.inspector.selection.isAnonymousNode();
},
/**
* Display the necessary copy context menu items depending on the clicked
* node and selection in the rule view.
*/
- _updateCopyMenuItems: function() {
+ _updateCopyMenuItems: function () {
this.menuitemCopy.disabled = !this._hasTextSelected();
this.menuitemCopyColor.hidden = !this._isColorPopup();
this.menuitemCopyImageDataUrl.hidden = !this._isImageUrl();
this.menuitemCopyUrl.hidden = !this._isImageUrl();
this.menuitemCopyRule.hidden = !this.isRuleView;
this.menuitemCopyLocation.hidden = true;
@@ -266,17 +266,17 @@ StyleInspectorMenu.prototype = {
break;
case overlays.VIEW_NODE_LOCATION_TYPE :
this.menuitemCopyLocation.hidden = false;
break;
}
}
},
- _hasTextSelected: function() {
+ _hasTextSelected: function () {
let hasTextSelected;
let selection = this.styleWindow.getSelection();
let node = this._getClickedNode();
if (node.nodeName == "input" || node.nodeName == "textarea") {
let { selectionStart, selectionEnd } = node;
hasTextSelected = isFinite(selectionStart) && isFinite(selectionEnd)
&& selectionStart !== selectionEnd;
@@ -285,29 +285,29 @@ StyleInspectorMenu.prototype = {
}
return hasTextSelected;
},
/**
* Get the type of the currently clicked node
*/
- _getClickedNodeInfo: function() {
+ _getClickedNodeInfo: function () {
let node = this._getClickedNode();
return this.view.getNodeInfo(node);
},
/**
* A helper that determines if the popup was opened with a click to a color
* value and saves the color to this._colorToCopy.
*
* @return {Boolean}
* true if click on color opened the popup, false otherwise.
*/
- _isColorPopup: function() {
+ _isColorPopup: function () {
this._colorToCopy = "";
let container = this._getClickedNode();
if (!container) {
return false;
}
let isColorNode = el => el.dataset && "color" in el.dataset;
@@ -318,82 +318,82 @@ StyleInspectorMenu.prototype = {
return false;
}
}
this._colorToCopy = container.dataset.color;
return true;
},
- _isPropertyName: function() {
+ _isPropertyName: function () {
let nodeInfo = this._getClickedNodeInfo();
if (!nodeInfo) {
return false;
}
return nodeInfo.type == overlays.VIEW_NODE_PROPERTY_TYPE;
},
/**
* Check if the current node (clicked node) is an image URL
*
* @return {Boolean} true if the node is an image url
*/
- _isImageUrl: function() {
+ _isImageUrl: function () {
let nodeInfo = this._getClickedNodeInfo();
if (!nodeInfo) {
return false;
}
return nodeInfo.type == overlays.VIEW_NODE_IMAGE_URL_TYPE;
},
/**
* Get the DOM Node container for the current popupNode.
* If popupNode is a textNode, return the parent node, otherwise return
* popupNode itself.
*
* @return {DOMNode}
*/
- _getClickedNode: function() {
+ _getClickedNode: function () {
let container = null;
let node = this.styleDocument.popupNode;
if (node) {
let isTextNode = node.nodeType == node.TEXT_NODE;
container = isTextNode ? node.parentElement : node;
}
return container;
},
/**
* Select all text.
*/
- _onSelectAll: function() {
+ _onSelectAll: function () {
let selection = this.styleWindow.getSelection();
selection.selectAllChildren(this.view.element);
},
/**
* Copy the most recently selected color value to clipboard.
*/
- _onCopy: function() {
+ _onCopy: function () {
this.view.copySelection(this.styleDocument.popupNode);
},
/**
* Copy the most recently selected color value to clipboard.
*/
- _onCopyColor: function() {
+ _onCopyColor: function () {
clipboardHelper.copyString(this._colorToCopy);
},
/*
* Retrieve the url for the selected image and copy it to the clipboard
*/
- _onCopyUrl: function() {
+ _onCopyUrl: function () {
if (!this._clickedNodeInfo) {
return;
}
clipboardHelper.copyString(this._clickedNodeInfo.value.url);
},
/**
@@ -417,121 +417,121 @@ StyleInspectorMenu.prototype = {
}
clipboardHelper.copyString(message);
}),
/**
* Show docs from MDN for a CSS property.
*/
- _onShowMdnDocs: function() {
+ _onShowMdnDocs: function () {
let cssPropertyName = this.styleDocument.popupNode.textContent;
let anchor = this.styleDocument.popupNode.parentNode;
let cssDocsTooltip = this.view.tooltips.cssDocs;
cssDocsTooltip.show(anchor, cssPropertyName);
},
/**
* Add a new rule to the current element.
*/
- _onAddNewRule: function() {
+ _onAddNewRule: function () {
this.view._onAddRule();
},
/**
* Copy the rule source location of the current clicked node.
*/
- _onCopyLocation: function() {
+ _onCopyLocation: function () {
if (!this._clickedNodeInfo) {
return;
}
clipboardHelper.copyString(this._clickedNodeInfo.value);
},
/**
* Copy the rule property declaration of the current clicked node.
*/
- _onCopyPropertyDeclaration: function() {
+ _onCopyPropertyDeclaration: function () {
if (!this._clickedNodeInfo) {
return;
}
let textProp = this._clickedNodeInfo.value.textProperty;
clipboardHelper.copyString(textProp.stringifyProperty());
},
/**
* Copy the rule property name of the current clicked node.
*/
- _onCopyPropertyName: function() {
+ _onCopyPropertyName: function () {
if (!this._clickedNodeInfo) {
return;
}
clipboardHelper.copyString(this._clickedNodeInfo.value.property);
},
/**
* Copy the rule property value of the current clicked node.
*/
- _onCopyPropertyValue: function() {
+ _onCopyPropertyValue: function () {
if (!this._clickedNodeInfo) {
return;
}
clipboardHelper.copyString(this._clickedNodeInfo.value.value);
},
/**
* Copy the rule of the current clicked node.
*/
- _onCopyRule: function() {
+ _onCopyRule: function () {
let ruleEditor =
this.styleDocument.popupNode.parentNode.offsetParent._ruleEditor;
let rule = ruleEditor.rule;
clipboardHelper.copyString(rule.stringifyRule());
},
/**
* Copy the rule selector of the current clicked node.
*/
- _onCopySelector: function() {
+ _onCopySelector: function () {
if (!this._clickedNodeInfo) {
return;
}
clipboardHelper.copyString(this._clickedNodeInfo.value);
},
/**
* Toggle the original sources pref.
*/
- _onToggleOrigSources: function() {
+ _onToggleOrigSources: function () {
let isEnabled = Services.prefs.getBoolPref(PREF_ORIG_SOURCES);
Services.prefs.setBoolPref(PREF_ORIG_SOURCES, !isEnabled);
},
- destroy: function() {
+ destroy: function () {
this._removeContextMenuItems();
// Destroy the context menu.
this._menupopup.removeEventListener("popupshowing", this._updateMenuItems);
this._menupopup.parentNode.removeChild(this._menupopup);
this._menupopup = null;
this.popupNode = null;
this.styleDocument.popupNode = null;
this.view = null;
this.inspector = null;
this.styleDocument = null;
this.styleWindow = null;
},
- _removeContextMenuItems: function() {
+ _removeContextMenuItems: function () {
this._removeContextMenuItem("menuitemAddRule", this._onAddNewRule);
this._removeContextMenuItem("menuitemCopy", this._onCopy);
this._removeContextMenuItem("menuitemCopyColor", this._onCopyColor);
this._removeContextMenuItem("menuitemCopyImageDataUrl",
this._onCopyImageDataUrl);
this._removeContextMenuItem("menuitemCopyLocation", this._onCopyLocation);
this._removeContextMenuItem("menuitemCopyPropertyDeclaration",
this._onCopyPropertyDeclaration);
@@ -542,15 +542,15 @@ StyleInspectorMenu.prototype = {
this._removeContextMenuItem("menuitemCopyRule", this._onCopyRule);
this._removeContextMenuItem("menuitemCopySelector", this._onCopySelector);
this._removeContextMenuItem("menuitemCopyUrl", this._onCopyUrl);
this._removeContextMenuItem("menuitemSelectAll", this._onSelectAll);
this._removeContextMenuItem("menuitemShowMdnDocs", this._onShowMdnDocs);
this._removeContextMenuItem("menuitemSources", this._onToggleOrigSources);
},
- _removeContextMenuItem: function(itemName, callback) {
+ _removeContextMenuItem: function (itemName, callback) {
if (this[itemName]) {
this[itemName].removeEventListener("command", callback);
this[itemName] = null;
}
}
};
--- a/devtools/client/inspector/shared/style-inspector-overlays.js
+++ b/devtools/client/inspector/shared/style-inspector-overlays.js
@@ -72,47 +72,47 @@ function HighlightersOverlay(view) {
exports.HighlightersOverlay = HighlightersOverlay;
HighlightersOverlay.prototype = {
/**
* Add the highlighters overlay to the view. This will start tracking mouse
* movements and display highlighters when needed
*/
- addToView: function() {
+ addToView: function () {
if (!this.supportsHighlighters || this._isStarted || this._isDestroyed) {
return;
}
let el = this.view.element;
el.addEventListener("mousemove", this._onMouseMove, false);
el.addEventListener("mouseleave", this._onMouseLeave, false);
this._isStarted = true;
},
/**
* Remove the overlay from the current view. This will stop tracking mouse
* movement and showing highlighters
*/
- removeFromView: function() {
+ removeFromView: function () {
if (!this.supportsHighlighters || !this._isStarted || this._isDestroyed) {
return;
}
this._hideCurrent();
let el = this.view.element;
el.removeEventListener("mousemove", this._onMouseMove, false);
el.removeEventListener("mouseleave", this._onMouseLeave, false);
this._isStarted = false;
},
- _onMouseMove: function(event) {
+ _onMouseMove: function (event) {
// Bail out if the target is the same as for the last mousemove
if (event.target === this._lastHovered) {
return;
}
// Only one highlighter can be displayed at a time, hide the currently shown
this._hideCurrent();
@@ -138,53 +138,53 @@ HighlightersOverlay.prototype = {
.then(shown => {
if (shown) {
this.emit("highlighter-shown");
}
});
}
},
- _onMouseLeave: function() {
+ _onMouseLeave: function () {
this._lastHovered = null;
this._hideCurrent();
},
/**
* Is the current hovered node a css transform property value in the rule-view
*
* @param {Object} nodeInfo
* @return {Boolean}
*/
- _isRuleViewTransform: function(nodeInfo) {
+ _isRuleViewTransform: function (nodeInfo) {
let isTransform = nodeInfo.type === VIEW_NODE_VALUE_TYPE &&
nodeInfo.value.property === "transform";
let isEnabled = nodeInfo.value.enabled &&
!nodeInfo.value.overridden &&
!nodeInfo.value.pseudoElement;
return this.isRuleView && isTransform && isEnabled;
},
/**
* Is the current hovered node a css transform property value in the
* computed-view
*
* @param {Object} nodeInfo
* @return {Boolean}
*/
- _isComputedViewTransform: function(nodeInfo) {
+ _isComputedViewTransform: function (nodeInfo) {
let isTransform = nodeInfo.type === VIEW_NODE_VALUE_TYPE &&
nodeInfo.value.property === "transform";
return !this.isRuleView && isTransform;
},
/**
* Hide the currently shown highlighter
*/
- _hideCurrent: function() {
+ _hideCurrent: function () {
if (!this.highlighterShown || !this.highlighters[this.highlighterShown]) {
return;
}
// For some reason, the call to highlighter.hide doesn't always return a
// promise. This causes some tests to fail when trying to install a
// rejection handler on the result of the call. To avoid this, check
// whether the result is truthy before installing the handler.
@@ -197,34 +197,34 @@ HighlightersOverlay.prototype = {
this.emit("highlighter-hidden");
},
/**
* Get a highlighter front given a type. It will only be initialized once
* @param {String} type The highlighter type. One of this.highlighters
* @return a promise that resolves to the highlighter
*/
- _getHighlighter: function(type) {
+ _getHighlighter: function (type) {
let utils = this.highlighterUtils;
if (this.highlighters[type]) {
return promise.resolve(this.highlighters[type]);
}
return utils.getHighlighterByType(type).then(highlighter => {
this.highlighters[type] = highlighter;
return highlighter;
});
},
/**
* Destroy this overlay instance, removing it from the view and destroying
* all initialized highlighters
*/
- destroy: function() {
+ destroy: function () {
this.removeFromView();
for (let type in this.highlighters) {
if (this.highlighters[type]) {
this.highlighters[type].finalize();
this.highlighters[type] = null;
}
}
@@ -261,17 +261,17 @@ TooltipsOverlay.prototype = {
this.cubicBezier.tooltip.isShown() ||
this.filterEditor.tooltip.isShown();
},
/**
* Add the tooltips overlay to the view. This will start tracking mouse
* movements and display tooltips when needed
*/
- addToView: function() {
+ addToView: function () {
if (this._isStarted || this._isDestroyed) {
return;
}
let panelDoc = this.view.inspector.panelDoc;
// Image, fonts, ... preview tooltip
this.previewTooltip = new Tooltip(panelDoc);
@@ -292,17 +292,17 @@ TooltipsOverlay.prototype = {
this._isStarted = true;
},
/**
* Remove the tooltips overlay from the view. This will stop tracking mouse
* movements and displaying tooltips
*/
- removeFromView: function() {
+ removeFromView: function () {
if (!this._isStarted || this._isDestroyed) {
return;
}
this.previewTooltip.stopTogglingOnHover(this.view.element);
this.previewTooltip.destroy();
if (this.colorPicker) {
@@ -326,17 +326,17 @@ TooltipsOverlay.prototype = {
/**
* Given a hovered node info, find out which type of tooltip should be shown,
* if any
*
* @param {Object} nodeInfo
* @return {String} The tooltip type to be shown, or null
*/
- _getTooltipType: function({type, value: prop}) {
+ _getTooltipType: function ({type, value: prop}) {
let tooltipType = null;
let inspector = this.view.inspector;
// Image preview tooltip
if (type === VIEW_NODE_IMAGE_URL_TYPE &&
inspector.hasUrlToImageDataResolver) {
tooltipType = TOOLTIP_IMAGE_TYPE;
}
@@ -355,17 +355,17 @@ TooltipsOverlay.prototype = {
/**
* Executed by the tooltip when the pointer hovers over an element of the
* view. Used to decide whether the tooltip should be shown or not and to
* actually put content in it.
* Checks if the hovered target is a css value we support tooltips for.
*
* @param {DOMNode} target The currently hovered node
*/
- _onPreviewTooltipTargetHover: function(target) {
+ _onPreviewTooltipTargetHover: function (target) {
let nodeInfo = this.view.getNodeInfo(target);
if (!nodeInfo) {
// The hovered node isn't something we care about
return promise.reject(false);
}
let type = this._getTooltipType(nodeInfo);
if (!type) {
@@ -405,17 +405,17 @@ TooltipsOverlay.prototype = {
if (type === TOOLTIP_FONTFAMILY_TYPE) {
return this.previewTooltip.setFontFamilyContent(nodeInfo.value.value,
inspector.selection.nodeFront);
}
return undefined;
},
- _onNewSelection: function() {
+ _onNewSelection: function () {
if (this.previewTooltip) {
this.previewTooltip.hide();
}
if (this.colorPicker) {
this.colorPicker.hide();
}
@@ -430,17 +430,17 @@ TooltipsOverlay.prototype = {
if (this.filterEditor) {
this.filterEditor.hide();
}
},
/**
* Destroy this overlay instance, removing it from the view
*/
- destroy: function() {
+ destroy: function () {
this.removeFromView();
this.view.inspector.selection.off("new-node-front", this._onNewSelection);
this.view = null;
this._isDestroyed = true;
}
};
--- a/devtools/client/inspector/shared/utils.js
+++ b/devtools/client/inspector/shared/utils.js
@@ -113,23 +113,23 @@ exports.advanceValidate = advanceValidat
* The throttling period
* @param {Object} scope
* The scope to use for func
* @return {Function} The throttled function
*/
function throttle(func, wait, scope) {
let timer = null;
- return function() {
+ return function () {
if (timer) {
clearTimeout(timer);
}
let args = arguments;
- timer = setTimeout(function() {
+ timer = setTimeout(function () {
timer = null;
func.apply(scope, args);
}, wait);
};
}
exports.throttle = throttle;
--- a/devtools/client/jsonview/components/headers-panel.js
+++ b/devtools/client/jsonview/components/headers-panel.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+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;
/**
@@ -21,23 +21,23 @@ define(function(require, exports, module
let HeadersPanel = createClass({
propTypes: {
actions: PropTypes.object,
data: PropTypes.object,
},
displayName: "HeadersPanel",
- getInitialState: function() {
+ getInitialState: function () {
return {
data: {}
};
},
- render: function() {
+ render: function () {
let data = this.props.data;
return (
div({className: "headersPanelBox"},
HeadersToolbar({actions: this.props.actions}),
div({className: "panelContent"},
Headers({data: data})
)
@@ -54,21 +54,21 @@ define(function(require, exports, module
propTypes: {
actions: PropTypes.object,
},
displayName: "HeadersToolbar",
// Commands
- onCopy: function(event) {
+ onCopy: function (event) {
this.props.actions.onCopyHeaders();
},
- render: function() {
+ render: function () {
return (
Toolbar({},
ToolbarButton({className: "btn copy", onClick: this.onCopy},
Locale.$STR("jsonViewer.Copy")
)
)
);
},
--- a/devtools/client/jsonview/components/headers.js
+++ b/devtools/client/jsonview/components/headers.js
@@ -1,38 +1,38 @@
/* -*- 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) {
+define(function (require, exports, module) {
const { DOM: dom, createFactory, createClass, PropTypes } = require("devtools/client/shared/vendor/react");
const { div, span, table, tbody, tr, td, code } = 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({
propTypes: {
data: PropTypes.object,
},
displayName: "Headers",
- getInitialState: function() {
+ getInitialState: function () {
return {};
},
- render: function() {
+ render: function () {
let data = this.props.data;
return (
div({className: "netInfoHeadersTable"},
div({className: "netHeadersGroup"},
div({className: "netInfoHeadersGroup"},
span({className: "netHeader twisty"},
Locale.$STR("jsonViewer.responseHeaders")
@@ -66,26 +66,26 @@ define(function(require, exports, module
headers: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
value: PropTypes.string
}))
},
displayName: "HeaderList",
- getInitialState: function() {
+ getInitialState: function () {
return {
headers: []
};
},
- render: function() {
+ render: function () {
let headers = this.props.headers;
- headers.sort(function(a, b) {
+ 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"},
--- a/devtools/client/jsonview/components/json-panel.js
+++ b/devtools/client/jsonview/components/json-panel.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+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;
@@ -32,42 +32,42 @@ define(function(require, exports, module
]),
jsonTextLength: PropTypes.number,
searchFilter: PropTypes.string,
actions: PropTypes.object,
},
displayName: "JsonPanel",
- getInitialState: function() {
+ getInitialState: function () {
return {};
},
- componentDidMount: function() {
+ componentDidMount: function () {
document.addEventListener("keypress", this.onKeyPress, true);
},
- componentWillUnmount: function() {
+ componentWillUnmount: function () {
document.removeEventListener("keypress", this.onKeyPress, true);
},
- onKeyPress: function(e) {
+ onKeyPress: function (e) {
// XXX shortcut for focusing the Filter field (see Bug 1178771).
},
- onFilter: function(object) {
+ onFilter: function (object) {
if (!this.props.searchFilter) {
return true;
}
let json = JSON.stringify(object).toLowerCase();
return json.indexOf(this.props.searchFilter) >= 0;
},
- getExpandedNodes: function(object, path = "", level = 0) {
+ getExpandedNodes: function (object, path = "", level = 0) {
if (typeof object != "object") {
return null;
}
if (level > AUTO_EXPAND_MAX_LEVEL) {
return null;
}
@@ -91,17 +91,17 @@ define(function(require, exports, module
if (typeof member.value == "object" && member.open) {
return null;
}
// Render the value (summary) using Reps library.
return Rep(props);
},
- renderTree: function() {
+ 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.
@@ -116,17 +116,17 @@ define(function(require, exports, module
mode: "tiny",
onFilter: this.onFilter.bind(this),
columns: columns,
renderValue: this.renderValue,
expandedNodes: expandedNodes,
});
},
- render: function() {
+ render: function () {
let content;
let data = this.props.data;
try {
if (typeof data == "object") {
content = this.renderTree();
} else {
content = div({className: "jsonParseError"},
@@ -157,25 +157,25 @@ define(function(require, exports, module
propTypes: {
actions: PropTypes.object,
},
displayName: "JsonToolbar",
// Commands
- onSave: function(event) {
+ onSave: function (event) {
this.props.actions.onSaveJson();
},
- onCopy: function(event) {
+ onCopy: function (event) {
this.props.actions.onCopyJson();
},
- render: function() {
+ 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")
),
--- a/devtools/client/jsonview/components/main-tabbed-area.js
+++ b/devtools/client/jsonview/components/main-tabbed-area.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+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("./reps/tabs"));
/**
@@ -29,30 +29,30 @@ define(function(require, exports, module
PropTypes.string,
PropTypes.object,
PropTypes.array
])
},
displayName: "MainTabbedArea",
- getInitialState: function() {
+ getInitialState: function () {
return {
json: {},
headers: {},
jsonText: this.props.jsonText,
tabActive: this.props.tabActive
};
},
- onTabChanged: function(index) {
+ onTabChanged: function (index) {
this.setState({tabActive: index});
},
- render: function() {
+ render: function () {
return (
Tabs({
tabActive: this.state.tabActive,
onAfterChange: this.onTabChanged},
TabPanel({
className: "json",
title: Locale.$STR("jsonViewer.tab.JSON")},
JsonPanel({
--- a/devtools/client/jsonview/components/reps/tabs.js
+++ b/devtools/client/jsonview/components/reps/tabs.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+define(function (require, exports, module) {
const React = require("devtools/client/shared/vendor/react");
const DOM = React.DOM;
/**
* Renders simple 'tab' widget.
*
* Based on ReactSimpleTabs component
* https://github.com/pedronauck/react-simpletabs
@@ -44,42 +44,42 @@ define(function(require, exports, module
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.element
]).isRequired
},
displayName: "Tabs",
- getDefaultProps: function() {
+ getDefaultProps: function () {
return {
tabActive: 1
};
},
- getInitialState: function() {
+ getInitialState: function () {
return {
tabActive: this.props.tabActive
};
},
- componentDidMount: function() {
+ componentDidMount: function () {
let index = this.state.tabActive;
if (this.props.onMount) {
this.props.onMount(index);
}
},
- componentWillReceiveProps: function(newProps) {
+ componentWillReceiveProps: function (newProps) {
if (newProps.tabActive) {
this.setState({tabActive: newProps.tabActive});
}
},
- setActive: function(index, e) {
+ setActive: function (index, e) {
let onAfterChange = this.props.onAfterChange;
let onBeforeChange = this.props.onBeforeChange;
if (onBeforeChange) {
let cancel = onBeforeChange(index);
if (cancel) {
return;
}
@@ -93,31 +93,31 @@ define(function(require, exports, module
if (onAfterChange) {
onAfterChange(index);
}
});
e.preventDefault();
},
- getMenuItems: function() {
+ getMenuItems: function () {
if (!this.props.children) {
throw new Error("Tabs must contain at least one Panel");
}
if (!Array.isArray(this.props.children)) {
this.props.children = [this.props.children];
}
let menuItems = this.props.children
- .map(function(panel) {
+ .map(function (panel) {
return typeof panel === "function" ? panel() : panel;
- }).filter(function(panel) {
+ }).filter(function (panel) {
return panel;
- }).map(function(panel, index) {
+ }).map(function (panel, index) {
let ref = ("tab-menu-" + (index + 1));
let title = panel.props.title;
let tabClassName = panel.props.className;
let classes = [
"tabs-menu-item",
tabClassName,
this.state.tabActive === (index + 1) && "is-active"
@@ -136,28 +136,28 @@ define(function(require, exports, module
DOM.nav({className: "tabs-navigation"},
DOM.ul({className: "tabs-menu"},
menuItems
)
)
);
},
- getSelectedPanel: function() {
+ getSelectedPanel: function () {
let index = this.state.tabActive - 1;
let panel = this.props.children[index];
return (
DOM.article({ref: "tab-panel", className: "tab-panel"},
panel
)
);
},
- render: function() {
+ render: function () {
let classNames = ["tabs", this.props.className].join(" ");
return (
DOM.div({className: classNames},
this.getMenuItems(),
this.getSelectedPanel()
)
);
@@ -173,17 +173,17 @@ define(function(require, exports, module
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.element
]).isRequired
},
displayName: "Panel",
- render: function() {
+ render: function () {
return DOM.div({},
this.props.children
);
}
});
// Exports from this module
exports.TabPanel = Panel;
--- a/devtools/client/jsonview/components/reps/toolbar.js
+++ b/devtools/client/jsonview/components/reps/toolbar.js
@@ -1,34 +1,34 @@
/* -*- 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) {
+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({
propTypes: {
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.element
])
},
displayName: "Toolbar",
- render: function() {
+ render: function () {
return (
DOM.div({className: "toolbar"},
this.props.children
)
);
}
});
@@ -39,17 +39,17 @@ define(function(require, exports, module
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
children: React.PropTypes.string,
},
displayName: "ToolbarButton",
- render: function() {
+ render: function () {
let props = Object.assign({className: "btn"}, this.props);
return (
DOM.button(props, this.props.children)
);
},
});
// Exports from this module
--- a/devtools/client/jsonview/components/search-box.js
+++ b/devtools/client/jsonview/components/search-box.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+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;
/**
@@ -20,33 +20,33 @@ define(function(require, exports, module
*/
let SearchBox = createClass({
propTypes: {
actions: PropTypes.object,
},
displayName: "SearchBox",
- onSearch: function(event) {
+ 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) {
+ doSearch: function (searchBox) {
this.props.actions.onSearch(searchBox.value);
},
- render: function() {
+ render: function () {
return (
input({className: "searchBox",
placeholder: Locale.$STR("jsonViewer.filterJSON"),
onChange: this.onSearch})
);
},
});
--- a/devtools/client/jsonview/components/text-panel.js
+++ b/devtools/client/jsonview/components/text-panel.js
@@ -1,17 +1,17 @@
/* -*- 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) {
+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.
@@ -19,21 +19,21 @@ define(function(require, exports, module
let TextPanel = createClass({
propTypes: {
actions: PropTypes.object,
data: PropTypes.string
},
displayName: "TextPanel",
- getInitialState: function() {
+ getInitialState: function () {
return {};
},
- render: function() {
+ render: function () {
return (
div({className: "textPanelBox"},
TextToolbar({actions: this.props.actions}),
div({className: "panelContent"},
pre({className: "data"},
this.props.data
)
)
@@ -50,29 +50,29 @@ define(function(require, exports, module
propTypes: {
actions: PropTypes.object,
},
displayName: "TextToolbar",
// Commands
- onPrettify: function(event) {
+ onPrettify: function (event) {
this.props.actions.onPrettify();
},
- onSave: function(event) {
+ onSave: function (event) {
this.props.actions.onSaveJson();
},
- onCopy: function(event) {
+ onCopy: function (event) {
this.props.actions.onCopyJson();
},
- render: function() {
+ render: function () {
return (
Toolbar({},
ToolbarButton({
className: "btn prettyprint",
onClick: this.onPrettify},
Locale.$STR("jsonViewer.PrettyPrint")
),
ToolbarButton({
--- a/devtools/client/jsonview/converter-child.js
+++ b/devtools/client/jsonview/converter-child.js
@@ -62,25 +62,25 @@ let Converter = Class({
* 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) {
+ convert: function (fromStream, fromType, toType, ctx) {
return fromStream;
},
- asyncConvertData: function(fromType, toType, listener, ctx) {
+ asyncConvertData: function (fromType, toType, listener, ctx) {
this.listener = listener;
},
- onDataAvailable: function(request, context, inputStream, offset, count) {
+ 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) {
@@ -89,17 +89,17 @@ let Converter = Class({
if (!bytesRead) {
break;
}
count -= bytesRead;
this.data += str.value;
}
},
- onStartRequest: function(request, context) {
+ 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";
@@ -113,17 +113,17 @@ let Converter = Class({
/**
* 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) {
+ onStopRequest: function (request, context, statusCode) {
let headers = {
response: [],
request: []
};
let win = NetworkHelper.getWindowForRequest(request);
let Locale = {
@@ -144,23 +144,23 @@ let Converter = Class({
defineAs: "postChromeMessage"
});
});
// 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) {
+ visitHeader: function (name, value) {
headers.response.push({name: name, value: value});
}
});
request.visitRequestHeaders({
- visitHeader: function(name, value) {
+ visitHeader: function (name, value) {
headers.request.push({name: name, value: value});
}
});
}
let outputDoc = "";
try {
@@ -192,25 +192,25 @@ let Converter = Class({
this.listener.onDataAvailable(this.channel, context, instream, 0,
instream.available());
this.listener.onStopRequest(this.channel, context, statusCode);
this.listener = null;
},
- htmlEncode: function(t) {
+ htmlEncode: function (t) {
return t !== null ? t.toString()
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/</g, "<")
.replace(/>/g, ">") : "";
},
- toHTML: function(json, headers, title) {
+ 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";
return "<!DOCTYPE html>\n" +
"<html class=\"" + themeClassName + "\">" +
@@ -224,17 +224,17 @@ let Converter = Class({
"<script data-main=\"viewer-config\" src=\"lib/require.js\"></script>" +
"</head><body>" +
"<div id=\"content\"></div>" +
"<div id=\"json\">" + this.htmlEncode(json) + "</div>" +
"<div id=\"headers\">" + this.htmlEncode(headers) + "</div>" +
"</body></html>";
},
- toErrorPage: function(error, data, uri) {
+ toErrorPage: function (error, data, uri) {
// Escape unicode nulls
data = data.replace("\u0000", "\uFFFD");
let errorInfo = error + "";
let output = "<div id=\"error\">" + "error parsing";
if (errorInfo.message) {
output += "<div class=\"errormessage\">" + errorInfo.message + "</div>";
@@ -248,17 +248,17 @@ let Converter = Class({
"<base href=\"" + this.htmlEncode(this.data.url()) + "\">" +
"</head><body>" +
output +
"</body></html>";
},
// Chrome <-> Content communication
- postChromeMessage: function(type, args, objects) {
+ postChromeMessage: function (type, args, objects) {
let value = args;
switch (type) {
case "copy":
Clipboard.set(value, "text");
break;
case "copy-headers":
@@ -266,17 +266,17 @@ let Converter = Class({
break;
case "save":
childProcessMessageManager.sendAsyncMessage(
"devtools:jsonview:save", value);
}
},
- copyHeaders: function(headers) {
+ 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;
}
--- a/devtools/client/jsonview/converter-observer.js
+++ b/devtools/client/jsonview/converter-observer.js
@@ -7,90 +7,90 @@
"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() {
+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() {
+XPCOMUtils.defineLazyGetter(this, "JsonViewService", function () {
const {JsonViewService} = devtools.require("devtools/client/jsonview/converter-child");
return JsonViewService;
});
-XPCOMUtils.defineLazyGetter(this, "JsonViewSniffer", function() {
+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() {
+ 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) {
+ observe: function (subject, topic, data) {
switch (topic) {
case "xpcom-shutdown":
this.onShutdown();
break;
case "nsPref:changed":
this.onPrefChanged();
break;
}
},
- onShutdown: function() {
+ onShutdown: function () {
Services.prefs.removeObserver(JSON_VIEW_PREF, observer);
Services.obs.removeObserver(observer, "xpcom-shutdown");
},
- onPrefChanged: function() {
+ onPrefChanged: function () {
if (this.isEnabled()) {
this.register();
} else {
this.unregister();
}
},
- register: function() {
+ register: function () {
JsonViewSniffer.register();
JsonViewService.register();
},
- unregister: function() {
+ unregister: function () {
JsonViewSniffer.unregister();
JsonViewService.unregister();
},
- isEnabled: function() {
+ 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();
--- a/devtools/client/jsonview/converter-sniffer.js
+++ b/devtools/client/jsonview/converter-sniffer.js
@@ -39,17 +39,17 @@ var Sniffer = Class({
interfaces: [
"nsIContentSniffer",
],
get wrappedJSObject() {
return this;
},
- getMIMETypeFromContent: function(request, data, length) {
+ 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 ==
--- a/devtools/client/jsonview/json-viewer.js
+++ b/devtools/client/jsonview/json-viewer.js
@@ -2,17 +2,17 @@
/* 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 postChromeMessage */
"use strict";
-define(function(require, exports, module) {
+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;
@@ -36,35 +36,35 @@ define(function(require, exports, module
json.remove();
headers.remove();
/**
* Application actions/commands. This list implements all commands
* available for the JSON viewer.
*/
input.actions = {
- onCopyJson: function() {
+ onCopyJson: function () {
let value = input.prettified ? input.jsonPretty : input.jsonText;
postChromeMessage("copy", value);
},
- onSaveJson: function() {
+ onSaveJson: function () {
let value = input.prettified ? input.jsonPretty : input.jsonText;
postChromeMessage("save", value);
},
- onCopyHeaders: function() {
+ onCopyHeaders: function () {
postChromeMessage("copy-headers", input.headers);
},
- onSearch: function(value) {
+ onSearch: function (value) {
theApp.setState({searchFilter: value});
},
- onPrettify: function(data) {
+ 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});
}
--- a/devtools/client/jsonview/main.js
+++ b/devtools/client/jsonview/main.js
@@ -7,54 +7,54 @@
"use strict";
const { Cu } = require("chrome");
const Services = require("Services");
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
-XPCOMUtils.defineLazyGetter(this, "JsonViewService", function() {
+XPCOMUtils.defineLazyGetter(this, "JsonViewService", 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() {
+ 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() {
+ 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) {
+ onSave: function (message) {
let value = message.data;
let file = JsonViewUtils.getTargetFile();
if (file) {
JsonViewUtils.saveToFile(file, value);
}
}
};
--- a/devtools/client/jsonview/test/doc_frame_script.js
+++ b/devtools/client/jsonview/test/doc_frame_script.js
@@ -29,64 +29,64 @@ Services.scriptloader.loadSubScript(
* "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) {
+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) {
+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) {
+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) {
+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) {
+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) {
+ 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;
}
--- a/devtools/client/jsonview/utils.js
+++ b/devtools/client/jsonview/utils.js
@@ -17,17 +17,17 @@ const OPEN_FLAGS = {
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() {
+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;
@@ -38,17 +38,17 @@ exports.getTargetFile = function() {
}
return null;
};
/**
* Save JSON to a file
*/
-exports.saveToFile = function(file, jsonString) {
+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);
@@ -71,24 +71,24 @@ exports.saveToFile = function(file, json
// this closes foStream
converter.close();
};
/**
* Get the current theme from preferences.
*/
-exports.getCurrentTheme = function() {
+exports.getCurrentTheme = function () {
return Services.prefs.getCharPref("devtools.theme");
};
/**
* Export given object into the target window scope.
*/
-exports.exportIntoContentScope = function(win, obj, defineAs) {
+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];
--- a/devtools/client/netmonitor/har/har-automation.js
+++ b/devtools/client/netmonitor/har/har-automation.js
@@ -13,17 +13,17 @@ Cu.import("resource://gre/modules/Task.j
loader.lazyRequireGetter(this, "HarCollector", "devtools/client/netmonitor/har/har-collector", true);
loader.lazyRequireGetter(this, "HarExporter", "devtools/client/netmonitor/har/har-exporter", true);
loader.lazyRequireGetter(this, "HarUtils", "devtools/client/netmonitor/har/har-utils", true);
const prefDomain = "devtools.netmonitor.har.";
// Helper tracer. Should be generic sharable by other modules (bug 1171927)
const trace = {
- log: function(...args) {
+ log: function (...args) {
}
};
/**
* This object is responsible for automated HAR export. It listens
* for Network activity, collects all HTTP data and triggers HAR
* export when the page is loaded.
*
@@ -34,59 +34,59 @@ const trace = {
* preference: devtools.netmonitor.har.defaultLogDir
*
* If the default log directory preference isn't set the following
* directory is used by default: <profile>/har/logs
*/
var HarAutomation = Class({
// Initialization
- initialize: function(toolbox) {
+ initialize: function (toolbox) {
this.toolbox = toolbox;
let target = toolbox.target;
target.makeRemote().then(() => {
this.startMonitoring(target.client, target.form);
});
},
- destroy: function() {
+ destroy: function () {
if (this.collector) {
this.collector.stop();
}
if (this.tabWatcher) {
this.tabWatcher.disconnect();
}
},
// Automation
- startMonitoring: function(client, tabGrip, callback) {
+ startMonitoring: function (client, tabGrip, callback) {
if (!client) {
return;
}
if (!tabGrip) {
return;
}
this.debuggerClient = client;
this.tabClient = this.toolbox.target.activeTab;
this.webConsoleClient = this.toolbox.target.activeConsole;
this.tabWatcher = new TabWatcher(this.toolbox, this);
this.tabWatcher.connect();
},
- pageLoadBegin: function(response) {
+ pageLoadBegin: function (response) {
this.resetCollector();
},
- resetCollector: function() {
+ resetCollector: function () {
if (this.collector) {
this.collector.stop();
}
// A page is about to be loaded, start collecting HTTP
// data from events sent from the backend.
this.collector = new HarCollector({
webConsoleClient: this.webConsoleClient,
@@ -101,27 +101,27 @@ var HarAutomation = Class({
* some requests for additional page resources might be pending,
* so export all after all has been properly received from the backend.
*
* This collector still works and collects any consequent HTTP
* traffic (e.g. XHRs) happening after the page is loaded and
* The additional traffic can be exported by executing
* triggerExport on this object.
*/
- pageLoadDone: function(response) {
+ pageLoadDone: function (response) {
trace.log("HarAutomation.pageLoadDone; ", response);
if (this.collector) {
this.collector.waitForHarLoad().then(collector => {
return this.autoExport();
});
}
},
- autoExport: function() {
+ autoExport: function () {
let autoExport = Services.prefs.getBoolPref(prefDomain +
"enableAutoExportToFile");
if (!autoExport) {
return resolve();
}
// Auto export to file is enabled, so save collected data
@@ -133,39 +133,39 @@ var HarAutomation = Class({
return this.executeExport(data);
},
// Public API
/**
* Export all what is currently collected.
*/
- triggerExport: function(data) {
+ triggerExport: function (data) {
if (!data.fileName) {
data.fileName = Services.prefs.getCharPref(prefDomain +
"defaultFileName");
}
return this.executeExport(data);
},
/**
* Clear currently collected data.
*/
- clear: function() {
+ clear: function () {
this.resetCollector();
},
// HAR Export
/**
* Execute HAR export. This method fetches all data from the
* Network panel (asynchronously) and saves it into a file.
*/
- executeExport: function(data) {
+ executeExport: function (data) {
let items = this.collector.getItems();
let form = this.toolbox.target.form;
let title = form.title || form.url;
let options = {
getString: this.getString.bind(this),
view: this,
items: items,
@@ -193,17 +193,17 @@ var HarAutomation = Class({
return jsonString;
});
},
/**
* Fetches the full text of a string.
*/
- getString: function(stringGrip) {
+ getString: function (stringGrip) {
return this.webConsoleClient.getString(stringGrip);
},
/**
* Extracts any urlencoded form data sections (e.g. "?foo=bar&baz=42") from a
* POST request.
*
* @param object headers
@@ -255,22 +255,22 @@ function TabWatcher(toolbox, listener) {
this.listener = listener;
this.onTabNavigated = this.onTabNavigated.bind(this);
}
TabWatcher.prototype = {
// Connection
- connect: function() {
+ connect: function () {
this.target.on("navigate", this.onTabNavigated);
this.target.on("will-navigate", this.onTabNavigated);
},
- disconnect: function() {
+ disconnect: function () {
if (!this.target) {
return;
}
this.target.off("navigate", this.onTabNavigated);
this.target.off("will-navigate", this.onTabNavigated);
},
@@ -279,17 +279,17 @@ TabWatcher.prototype = {
/**
* Called for each location change in the monitored tab.
*
* @param string aType
* Packet type.
* @param object aPacket
* Packet received from the server.
*/
- onTabNavigated: function(type, packet) {
+ onTabNavigated: function (type, packet) {
switch (type) {
case "will-navigate": {
this.listener.pageLoadBegin(packet);
break;
}
case "navigate": {
this.listener.pageLoadDone(packet);
break;
--- a/devtools/client/netmonitor/har/har-builder.js
+++ b/devtools/client/netmonitor/har/har-builder.js
@@ -34,33 +34,33 @@ const HAR_VERSION = "1.1";
*
* - id {String}: ID of the exported page.
*
* - title {String}: Title of the exported page.
*
* - includeResponseBodies {Boolean}: Set to true to include HTTP response
* bodies in the result data structure.
*/
-var HarBuilder = function(options) {
+var HarBuilder = function (options) {
this._options = options;
this._pageMap = [];
};
HarBuilder.prototype = {
// Public API
/**
* This is the main method used to build the entire result HAR data.
* The process is asynchronous since it can involve additional RDP
* communication (e.g. resolving long strings).
*
* @returns {Promise} A promise that resolves to the HAR object when
* the entire build process is done.
*/
- build: function() {
+ build: function () {
this.promises = [];
// Build basic structure for data.
let log = this.buildLog();
// Build entries.
let items = this._options.items;
for (let i = 0; i < items.length; i++) {
@@ -73,58 +73,58 @@ HarBuilder.prototype = {
let { resolve, promise } = defer();
all(this.promises).then(results => resolve({ log: log }));
return promise;
},
// Helpers
- buildLog: function() {
+ buildLog: function () {
return {
version: HAR_VERSION,
creator: {
name: appInfo.name,
version: appInfo.version
},
browser: {
name: appInfo.name,
version: appInfo.version
},
pages: [],
entries: [],
};
},
- buildPage: function(file) {
+ buildPage: function (file) {
let page = {};
// Page start time is set when the first request is processed
// (see buildEntry)
page.startedDateTime = 0;
page.id = "page_" + this._options.id;
page.title = this._options.title;
return page;
},
- getPage: function(log, file) {
+ getPage: function (log, file) {
let id = this._options.id;
let page = this._pageMap[id];
if (page) {
return page;
}
this._pageMap[id] = page = this.buildPage(file);
log.pages.push(page);
return page;
},
- buildEntry: function(log, file) {
+ buildEntry: function (log, file) {
let page = this.getPage(log, file);
let entry = {};
entry.pageref = page.id;
entry.startedDateTime = dateToJSON(new Date(file.startedMillis));
entry.time = file.endedMillis - file.startedMillis;
entry.request = this.buildRequest(file);
@@ -144,27 +144,27 @@ HarBuilder.prototype = {
if (!page.startedDateTime) {
page.startedDateTime = entry.startedDateTime;
page.pageTimings = this.buildPageTimings(page, file);
}
return entry;
},
- buildPageTimings: function(page, file) {
+ buildPageTimings: function (page, file) {
// Event timing info isn't available
let timings = {
onContentLoad: -1,
onLoad: -1
};
return timings;
},
- buildRequest: function(file) {
+ buildRequest: function (file) {
let request = {
bodySize: 0
};
request.method = file.method;
request.url = file.url;
request.httpVersion = file.httpVersion || "";
@@ -190,33 +190,33 @@ HarBuilder.prototype = {
},
/**
* Fetch all header values from the backend (if necessary) and
* build the result HAR structure.
*
* @param {Object} input Request or response header object.
*/
- buildHeaders: function(input) {
+ buildHeaders: function (input) {
if (!input) {
return [];
}
return this.buildNameValuePairs(input.headers);
},
- buildCookies: function(input) {
+ buildCookies: function (input) {
if (!input) {
return [];
}
return this.buildNameValuePairs(input.cookies);
},
- buildNameValuePairs: function(entries) {
+ buildNameValuePairs: function (entries) {
let result = [];
// HAR requires headers array to be presented, so always
// return at least an empty array.
if (!entries) {
return result;
}
@@ -228,17 +228,17 @@ HarBuilder.prototype = {
value: value
});
});
});
return result;
},
- buildPostData: function(file) {
+ buildPostData: function (file) {
let postData = {
mimeType: findValue(file.requestHeaders.headers, "content-type"),
params: [],
text: ""
};
if (!file.requestPostData) {
return postData;
@@ -269,17 +269,17 @@ HarBuilder.prototype = {
});
});
}
});
return postData;
},
- buildResponse: function(file) {
+ buildResponse: function (file) {
let response = {
status: 0
};
// Arbitrary value if it's aborted to make sure status has a number
if (file.status) {
response.status = parseInt(file.status, 10);
}
@@ -306,17 +306,17 @@ HarBuilder.prototype = {
response.bodySize = (response.status == 304) ? 0 : -1;
} else {
response.bodySize = file.transferredSize;
}
return response;
},
- buildContent: function(file) {
+ buildContent: function (file) {
let content = {
mimeType: file.mimeType,
size: -1
};
let responseContent = file.responseContent;
if (responseContent && responseContent.content) {
content.size = responseContent.content.size;
@@ -339,17 +339,17 @@ HarBuilder.prototype = {
this.fetchData(text).then(value => {
content.text = value;
});
}
return content;
},
- buildCache: function(file) {
+ buildCache: function (file) {
let cache = {};
if (!file.fromCache) {
return cache;
}
// There is no such info yet in the Net panel.
// cache.beforeRequest = {};
@@ -358,28 +358,28 @@ HarBuilder.prototype = {
cache.afterRequest = this.buildCacheEntry(file.cacheEntry);
} else {
cache.afterRequest = null;
}
return cache;
},
- buildCacheEntry: function(cacheEntry) {
+ buildCacheEntry: function (cacheEntry) {
let cache = {};
cache.expires = findValue(cacheEntry, "Expires");
cache.lastAccess = findValue(cacheEntry, "Last Fetched");
cache.eTag = "";
cache.hitCount = findValue(cacheEntry, "Fetch Count");
return cache;
},
- getBlockingEndTime: function(file) {
+ getBlockingEndTime: function (file) {
if (file.resolveStarted && file.connectStarted) {
return file.resolvingTime;
}
if (file.connectStarted) {
return file.connectingTime;
}
@@ -388,17 +388,17 @@ HarBuilder.prototype = {
}
return (file.sendingTime > file.startTime) ?
file.sendingTime : file.waitingForTime;
},
// RDP Helpers
- fetchData: function(string) {
+ fetchData: function (string) {
let promise = this._options.getString(string).then(value => {
return value;
});
// Building HAR is asynchronous and not done till all
// collected promises are resolved.
this.promises.push(promise);
--- a/devtools/client/netmonitor/har/har-collector.js
+++ b/devtools/client/netmonitor/har/har-collector.js
@@ -6,17 +6,17 @@
const { Cu } = require("chrome");
const { defer, all } = require("promise");
const { setTimeout, clearTimeout } = require("sdk/timers");
const { makeInfallible } = require("devtools/shared/DevToolsUtils");
const Services = require("Services");
// Helper tracer. Should be generic sharable by other modules (bug 1171927)
const trace = {
- log: function(...args) {
+ log: function (...args) {
}
};
/**
* This object is responsible for collecting data related to all
* HTTP requests executed by the page (including inner iframes).
*/
function HarCollector(options) {
@@ -36,52 +36,52 @@ function HarCollector(options) {
this.onPageLoadTimeout = this.onPageLoadTimeout.bind(this);
this.clear();
}
HarCollector.prototype = {
// Connection
- start: function() {
+ start: function () {
this.debuggerClient.addListener("networkEvent", this.onNetworkEvent);
this.debuggerClient.addListener("networkEventUpdate",
this.onNetworkEventUpdate);
},
- stop: function() {
+ stop: function () {
this.debuggerClient.removeListener("networkEvent", this.onNetworkEvent);
this.debuggerClient.removeListener("networkEventUpdate",
this.onNetworkEventUpdate);
},
- clear: function() {
+ clear: function () {
// Any pending requests events will be ignored (they turn
// into zombies, since not present in the files array).
this.files = new Map();
this.items = [];
this.firstRequestStart = -1;
this.lastRequestStart = -1;
this.requests = [];
},
- waitForHarLoad: function() {
+ waitForHarLoad: function () {
// There should be yet another timeout e.g.:
// 'devtools.netmonitor.har.pageLoadTimeout'
// that should force export even if page isn't fully loaded.
let deferred = defer();
this.waitForResponses().then(() => {
trace.log("HarCollector.waitForHarLoad; DONE HAR loaded!");
deferred.resolve(this);
});
return deferred.promise;
},
- waitForResponses: function() {
+ waitForResponses: function () {
trace.log("HarCollector.waitForResponses; " + this.requests.length);
// All requests for additional data must be received to have complete
// HTTP info to generate the result HAR file. So, wait for all current
// promises. Note that new promises (requests) can be generated during the
// process of HTTP data collection.
return waitForAll(this.requests).then(() => {
// All responses are received from the backend now. We yet need to
@@ -104,17 +104,17 @@ HarCollector.prototype = {
// Page Loaded Timeout
/**
* The page is loaded when there are no new requests within given period
* of time. The time is set in preferences:
* 'devtools.netmonitor.har.pageLoadedTimeout'
*/
- waitForTimeout: function() {
+ waitForTimeout: function () {
// The auto-export is not done if the timeout is set to zero (or less).
// This is useful in cases where the export is done manually through
// API exposed to the content.
let timeout = Services.prefs.getIntPref(
"devtools.netmonitor.har.pageLoadedTimeout");
trace.log("HarCollector.waitForTimeout; " + timeout);
@@ -125,24 +125,24 @@ HarCollector.prototype = {
return this.pageLoadDeferred.promise;
}
this.pageLoadTimeout = setTimeout(this.onPageLoadTimeout, timeout);
return this.pageLoadDeferred.promise;
},
- onPageLoadTimeout: function() {
+ onPageLoadTimeout: function () {
trace.log("HarCollector.onPageLoadTimeout;");
// Ha, page has been loaded. Resolve the final timeout promise.
this.pageLoadDeferred.resolve();
},
- resetPageLoadTimeout: function() {
+ resetPageLoadTimeout: function () {
// Remove the current timeout.
if (this.pageLoadTimeout) {
trace.log("HarCollector.resetPageLoadTimeout;");
clearTimeout(this.pageLoadTimeout);
this.pageLoadTimeout = null;
}
@@ -150,27 +150,27 @@ HarCollector.prototype = {
if (this.pageLoadDeferred) {
this.pageLoadDeferred.reject();
this.pageLoadDeferred = null;
}
},
// Collected Data
- getFile: function(actorId) {
+ getFile: function (actorId) {
return this.files.get(actorId);
},
- getItems: function() {
+ getItems: function () {
return this.items;
},
// Event Handlers
- onNetworkEvent: function(type, packet) {
+ onNetworkEvent: function (type, packet) {
// Skip events from different console actors.
if (packet.from != this.webConsoleClient.actor) {
return;
}
trace.log("HarCollector.onNetworkEvent; " + type, packet);
let { actor, startedDateTime, method, url, isXHR } = packet.eventActor;
@@ -202,17 +202,17 @@ HarCollector.prototype = {
this.files.set(actor, file);
// Mimic the Net panel data structure
this.items.push({
attachment: file
});
},
- onNetworkEventUpdate: function(type, packet) {
+ onNetworkEventUpdate: function (type, packet) {
let actor = packet.from;
// Skip events from unknown actors (not in the list).
// It can happen when there are zombie requests received after
// the target is closed or multiple tabs are attached through
// one connection (one DebuggerClient object).
let file = this.getFile(packet.from);
if (!file) {
@@ -270,17 +270,17 @@ HarCollector.prototype = {
if (request) {
this.requests.push(request);
}
this.resetPageLoadTimeout();
},
- getData: function(actor, method, callback) {
+ getData: function (actor, method, callback) {
let deferred = defer();
if (!this.webConsoleClient[method]) {
Cu.reportError("HarCollector.getData; ERROR " +
"Unknown method!");
return deferred.resolve();
}
@@ -301,43 +301,43 @@ HarCollector.prototype = {
},
/**
* Handles additional information received for a "requestHeaders" packet.
*
* @param object response
* The message received from the server.
*/
- onRequestHeaders: function(response) {
+ onRequestHeaders: function (response) {
let file = this.getFile(response.from);
file.requestHeaders = response;
this.getLongHeaders(response.headers);
},
/**
* Handles additional information received for a "requestCookies" packet.
*
* @param object response
* The message received from the server.
*/
- onRequestCookies: function(response) {
+ onRequestCookies: function (response) {
let file = this.getFile(response.from);
file.requestCookies = response;
this.getLongHeaders(response.cookies);
},
/**
* Handles additional information received for a "requestPostData" packet.
*
* @param object response
* The message received from the server.
*/
- onRequestPostData: function(response) {
+ onRequestPostData: function (response) {
trace.log("HarCollector.onRequestPostData;", response);
let file = this.getFile(response.from);
file.requestPostData = response;
// Resolve long string
let text = response.postData.text;
if (typeof text == "object") {
@@ -348,43 +348,43 @@ HarCollector.prototype = {
},
/**
* Handles additional information received for a "responseHeaders" packet.
*
* @param object response
* The message received from the server.
*/
- onResponseHeaders: function(response) {
+ onResponseHeaders: function (response) {
let file = this.getFile(response.from);
file.responseHeaders = response;
this.getLongHeaders(response.headers);
},
/**
* Handles additional information received for a "responseCookies" packet.
*
* @param object response
* The message received from the server.
*/
- onResponseCookies: function(response) {
+ onResponseCookies: function (response) {
let file = this.getFile(response.from);
file.responseCookies = response;
this.getLongHeaders(response.cookies);
},
/**
* Handles additional information received for a "responseContent" packet.
*
* @param object response
* The message received from the server.
*/
- onResponseContent: function(response) {
+ onResponseContent: function (response) {
let file = this.getFile(response.from);
file.responseContent = response;
// Resolve long string
let text = response.content.text;
if (typeof text == "object") {
this.getString(text).then(value => {
response.content.text = value;
@@ -393,28 +393,28 @@ HarCollector.prototype = {
},
/**
* Handles additional information received for a "eventTimings" packet.
*
* @param object response
* The message received from the server.
*/
- onEventTimings: function(response) {
+ onEventTimings: function (response) {
let file = this.getFile(response.from);
file.eventTimings = response;
let totalTime = response.totalTime;
file.totalTime = totalTime;
file.endedMillis = file.startedMillis + totalTime;
},
// Helpers
- getLongHeaders: makeInfallible(function(headers) {
+ getLongHeaders: makeInfallible(function (headers) {
for (let header of headers) {
if (typeof header.value == "object") {
this.getString(header.value).then(value => {
header.value = value;
});
}
}
}),
@@ -425,17 +425,17 @@ HarCollector.prototype = {
* @param object | string stringGrip
* The long string grip containing the corresponding actor.
* If you pass in a plain string (by accident or because you're lazy),
* then a promise of the same string is simply returned.
* @return object Promise
* A promise that is resolved when the full string contents
* are available, or rejected if something goes wrong.
*/
- getString: function(stringGrip) {
+ getString: function (stringGrip) {
let promise = this.webConsoleClient.getString(stringGrip);
this.requests.push(promise);
return promise;
}
};
// Helpers
--- a/devtools/client/netmonitor/har/har-exporter.js
+++ b/devtools/client/netmonitor/har/har-exporter.js
@@ -4,26 +4,26 @@
"use strict";
const { Cu, Cc, Ci } = require("chrome");
const Services = require("Services");
const { resolve } = require("promise");
const { HarUtils } = require("./har-utils.js");
const { HarBuilder } = require("./har-builder.js");
-XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function() {
+XPCOMUtils.defineLazyGetter(this, "clipboardHelper", function () {
return Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper);
});
var uid = 1;
// Helper tracer. Should be generic sharable by other modules (bug 1171927)
const trace = {
- log: function(...args) {
+ log: function (...args) {
}
};
/**
* This object represents the main public API designed to access
* Network export logic. Clients, such as the Network panel itself,
* should use this API to export collected HTTP data from the panel.
*/
@@ -62,17 +62,17 @@ const HarExporter = {
*
* - id {String}: ID of the page (used in the HAR file).
*
* - title {String}: Title of the page (used in the HAR file).
*
* - forceExport {Boolean}: The result HAR file is created even if
* there are no HTTP entries.
*/
- save: function(options) {
+ save: function (options) {
// Set default options related to save operation.
options.defaultFileName = Services.prefs.getCharPref(
"devtools.netmonitor.har.defaultFileName");
options.compress = Services.prefs.getBoolPref(
"devtools.netmonitor.har.compress");
// Get target file for exported data. Bail out, if the user
// presses cancel.
@@ -95,26 +95,26 @@ const HarExporter = {
},
/**
* Copy HAR string into the clipboard.
*
* @param Object options
* Configuration object, see save() for detailed description.
*/
- copy: function(options) {
+ copy: function (options) {
return this.fetchHarData(options).then(jsonString => {
clipboardHelper.copyString(jsonString);
return jsonString;
});
},
// Helpers
- fetchHarData: function(options) {
+ fetchHarData: function (options) {
// Generate page ID
options.id = options.id || uid++;
// Set default generic HAR export options.
options.jsonp = options.jsonp ||
Services.prefs.getBoolPref("devtools.netmonitor.har.jsonp");
options.includeResponseBodies = options.includeResponseBodies ||
Services.prefs.getBoolPref(
@@ -152,26 +152,26 @@ const HarExporter = {
},
/**
* Build HAR data object. This object contains all HTTP data
* collected by the Network panel. The process is asynchronous
* since it can involve additional RDP communication (e.g. resolving
* long strings).
*/
- buildHarData: function(options) {
+ buildHarData: function (options) {
// Build HAR object from collected data.
let builder = new HarBuilder(options);
return builder.build();
},
/**
* Build JSON string from the HAR data object.
*/
- stringify: function(har) {
+ stringify: function (har) {
if (!har) {
return null;
}
try {
return JSON.stringify(har, null, " ");
} catch (err) {
Cu.reportError(err);
--- a/devtools/client/netmonitor/har/har-utils.js
+++ b/devtools/client/netmonitor/har/har-utils.js
@@ -1,29 +1,29 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Cu, Ci, Cc, CC } = require("chrome");
-XPCOMUtils.defineLazyGetter(this, "dirService", function() {
+XPCOMUtils.defineLazyGetter(this, "dirService", function () {
return Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties);
});
-XPCOMUtils.defineLazyGetter(this, "ZipWriter", function() {
+XPCOMUtils.defineLazyGetter(this, "ZipWriter", function () {
return CC("@mozilla.org/zipwriter;1", "nsIZipWriter");
});
-XPCOMUtils.defineLazyGetter(this, "LocalFile", function() {
+XPCOMUtils.defineLazyGetter(this, "LocalFile", function () {
return new CC("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath");
});
-XPCOMUtils.defineLazyGetter(this, "getMostRecentBrowserWindow", function() {
+XPCOMUtils.defineLazyGetter(this, "getMostRecentBrowserWindow", function () {
return require("sdk/window/utils").getMostRecentBrowserWindow;
});
const nsIFilePicker = Ci.nsIFilePicker;
const OPEN_FLAGS = {
RDONLY: parseInt("0x01", 16),
WRONLY: parseInt("0x02", 16),
@@ -36,17 +36,17 @@ const OPEN_FLAGS = {
/**
* Helper API for HAR export features.
*/
var HarUtils = {
/**
* Open File Save As dialog and let the user pick the proper file
* location for generated HAR log.
*/
- getTargetFile: function(fileName, jsonp, compress) {
+ getTargetFile: function (fileName, jsonp, compress) {
let browser = getMostRecentBrowserWindow();
let fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(browser, null, nsIFilePicker.modeSave);
fp.appendFilter(
"HTTP Archive Files", "*.har; *.harp; *.json; *.jsonp; *.zip");
fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
fp.filterIndex = 1;
@@ -56,17 +56,17 @@ var HarUtils = {
let rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
return fp.file;
}
return null;
},
- getHarFileName: function(defaultFileName, jsonp, compress) {
+ getHarFileName: function (defaultFileName, jsonp, compress) {
let extension = jsonp ? ".harp" : ".har";
// Read more about toLocaleFormat & format string.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat
let now = new Date();
let name = now.toLocaleFormat(defaultFileName);
name = name.replace(/\:/gm, "-", "");
name = name.replace(/\//gm, "_", "");
@@ -85,17 +85,17 @@ var HarUtils = {
* Save HAR string into a given file. The file might be compressed
* if specified in the options.
*
* @param {File} file Target file where the HAR string (JSON)
* should be stored.
* @param {String} jsonString HAR data (JSON or JSONP)
* @param {Boolean} compress The result file is zipped if set to true.
*/
- saveToFile: function(file, jsonString, compress) {
+ saveToFile: function (file, jsonString, compress) {
let openFlags = OPEN_FLAGS.WRONLY | OPEN_FLAGS.CREATE_FILE |
OPEN_FLAGS.TRUNCATE;
try {
let foStream = Cc["@mozilla.org/network/file-output-stream;1"]
.createInstance(Ci.nsIFileOutputStream);
let permFlags = parseInt("0666", 8);
@@ -161,17 +161,17 @@ var HarUtils = {
// Something went wrong (disk space?) rename the original file back.
file.moveTo(null, originalFileName);
}
return false;
},
- getLocalDirectory: function(path) {
+ getLocalDirectory: function (path) {
let dir;
if (!path) {
dir = dirService.get("ProfD", Ci.nsILocalFile);
dir.append("har");
dir.append("logs");
} else {
dir = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
--- a/devtools/client/netmonitor/har/toolbox-overlay.js
+++ b/devtools/client/netmonitor/har/toolbox-overlay.js
@@ -29,41 +29,41 @@ function ToolboxOverlay(toolbox) {
this.toolbox.on("ready", this.onInit);
this.toolbox.on("destroy", this.onDestroy);
}
ToolboxOverlay.prototype = {
/**
* Executed when the toolbox is ready.
*/
- onInit: function() {
+ onInit: function () {
let autoExport = Services.prefs.getBoolPref(
"devtools.netmonitor.har.enableAutoExportToFile");
if (!autoExport) {
return;
}
this.initAutomation();
},
/**
* Executed when the toolbox is destroyed.
*/
- onDestroy: function(eventId, toolbox) {
+ onDestroy: function (eventId, toolbox) {
this.destroyAutomation();
},
// Automation
- initAutomation: function() {
+ initAutomation: function () {
this.automation = new HarAutomation(this.toolbox);
},
- destroyAutomation: function() {
+ destroyAutomation: function () {
if (this.automation) {
this.automation.destroy();
}
},
};
// Registration
function register(toolbox) {
--- a/devtools/client/netmonitor/netmonitor-controller.js
+++ b/devtools/client/netmonitor/netmonitor-controller.js
@@ -141,17 +141,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
XPCOMUtils.defineLazyServiceGetter(this, "clipboardHelper",
"@mozilla.org/widget/clipboardhelper;1", "nsIClipboardHelper");
XPCOMUtils.defineLazyServiceGetter(this, "DOMParser",
"@mozilla.org/xmlextras/domparser;1", "nsIDOMParser");
Object.defineProperty(this, "NetworkHelper", {
- get: function() {
+ get: function () {
return require("devtools/shared/webconsole/network-helper");
},
configurable: true,
enumerable: true
});
/**
* Object defining the network monitor controller components.
@@ -272,39 +272,39 @@ var NetMonitorController = {
this._connected = false;
return undefined;
}),
/**
* Checks whether the netmonitor connection is active.
* @return boolean
*/
- isConnected: function() {
+ isConnected: function () {
return !!this._connected;
},
/**
* Gets the activity currently performed by the frontend.
* @return number
*/
- getCurrentActivity: function() {
+ getCurrentActivity: function () {
return this._currentActivity || ACTIVITY_TYPE.NONE;
},
/**
* Triggers a specific "activity" to be performed by the frontend.
* This can be, for example, triggering reloads or enabling/disabling cache.
*
* @param number type
* The activity type. See the ACTIVITY_TYPE const.
* @return object
* A promise resolved once the activity finishes and the frontend
* is back into "standby" mode.
*/
- triggerActivity: function(type) {
+ triggerActivity: function (type) {
// Puts the frontend into "standby" (when there's no particular activity).
let standBy = () => {
this._currentActivity = ACTIVITY_TYPE.NONE;
};
// Waits for a series of "navigation start" and "navigation stop" events.
let waitForNavigation = () => {
let deferred = promise.defer();
@@ -373,22 +373,22 @@ var NetMonitorController = {
/**
* Selects the specified request in the waterfall and opens the details view.
*
* @param string requestId
* The actor ID of the request to inspect.
* @return object
* A promise resolved once the task finishes.
*/
- inspectRequest: function(requestId) {
+ inspectRequest: function (requestId) {
// Look for the request in the existing ones or wait for it to appear, if
// the network monitor is still loading.
let deferred = promise.defer();
let request = null;
- let inspector = function() {
+ let inspector = function () {
let predicate = i => i.value === requestId;
request = NetMonitorView.RequestsMenu.getItemForPredicate(predicate);
if (!request) {
// Reset filters so that the request is visible.
NetMonitorView.RequestsMenu.filterOn("all");
request = NetMonitorView.RequestsMenu.getItemForPredicate(predicate);
}
@@ -449,27 +449,27 @@ function TargetEventsHandler() {
TargetEventsHandler.prototype = {
get target() {
return NetMonitorController._target;
},
/**
* Listen for events emitted by the current tab target.
*/
- connect: function() {
+ connect: function () {
dumpn("TargetEventsHandler is connecting...");
this.target.on("close", this._onTabDetached);
this.target.on("navigate", this._onTabNavigated);
this.target.on("will-navigate", this._onTabNavigated);
},
/**
* Remove events emitted by the current tab target.
*/
- disconnect: function() {
+ disconnect: function () {
if (!this.target) {
return;
}
dumpn("TargetEventsHandler is disconnecting...");
this.target.off("close", this._onTabDetached);
this.target.off("navigate", this._onTabNavigated);
this.target.off("will-navigate", this._onTabNavigated);
},
@@ -477,17 +477,17 @@ TargetEventsHandler.prototype = {
/**
* Called for each location change in the monitored tab.
*
* @param string type
* Packet type.
* @param object packet
* Packet received from the server.
*/
- _onTabNavigated: function(type, packet) {
+ _onTabNavigated: function (type, packet) {
switch (type) {
case "will-navigate": {
// Reset UI.
if (!Services.prefs.getBoolPref("devtools.webconsole.persistlog")) {
NetMonitorView.RequestsMenu.reset();
NetMonitorView.Sidebar.toggle(false);
}
// Switch to the default network traffic inspector view.
@@ -505,17 +505,17 @@ TargetEventsHandler.prototype = {
break;
}
}
},
/**
* Called when the monitored tab is closed.
*/
- _onTabDetached: function() {
+ _onTabDetached: function () {
NetMonitorController.shutdownNetMonitor();
}
};
/**
* Functions handling target network events.
*/
function NetworkEventsHandler() {
@@ -557,48 +557,48 @@ NetworkEventsHandler.prototype = {
get firstDocumentLoadTimestamp() {
let marker = this._markers.filter(e => e.name == "document::Load")[0];
return marker ? marker.unixTime / 1000 : -1;
},
/**
* Connect to the current target client.
*/
- connect: function() {
+ connect: function () {
dumpn("NetworkEventsHandler is connecting...");
this.webConsoleClient.on("networkEvent", this._onNetworkEvent);
this.webConsoleClient.on("networkEventUpdate", this._onNetworkEventUpdate);
if (this.timelineFront) {
this.timelineFront.on("doc-loading", this._onDocLoadingMarker);
}
this._displayCachedEvents();
},
/**
* Disconnect from the client.
*/
- disconnect: function() {
+ disconnect: function () {
if (!this.client) {
return;
}
dumpn("NetworkEventsHandler is disconnecting...");
this.webConsoleClient.off("networkEvent", this._onNetworkEvent);
this.webConsoleClient.off("networkEventUpdate", this._onNetworkEventUpdate);
if (this.timelineFront) {
this.timelineFront.off("doc-loading", this._onDocLoadingMarker);
}
},
/**
* Display any network events already in the cache.
*/
- _displayCachedEvents: function() {
+ _displayCachedEvents: function () {
for (let cachedEvent of this.webConsoleClient.getNetworkEvents()) {
// First add the request to the timeline.
this._onNetworkEvent("networkEvent", cachedEvent);
// Then replay any updates already received.
for (let update of cachedEvent.updates) {
this._onNetworkEventUpdate("networkEventUpdate", {
packet: {
updateType: update
@@ -608,30 +608,30 @@ NetworkEventsHandler.prototype = {
}
}
},
/**
* The "DOMContentLoaded" and "Load" events sent by the timeline actor.
* @param object marker
*/
- _onDocLoadingMarker: function(marker) {
+ _onDocLoadingMarker: function (marker) {
window.emit(EVENTS.TIMELINE_EVENT, marker);
this._markers.push(marker);
},
/**
* The "networkEvent" message type handler.
*
* @param string type
* Message type.
* @param object networkInfo
* The network request information.
*/
- _onNetworkEvent: function(type, networkInfo) {
+ _onNetworkEvent: function (type, networkInfo) {
let { actor,
startedDateTime,
request: { method, url },
isXHR,
fromCache,
fromServiceWorker
} = networkInfo;
@@ -646,17 +646,17 @@ NetworkEventsHandler.prototype = {
*
* @param string type
* Message type.
* @param object packet
* The message received from the server.
* @param object networkInfo
* The network request information.
*/
- _onNetworkEventUpdate: function(type, { packet, networkInfo }) {
+ _onNetworkEventUpdate: function (type, { packet, networkInfo }) {
let { actor } = networkInfo;
switch (packet.updateType) {
case "requestHeaders":
this.webConsoleClient.getRequestHeaders(actor, this._onRequestHeaders);
window.emit(EVENTS.UPDATING_REQUEST_HEADERS, actor);
break;
case "requestCookies":
@@ -717,150 +717,150 @@ NetworkEventsHandler.prototype = {
},
/**
* Handles additional information received for a "requestHeaders" packet.
*
* @param object response
* The message received from the server.
*/
- _onRequestHeaders: function(response) {
+ _onRequestHeaders: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
requestHeaders: response
}, () => {
window.emit(EVENTS.RECEIVED_REQUEST_HEADERS, response.from);
});
},
/**
* Handles additional information received for a "requestCookies" packet.
*
* @param object response
* The message received from the server.
*/
- _onRequestCookies: function(response) {
+ _onRequestCookies: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
requestCookies: response
}, () => {
window.emit(EVENTS.RECEIVED_REQUEST_COOKIES, response.from);
});
},
/**
* Handles additional information received for a "requestPostData" packet.
*
* @param object response
* The message received from the server.
*/
- _onRequestPostData: function(response) {
+ _onRequestPostData: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
requestPostData: response
}, () => {
window.emit(EVENTS.RECEIVED_REQUEST_POST_DATA, response.from);
});
},
/**
* Handles additional information received for a "securityInfo" packet.
*
* @param object response
* The message received from the server.
*/
- _onSecurityInfo: function(response) {
+ _onSecurityInfo: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
securityInfo: response.securityInfo
}, () => {
window.emit(EVENTS.RECEIVED_SECURITY_INFO, response.from);
});
},
/**
* Handles additional information received for a "responseHeaders" packet.
*
* @param object response
* The message received from the server.
*/
- _onResponseHeaders: function(response) {
+ _onResponseHeaders: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
responseHeaders: response
}, () => {
window.emit(EVENTS.RECEIVED_RESPONSE_HEADERS, response.from);
});
},
/**
* Handles additional information received for a "responseCookies" packet.
*
* @param object response
* The message received from the server.
*/
- _onResponseCookies: function(response) {
+ _onResponseCookies: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
responseCookies: response
}, () => {
window.emit(EVENTS.RECEIVED_RESPONSE_COOKIES, response.from);
});
},
/**
* Handles additional information received for a "responseContent" packet.
*
* @param object response
* The message received from the server.
*/
- _onResponseContent: function(response) {
+ _onResponseContent: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
responseContent: response
}, () => {
window.emit(EVENTS.RECEIVED_RESPONSE_CONTENT, response.from);
});
},
/**
* Handles additional information received for a "eventTimings" packet.
*
* @param object response
* The message received from the server.
*/
- _onEventTimings: function(response) {
+ _onEventTimings: function (response) {
NetMonitorView.RequestsMenu.updateRequest(response.from, {
eventTimings: response
}, () => {
window.emit(EVENTS.RECEIVED_EVENT_TIMINGS, response.from);
});
},
/**
* Clears all accumulated markers.
*/
- clearMarkers: function() {
+ clearMarkers: function () {
this._markers.length = 0;
},
/**
* Fetches the full text of a LongString.
*
* @param object | string stringGrip
* The long string grip containing the corresponding actor.
* If you pass in a plain string (by accident or because you're lazy),
* then a promise of the same string is simply returned.
* @return object Promise
* A promise that is resolved when the full string contents
* are available, or rejected if something goes wrong.
*/
- getString: function(stringGrip) {
+ getString: function (stringGrip) {
return this.webConsoleClient.getString(stringGrip);
}
};
/**
* Returns true if this is document is in RTL mode.
* @return boolean
*/
-XPCOMUtils.defineLazyGetter(window, "isRTL", function() {
+XPCOMUtils.defineLazyGetter(window, "isRTL", function () {
return window.getComputedStyle(document.documentElement, null)
.direction == "rtl";
});
/**
* Convenient way of emitting events from the panel window.
*/
EventEmitter.decorate(this);
@@ -871,17 +871,17 @@ EventEmitter.decorate(this);
NetMonitorController.TargetEventsHandler = new TargetEventsHandler();
NetMonitorController.NetworkEventsHandler = new NetworkEventsHandler();
/**
* Export some properties to the global scope for easier access.
*/
Object.defineProperties(window, {
"gNetwork": {
- get: function() {
+ get: function () {
return NetMonitorController.NetworkEventsHandler;
},
configurable: true
}
});
/**
* Helper method for debugging.
--- a/devtools/client/netmonitor/netmonitor-view.js
+++ b/devtools/client/netmonitor/netmonitor-view.js
@@ -6,21 +6,21 @@
/* import-globals-from ./netmonitor-controller.js */
/* import-globals-from ../shared/widgets/ViewHelpers.jsm */
/* globals gNetwork, setInterval, setTimeout, clearInterval,
clearTimeout btoa */
"use strict";
var { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-XPCOMUtils.defineLazyGetter(this, "HarExporter", function() {
+XPCOMUtils.defineLazyGetter(this, "HarExporter", function () {
return require("devtools/client/netmonitor/har/har-exporter").HarExporter;
});
-XPCOMUtils.defineLazyGetter(this, "NetworkHelper", function() {
+XPCOMUtils.defineLazyGetter(this, "NetworkHelper", function () {
return require("devtools/shared/webconsole/network-helper");
});
const {ToolSidebar} = require("devtools/client/framework/sidebar");
const {Tooltip} = require("devtools/client/shared/widgets/Tooltip");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
const {LocalizationHelper} = require("devtools/client/shared/l10n");
const {PrefsHelper} = require("devtools/client/shared/prefs");
@@ -128,42 +128,42 @@ const {DeferredTask} = Cu.import("resour
/**
* Object defining the network monitor view components.
*/
var NetMonitorView = {
/**
* Initializes the network monitor view.
*/
- initialize: function() {
+ initialize: function () {
this._initializePanes();
this.Toolbar.initialize();
this.RequestsMenu.initialize();
this.NetworkDetails.initialize();
this.CustomRequest.initialize();
},
/**
* Destroys the network monitor view.
*/
- destroy: function() {
+ destroy: function () {
this._isDestroyed = true;
this.Toolbar.destroy();
this.RequestsMenu.destroy();
this.NetworkDetails.destroy();
this.CustomRequest.destroy();
this._destroyPanes();
},
/**
* Initializes the UI for all the displayed panes.
*/
- _initializePanes: function() {
+ _initializePanes: function () {
dumpn("Initializing the NetMonitorView panes");
this._body = $("#body");
this._detailsPane = $("#details-pane");
this._detailsPaneToggleButton = $("#details-pane-toggle");
this._collapsePaneString = L10N.getStr("collapseDetailsPane");
this._expandPaneString = L10N.getStr("expandDetailsPane");
@@ -213,17 +213,17 @@ var NetMonitorView = {
* An object containing some of the following properties:
* - visible: true if the pane should be shown, false to hide
* - animated: true to display an animation on toggle
* - delayed: true to wait a few cycles before toggle
* - callback: a function to invoke when the toggle finishes
* @param number tabIndex [optional]
* The index of the intended selected tab in the details pane.
*/
- toggleDetailsPane: function(flags, tabIndex) {
+ toggleDetailsPane: function (flags, tabIndex) {
let pane = this._detailsPane;
let button = this._detailsPaneToggleButton;
ViewHelpers.togglePane(flags, pane);
if (flags.visible) {
this._body.removeAttribute("pane-collapsed");
button.removeAttribute("pane-collapsed");
@@ -249,36 +249,36 @@ var NetMonitorView = {
return null;
}
return this._body.selectedPanel.id;
},
/**
* Toggles between the frontend view modes ("Inspector" vs. "Statistics").
*/
- toggleFrontendMode: function() {
+ toggleFrontendMode: function () {
if (this.currentFrontendMode != "network-inspector-view") {
this.showNetworkInspectorView();
} else {
this.showNetworkStatisticsView();
}
},
/**
* Switches to the "Inspector" frontend view mode.
*/
- showNetworkInspectorView: function() {
+ showNetworkInspectorView: function () {
this._body.selectedPanel = $("#network-inspector-view");
this.RequestsMenu._flushWaterfallViews(true);
},
/**
* Switches to the "Statistics" frontend view mode.
*/
- showNetworkStatisticsView: function() {
+ showNetworkStatisticsView: function () {
this._body.selectedPanel = $("#network-statistics-view");
let controller = NetMonitorController;
let requestsView = this.RequestsMenu;
let statisticsView = this.PerformanceStatistics;
Task.spawn(function* () {
statisticsView.displayPlaceholderCharts();
@@ -298,30 +298,30 @@ var NetMonitorView = {
DevToolsUtils.reportException("showNetworkStatisticsView", ex);
}
statisticsView.createPrimedCacheChart(requestsView.items);
statisticsView.createEmptyCacheChart(requestsView.items);
});
},
- reloadPage: function() {
+ reloadPage: function () {
NetMonitorController.triggerActivity(
ACTIVITY_TYPE.RELOAD.WITH_CACHE_DEFAULT);
},
/**
* Lazily initializes and returns a promise for a Editor instance.
*
* @param string id
* The id of the editor placeholder node.
* @return object
* A promise that is resolved when the editor is available.
*/
- editor: function(id) {
+ editor: function (id) {
dumpn("Getting a NetMonitorView editor: " + id);
if (this._editorPromises.has(id)) {
return this._editorPromises.get(id);
}
let deferred = promise.defer();
this._editorPromises.set(id, deferred.promise);
@@ -350,38 +350,38 @@ function ToolbarView() {
this._onTogglePanesPressed = this._onTogglePanesPressed.bind(this);
}
ToolbarView.prototype = {
/**
* Initialization function, called when the debugger is started.
*/
- initialize: function() {
+ initialize: function () {
dumpn("Initializing the ToolbarView");
this._detailsPaneToggleButton = $("#details-pane-toggle");
this._detailsPaneToggleButton.addEventListener("mousedown",
this._onTogglePanesPressed, false);
},
/**
* Destruction function, called when the debugger is closed.
*/
- destroy: function() {
+ destroy: function () {
dumpn("Destroying the ToolbarView");
this._detailsPaneToggleButton.removeEventListener("mousedown",
this._onTogglePanesPressed, false);
},
/**
* Listener handling the toggle button click event.
*/
- _onTogglePanesPressed: function() {
+ _onTogglePanesPressed: function () {
let requestsMenu = NetMonitorView.RequestsMenu;
let selectedIndex = requestsMenu.selectedIndex;
// Make sure there's a selection if the button is pressed, to avoid
// showing an empty network details pane.
if (selectedIndex == -1 && requestsMenu.itemCount) {
requestsMenu.selectedIndex = 0;
} else {
@@ -410,17 +410,17 @@ function RequestsMenuView() {
this._byType = this._byType.bind(this);
this._onSecurityIconClick = this._onSecurityIconClick.bind(this);
}
RequestsMenuView.prototype = Heritage.extend(WidgetMethods, {
/**
* Initialization function, called when the network monitor is started.
*/
- initialize: function() {
+ initialize: function () {
dumpn("Initializing the RequestsMenuView");
this.widget = new SideMenuWidget($("#requests-menu-contents"));
this._splitter = $("#network-inspector-view-splitter");
this._summary = $("#requests-menu-network-summary-button");
this._summary.setAttribute("label", L10N.getStr("networkMenu.empty"));
this.userInputTimer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
@@ -484,17 +484,17 @@ RequestsMenuView.prototype = Heritage.ex
$("#request-menu-context-copy-image-as-data-uri").addEventListener(
"command", this._onContextCopyImageAsDataUriCommand, false);
$("#toggle-raw-headers").addEventListener("click",
this.toggleRawHeadersEvent, false);
window.once("connected", this._onConnect.bind(this));
},
- _onConnect: function() {
+ _onConnect: function () {
$("#requests-menu-reload-notice-button").addEventListener("command",
this._onReloadCommand, false);
if (NetMonitorController.supportsCustomRequest) {
$("#request-menu-context-resend").addEventListener("command",
this._onContextResendCommand, false);
$("#custom-request-send-button").addEventListener("click",
this.sendCustomRequestEvent, false);
@@ -527,17 +527,17 @@ RequestsMenuView.prototype = Heritage.ex
$("#requests-menu-item-template .requests-menu-transferred")
.hidden = true;
}
},
/**
* Destruction function, called when the network monitor is closed.
*/
- destroy: function() {
+ destroy: function () {
dumpn("Destroying the SourcesView");
Prefs.filters = this._activeFilters;
this.widget.removeEventListener("select", this._onSelect, false);
this.widget.removeEventListener("swap", this._onSwap, false);
this._splitter.removeEventListener("mousemove", this._onResize, false);
window.removeEventListener("resize", this._onResize, false);
@@ -588,17 +588,17 @@ RequestsMenuView.prototype = Heritage.ex
this.cloneSelectedRequestEvent, false);
$("#toggle-raw-headers").removeEventListener("click",
this.toggleRawHeadersEvent, false);
},
/**
* Resets this container (removes all the networking information).
*/
- reset: function() {
+ reset: function () {
this.empty();
this._addQueue = [];
this._updateQueue = [];
this._firstRequestStartedMillis = -1;
this._lastRequestEndedMillis = -1;
},
/**
@@ -631,52 +631,52 @@ RequestsMenuView.prototype = Heritage.ex
* Specifies the request's url.
* @param boolean isXHR
* True if this request was initiated via XHR.
* @param boolean fromCache
* Indicates if the result came from the browser cache
* @param boolean fromServiceWorker
* Indicates if the request has been intercepted by a Service Worker
*/
- addRequest: function(id, startedDateTime, method, url, isXHR, fromCache,
+ addRequest: function (id, startedDateTime, method, url, isXHR, fromCache,
fromServiceWorker) {
this._addQueue.push([id, startedDateTime, method, url, isXHR, fromCache,
fromServiceWorker]);
// Lazy updating is disabled in some tests.
if (!this.lazyUpdate) {
return void this._flushRequests();
}
this._flushRequestsTask.arm();
return undefined;
},
/**
* Opens selected item in a new tab.
*/
- openRequestInTab: function() {
+ openRequestInTab: function () {
let win = Services.wm.getMostRecentWindow("navigator:browser");
let selected = this.selectedItem.attachment;
win.openUILinkIn(selected.url, "tab", { relatedToCurrent: true });
},
/**
* Copy the request url from the currently selected item.
*/
- copyUrl: function() {
+ copyUrl: function () {
let selected = this.selectedItem.attachment;
clipboardHelper.copyString(selected.url);
},
/**
* Copy the request url query string parameters from the currently
* selected item.
*/
- copyUrlParams: function() {
+ copyUrlParams: function () {
let selected = this.selectedItem.attachment;
let params = NetworkHelper.nsIURL(selected.url).query.split("&");
let string = params.join(Services.appinfo.OS === "WINNT" ? "\r\n" : "\n");
clipboardHelper.copyString(string);
},
/**
* Extracts any urlencoded form data sections (e.g. "?foo=bar&baz=42") from a
@@ -760,17 +760,17 @@ RequestsMenuView.prototype = Heritage.ex
}
clipboardHelper.copyString(string);
}),
/**
* Copy a cURL command from the currently selected item.
*/
- copyAsCurl: function() {
+ copyAsCurl: function () {
let selected = this.selectedItem.attachment;
Task.spawn(function* () {
// Create a sanitized object for the Curl command generator.
let data = {
url: selected.url,
method: selected.method,
headers: [],
@@ -792,95 +792,95 @@ RequestsMenuView.prototype = Heritage.ex
clipboardHelper.copyString(Curl.generateCommand(data));
});
},
/**
* Copy HAR from the network panel content to the clipboard.
*/
- copyAllAsHar: function() {
+ copyAllAsHar: function () {
let options = this.getDefaultHarOptions();
return HarExporter.copy(options);
},
/**
* Save HAR from the network panel content to a file.
*/
- saveAllAsHar: function() {
+ saveAllAsHar: function () {
let options = this.getDefaultHarOptions();
return HarExporter.save(options);
},
- getDefaultHarOptions: function() {
+ getDefaultHarOptions: function () {
let form = NetMonitorController._target.form;
let title = form.title || form.url;
return {
getString: gNetwork.getString.bind(gNetwork),
view: this,
items: NetMonitorView.RequestsMenu.items,
title: title
};
},
/**
* Copy the raw request headers from the currently selected item.
*/
- copyRequestHeaders: function() {
+ copyRequestHeaders: function () {
let selected = this.selectedItem.attachment;
let rawHeaders = selected.requestHeaders.rawHeaders.trim();
if (Services.appinfo.OS !== "WINNT") {
rawHeaders = rawHeaders.replace(/\r/g, "");
}
clipboardHelper.copyString(rawHeaders);
},
/**
* Copy the raw response headers from the currently selected item.
*/
- copyResponseHeaders: function() {
+ copyResponseHeaders: function () {
let selected = this.selectedItem.attachment;
let rawHeaders = selected.responseHeaders.rawHeaders.trim();
if (Services.appinfo.OS !== "WINNT") {
rawHeaders = rawHeaders.replace(/\r/g, "");
}
clipboardHelper.copyString(rawHeaders);
},
/**
* Copy image as data uri.
*/
- copyImageAsDataUri: function() {
+ copyImageAsDataUri: function () {
let selected = this.selectedItem.attachment;
let { mimeType, text, encoding } = selected.responseContent.content;
gNetwork.getString(text).then(string => {
let data = formDataURI(mimeType, encoding, string);
clipboardHelper.copyString(data);
});
},
/**
* Copy response data as a string.
*/
- copyResponse: function() {
+ copyResponse: function () {
let selected = this.selectedItem.attachment;
let text = selected.responseContent.content.text;
gNetwork.getString(text).then(string => {
clipboardHelper.copyString(string);
});
},
/**
* Create a new custom request form populated with the data from
* the currently selected request.
*/
- cloneSelectedRequest: function() {
+ cloneSelectedRequest: function () {
let selected = this.selectedItem.attachment;
// Create the element node for the network request item.
let menuView = this._createMenuView(selected.method, selected.url);
// Append a network request item to this container.
let newItem = this.push([menuView], {
attachment: Object.create(selected, {
@@ -890,17 +890,17 @@ RequestsMenuView.prototype = Heritage.ex
// Immediately switch to new request pane.
this.selectedItem = newItem;
},
/**
* Send a new HTTP request using the data in the custom request form.
*/
- sendCustomRequest: function() {
+ sendCustomRequest: function () {
let selected = this.selectedItem.attachment;
let data = {
url: selected.url,
method: selected.method,
httpVersion: selected.httpVersion,
};
if (selected.requestHeaders) {
@@ -916,25 +916,25 @@ RequestsMenuView.prototype = Heritage.ex
});
this.closeCustomRequest();
},
/**
* Remove the currently selected custom request.
*/
- closeCustomRequest: function() {
+ closeCustomRequest: function () {
this.remove(this.selectedItem);
NetMonitorView.Sidebar.toggle(false);
},
/**
* Shows raw request/response headers in textboxes.
*/
- toggleRawHeaders: function() {
+ toggleRawHeaders: function () {
let requestTextarea = $("#raw-request-headers-textarea");
let responseTextare = $("#raw-response-headers-textarea");
let rawHeadersHidden = $("#raw-headers").getAttribute("hidden");
if (rawHeadersHidden) {
let selected = this.selectedItem.attachment;
let selectedRequestHeaders = selected.requestHeaders.headers;
let selectedResponseHeaders = selected.responseHeaders.headers;
@@ -946,47 +946,47 @@ RequestsMenuView.prototype = Heritage.ex
responseTextare.value = null;
$("#raw-headers").hidden = true;
}
},
/**
* Handles the timeout on the freetext filter textbox
*/
- requestsFreetextFilterEvent: function() {
+ requestsFreetextFilterEvent: function () {
this.userInputTimer.cancel();
this._currentFreetextFilter = this.freetextFilterBox.value || "";
if (this._currentFreetextFilter.length === 0) {
this.freetextFilterBox.removeAttribute("filled");
} else {
this.freetextFilterBox.setAttribute("filled", true);
}
this.userInputTimer.initWithCallback(this.reFilterRequests,
FREETEXT_FILTER_SEARCH_DELAY, Ci.nsITimer.TYPE_ONE_SHOT);
},
/**
* Refreshes the view contents with the newly selected filters
*/
- reFilterRequests: function() {
+ reFilterRequests: function () {
this.filterContents(this._filterPredicate);
this.refreshSummary();
this.refreshZebra();
},
/**
* Filters all network requests in this container by a specified type.
*
* @param string type
* Either "all", "html", "css", "js", "xhr", "fonts", "images", "media"
* "flash", "ws" or "other".
*/
- filterOn: function(type = "all") {
+ filterOn: function (type = "all") {
if (type === "all") {
// The filter "all" is special as it doesn't toggle.
// - If some filters are selected and 'all' is clicked, the previously
// selected filters will be disabled and 'all' is the only active one.
// - If 'all' is already selected, do nothing.
if (this._activeFilters.indexOf("all") !== -1) {
return;
}
@@ -1006,30 +1006,30 @@ RequestsMenuView.prototype = Heritage.ex
},
/**
* Same as `filterOn`, except that it only allows a single type exclusively.
*
* @param string type
* @see RequestsMenuView.prototype.fitlerOn
*/
- filterOnlyOn: function(type = "all") {
+ filterOnlyOn: function (type = "all") {
this._activeFilters.slice().forEach(this._disableFilter, this);
this.filterOn(type);
},
/**
* Disables the given filter, its button and toggles 'all' on if the filter to
* be disabled is the last one active.
*
* @param string type
* Either "all", "html", "css", "js", "xhr", "fonts", "images", "media"
* "flash", "ws" or "other".
*/
- _disableFilter: function(type) {
+ _disableFilter: function (type) {
// Remove the filter from list of active filters.
this._activeFilters.splice(this._activeFilters.indexOf(type), 1);
// Remove the checked status from the filter.
let target = $("#requests-menu-filter-" + type + "-button");
target.removeAttribute("checked");
// Check if the filter disabled was the last one. If so, toggle all on.
@@ -1041,17 +1041,17 @@ RequestsMenuView.prototype = Heritage.ex
/**
* Enables the given filter, its button and toggles 'all' off if the filter to
* be enabled is the first one active.
*
* @param string type
* Either "all", "html", "css", "js", "xhr", "fonts", "images", "media"
* "flash", "ws" or "other".
*/
- _enableFilter: function(type) {
+ _enableFilter: function (type) {
// Make sure this is a valid filter type.
if (Object.keys(this._allFilterPredicates).indexOf(type) == -1) {
return;
}
// Add the filter to the list of active filters.
this._activeFilters.push(type);
@@ -1104,17 +1104,17 @@ RequestsMenuView.prototype = Heritage.ex
/**
* Sorts all network requests in this container by a specified detail.
*
* @param string type
* Either "status", "method", "file", "domain", "type", "transferred",
* "size" or "waterfall".
*/
- sortBy: function(type = "waterfall") {
+ sortBy: function (type = "waterfall") {
let target = $("#requests-menu-" + type + "-button");
let headers = document.querySelectorAll(".requests-menu-header-button");
for (let header of headers) {
if (header != target) {
header.removeAttribute("sorted");
header.removeAttribute("tooltiptext");
header.parentNode.removeAttribute("active");
@@ -1198,17 +1198,17 @@ RequestsMenuView.prototype = Heritage.ex
this.refreshSummary();
this.refreshZebra();
},
/**
* Removes all network requests and closes the sidebar if open.
*/
- clear: function() {
+ clear: function () {
NetMonitorController.NetworkEventsHandler.clearMarkers();
NetMonitorView.Sidebar.toggle(false);
$("#details-pane-toggle").disabled = true;
$("#requests-menu-empty-notice").hidden = false;
this.empty();
this.refreshSummary();
@@ -1217,70 +1217,70 @@ RequestsMenuView.prototype = Heritage.ex
/**
* Predicates used when filtering items.
*
* @param object item
* The filtered item.
* @return boolean
* True if the item should be visible, false otherwise.
*/
- isHtml: function({ attachment: { mimeType } }) {
+ isHtml: function ({ attachment: { mimeType } }) {
return mimeType && mimeType.includes("/html");
},
- isCss: function({ attachment: { mimeType } }) {
+ isCss: function ({ attachment: { mimeType } }) {
return mimeType && mimeType.includes("/css");
},
- isJs: function({ attachment: { mimeType } }) {
+ isJs: function ({ attachment: { mimeType } }) {
return mimeType && (
mimeType.includes("/ecmascript") ||
mimeType.includes("/javascript") ||
mimeType.includes("/x-javascript"));
},
- isXHR: function(item) {
+ isXHR: function (item) {
// Show the request it is XHR, except
// if the request is a WS upgrade
return item.attachment.isXHR && !this.isWS(item);
},
- isFont: function({ attachment: { url, mimeType } }) {
+ isFont: function ({ attachment: { url, mimeType } }) {
// Fonts are a mess.
return (mimeType && (
mimeType.includes("font/") ||
mimeType.includes("/font"))) ||
url.includes(".eot") ||
url.includes(".ttf") ||
url.includes(".otf") ||
url.includes(".woff");
},
- isImage: function({ attachment: { mimeType } }) {
+ isImage: function ({ attachment: { mimeType } }) {
return mimeType && mimeType.includes("image/");
},
- isMedia: function({ attachment: { mimeType } }) {
+ isMedia: function ({ attachment: { mimeType } }) {
// Not including images.
return mimeType && (
mimeType.includes("audio/") ||
mimeType.includes("video/") ||
mimeType.includes("model/"));
},
- isFlash: function({ attachment: { url, mimeType } }) {
+ isFlash: function ({ attachment: { url, mimeType } }) {
// Flash is a mess.
return (mimeType && (
mimeType.includes("/x-flv") ||
mimeType.includes("/x-shockwave-flash"))) ||
url.includes(".swf") ||
url.includes(".flv");
},
- isWS: function({ attachment: { requestHeaders, responseHeaders } }) {
+ isWS: function ({ attachment: { requestHeaders, responseHeaders } }) {
// Detect a websocket upgrade if request has an Upgrade header
// with value 'websocket'
if (!requestHeaders || !Array.isArray(requestHeaders.headers)) {
return false;
}
// Find the 'upgrade' header.
@@ -1302,29 +1302,29 @@ RequestsMenuView.prototype = Heritage.ex
// 'websocket'.
if (!upgradeHeader || upgradeHeader.value != "websocket") {
return false;
}
return true;
},
- isOther: function(e) {
+ isOther: function (e) {
return !this.isHtml(e) &&
!this.isCss(e) &&
!this.isJs(e) &&
!this.isXHR(e) &&
!this.isFont(e) &&
!this.isImage(e) &&
!this.isMedia(e) &&
!this.isFlash(e) &&
!this.isWS(e);
},
- isFreetextMatch: function({ attachment: { url } }, text) {
+ isFreetextMatch: function ({ attachment: { url } }, text) {
let lowerCaseUrl = url.toLowerCase();
let lowerCaseText = text.toLowerCase();
let textLength = text.length;
// Support negative filtering
if (text.startsWith("-") && textLength > 1) {
lowerCaseText = lowerCaseText.substring(1, textLength);
return !lowerCaseUrl.includes(lowerCaseText);
}
@@ -1340,71 +1340,71 @@ RequestsMenuView.prototype = Heritage.ex
* The first item used in the comparison.
* @param object aSecond
* The second item used in the comparison.
* @return number
* -1 to sort aFirst to a lower index than aSecond
* 0 to leave aFirst and aSecond unchanged with respect to each other
* 1 to sort aSecond to a lower index than aFirst
*/
- _byTiming: function({ attachment: first }, { attachment: second }) {
+ _byTiming: function ({ attachment: first }, { attachment: second }) {
return first.startedMillis > second.startedMillis;
},
- _byStatus: function({ attachment: first }, { attachment: second }) {
+ _byStatus: function ({ attachment: first }, { attachment: second }) {
return first.status == second.status
? first.startedMillis > second.startedMillis
: first.status > second.status;
},
- _byMethod: function({ attachment: first }, { attachment: second }) {
+ _byMethod: function ({ attachment: first }, { attachment: second }) {
return first.method == second.method
? first.startedMillis > second.startedMillis
: first.method > second.method;
},
- _byFile: function({ attachment: first }, { attachment: second }) {
+ _byFile: function ({ attachment: first }, { attachment: second }) {
let firstUrl = this._getUriNameWithQuery(first.url).toLowerCase();
let secondUrl = this._getUriNameWithQuery(second.url).toLowerCase();
return firstUrl == secondUrl
? first.startedMillis > second.startedMillis
: firstUrl > secondUrl;
},
- _byDomain: function({ attachment: first }, { attachment: second }) {
+ _byDomain: function ({ attachment: first }, { attachment: second }) {
let firstDomain = this._getUriHostPort(first.url).toLowerCase();
let secondDomain = this._getUriHostPort(second.url).toLowerCase();
return firstDomain == secondDomain
? first.startedMillis > second.startedMillis
: firstDomain > secondDomain;
},
- _byType: function({ attachment: first }, { attachment: second }) {
+ _byType: function ({ attachment: first }, { attachment: second }) {
let firstType = this._getAbbreviatedMimeType(first.mimeType).toLowerCase();
let secondType = this._getAbbreviatedMimeType(second.mimeType)
.toLowerCase();
return firstType == secondType
? first.startedMillis > second.startedMillis
: firstType > secondType;
},
- _byTransferred: function({ attachment: first }, { attachment: second }) {
+ _byTransferred: function ({ attachment: first }, { attachment: second }) {
return first.transferredSize > second.transferredSize;
},
- _bySize: function({ attachment: first }, { attachment: second }) {
+ _bySize: function ({ attachment: first }, { attachment: second }) {
return first.contentSize > second.contentSize;
},
/**
* Refreshes the status displayed in this container's footer, providing
* concise information about all requests.
*/
- refreshSummary: function() {
+ refreshSummary: function () {
let visibleItems = this.visibleItems;
let visibleRequestsCount = visibleItems.length;
if (!visibleRequestsCount) {
this._summary.setAttribute("label", L10N.getStr("networkMenu.empty"));
return;
}
let totalBytes = this._getTotalBytesOfRequests(visibleItems);
@@ -1423,17 +1423,17 @@ RequestsMenuView.prototype = Heritage.ex
.replace("#3", L10N.numberWithDecimals((totalMillis || 0) / 1000,
REQUEST_TIME_DECIMALS))
);
},
/**
* Adds odd/even attributes to all the visible items in this container.
*/
- refreshZebra: function() {
+ refreshZebra: function () {
let visibleItems = this.visibleItems;
for (let i = 0, len = visibleItems.length; i < len; i++) {
let requestItem = visibleItems[i];
let requestTarget = requestItem.target;
if (i % 2 == 0) {
requestTarget.setAttribute("even", "");
@@ -1446,61 +1446,61 @@ RequestsMenuView.prototype = Heritage.ex
},
/**
* Refreshes the toggling anchor for the specified item's tooltip.
*
* @param object item
* The network request item in this container.
*/
- refreshTooltip: function(item) {
+ refreshTooltip: function (item) {
let tooltip = item.attachment.tooltip;
tooltip.hide();
tooltip.startTogglingOnHover(item.target, this._onHover);
tooltip.defaultPosition = REQUESTS_TOOLTIP_POSITION;
},
/**
* Attaches security icon click listener for the given request menu item.
*
* @param object item
* The network request item to attach the listener to.
*/
- attachSecurityIconClickListener: function({ target }) {
+ attachSecurityIconClickListener: function ({ target }) {
let icon = $(".requests-security-state-icon", target);
icon.addEventListener("click", this._onSecurityIconClick);
},
/**
* Schedules adding additional information to a network request.
*
* @param string id
* An identifier coming from the network monitor controller.
* @param object data
* An object containing several { key: value } tuples of network info.
* Supported keys are "httpVersion", "status", "statusText" etc.
* @param function callback
* A function to call once the request has been updated in the view.
*/
- updateRequest: function(id, data, callback) {
+ updateRequest: function (id, data, callback) {
this._updateQueue.push([id, data, callback]);
// Lazy updating is disabled in some tests.
if (!this.lazyUpdate) {
return void this._flushRequests();
}
this._flushRequestsTask.arm();
return undefined;
},
/**
* Starts adding all queued additional information about network requests.
*/
- _flushRequests: function() {
+ _flushRequests: function () {
// Prevent displaying any updates received after the target closed.
if (NetMonitorView._isDestroyed) {
return;
}
let widget = NetMonitorView.RequestsMenu.widget;
let isScrolledToBottom = widget.isScrolledToBottom();
@@ -1746,17 +1746,17 @@ RequestsMenuView.prototype = Heritage.ex
*
* @param string method
* Specifies the request method (e.g. "GET", "POST", etc.)
* @param string url
* Specifies the request's url.
* @return nsIDOMNode
* The network request view.
*/
- _createMenuView: function(method, url) {
+ _createMenuView: function (method, url) {
let template = $("#requests-menu-item-template");
let fragment = document.createDocumentFragment();
this.updateMenuView(template, "method", method);
this.updateMenuView(template, "url", url);
// Flatten the DOM by removing one redundant box (the template container).
for (let node of template.childNodes) {
@@ -1944,17 +1944,17 @@ RequestsMenuView.prototype = Heritage.ex
* @param object item
* The network request item in this container.
* @param object timings
* An object containing timing information.
* @param boolean fromCache
* Indicates if the result came from the browser cache or
* a service worker
*/
- _createWaterfallView: function(item, timings, fromCache) {
+ _createWaterfallView: function (item, timings, fromCache) {
let { target } = item;
let sections = ["dns", "connect", "send", "wait", "receive"];
// Skipping "blocked" because it doesn't work yet.
let timingsNode = $(".requests-menu-timings", target);
let timingsTotal = $(".requests-menu-timings-total", timingsNode);
if (fromCache) {
@@ -1978,17 +1978,17 @@ RequestsMenuView.prototype = Heritage.ex
},
/**
* Rescales and redraws all the waterfall views in this container.
*
* @param boolean reset
* True if this container's width was changed.
*/
- _flushWaterfallViews: function(reset) {
+ _flushWaterfallViews: function (reset) {
// Don't paint things while the waterfall view isn't even visible,
// or there are no items added to this container.
if (NetMonitorView.currentFrontendMode !=
"network-inspector-view" || !this.itemCount) {
return;
}
// To avoid expensive operations like getBoundingClientRect() and
@@ -2036,17 +2036,17 @@ RequestsMenuView.prototype = Heritage.ex
},
/**
* Creates the labels displayed on the waterfall header in this container.
*
* @param number scale
* The current waterfall scale.
*/
- _showWaterfallDivisionLabels: function(scale) {
+ _showWaterfallDivisionLabels: function (scale) {
let container = $("#requests-menu-waterfall-label-wrapper");
let availableWidth = this._waterfallWidth - REQUESTS_WATERFALL_SAFE_BOUNDS;
// Nuke all existing labels.
while (container.hasChildNodes()) {
container.firstChild.remove();
}
@@ -2109,17 +2109,17 @@ RequestsMenuView.prototype = Heritage.ex
},
/**
* Creates the background displayed on each waterfall view in this container.
*
* @param number scale
* The current waterfall scale.
*/
- _drawWaterfallBackground: function(scale) {
+ _drawWaterfallBackground: function (scale) {
if (!this._canvas || !this._ctx) {
this._canvas = document.createElementNS(HTML_NS, "canvas");
this._ctx = this._canvas.getContext("2d");
}
let canvas = this._canvas;
let ctx = this._ctx;
// Nuke the context.
@@ -2184,30 +2184,30 @@ RequestsMenuView.prototype = Heritage.ex
pixelArray.set(view8bit);
ctx.putImageData(imageData, 0, 0);
document.mozSetImageElement("waterfall-background", canvas);
},
/**
* The selection listener for this container.
*/
- _onSelect: function({ detail: item }) {
+ _onSelect: function ({ detail: item }) {
if (item) {
NetMonitorView.Sidebar.populate(item.attachment);
NetMonitorView.Sidebar.toggle(true);
} else {
NetMonitorView.Sidebar.toggle(false);
}
},
/**
* The swap listener for this container.
* Called when two items switch places, when the contents are sorted.
*/
- _onSwap: function({ detail: [firstItem, secondItem] }) {
+ _onSwap: function ({ detail: [firstItem, secondItem] }) {
// Sorting will create new anchor nodes for all the swapped request items
// in this container, so it's necessary to refresh the Tooltip instances.
this.refreshTooltip(firstItem);
this.refreshTooltip(secondItem);
// Reattach click listener to the security icons
this.attachSecurityIconClickListener(firstItem);
this.attachSecurityIconClickListener(secondItem);
@@ -2217,17 +2217,17 @@ RequestsMenuView.prototype = Heritage.ex
* The predicate used when deciding whether a popup should be shown
* over a request item or not.
*
* @param nsIDOMNode target
* The element node currently being hovered.
* @param object tooltip
* The current tooltip instance.
*/
- _onHover: function(target, tooltip) {
+ _onHover: function (target, tooltip) {
let requestItem = this.getItemForElement(target);
if (!requestItem || !requestItem.attachment.responseContent) {
return null;
}
let hovered = requestItem.attachment;
let { mimeType, text, encoding } = hovered.responseContent.content;
@@ -2247,37 +2247,37 @@ RequestsMenuView.prototype = Heritage.ex
}
return undefined;
},
/**
* A handler that opens the security tab in the details view if secure or
* broken security indicator is clicked.
*/
- _onSecurityIconClick: function(e) {
+ _onSecurityIconClick: function (e) {
let state = this.selectedItem.attachment.securityState;
if (state !== "insecure") {
// Choose the security tab.
NetMonitorView.NetworkDetails.widget.selectedIndex = 5;
}
},
/**
* The resize listener for this container's window.
*/
- _onResize: function(e) {
+ _onResize: function (e) {
// Allow requests to settle down first.
setNamedTimeout("resize-events",
RESIZE_REFRESH_RATE, () => this._flushWaterfallViews(true));
},
/**
* Handle the context menu opening. Hide items if no request is selected.
*/
- _onContextShowing: function() {
+ _onContextShowing: function () {
let selectedItem = this.selectedItem;
let resendElement = $("#request-menu-context-resend");
resendElement.hidden = !NetMonitorController.supportsCustomRequest ||
!selectedItem || selectedItem.attachment.isCustom;
let copyUrlElement = $("#request-menu-context-copy-url");
copyUrlElement.hidden = !selectedItem;
@@ -2333,85 +2333,85 @@ RequestsMenuView.prototype = Heritage.ex
/**
* Checks if the specified unix time is the first one to be known of,
* and saves it if so.
*
* @param number unixTime
* The milliseconds to check and save.
*/
- _registerFirstRequestStart: function(unixTime) {
+ _registerFirstRequestStart: function (unixTime) {
if (this._firstRequestStartedMillis == -1) {
this._firstRequestStartedMillis = unixTime;
}
},
/**
* Checks if the specified unix time is the last one to be known of,
* and saves it if so.
*
* @param number unixTime
* The milliseconds to check and save.
*/
- _registerLastRequestEnd: function(unixTime) {
+ _registerLastRequestEnd: function (unixTime) {
if (this._lastRequestEndedMillis < unixTime) {
this._lastRequestEndedMillis = unixTime;
}
},
/**
* Helpers for getting details about an nsIURL.
*
* @param nsIURL | string url
* @return string
*/
- _getUriNameWithQuery: function(url) {
+ _getUriNameWithQuery: function (url) {
if (!(url instanceof Ci.nsIURL)) {
url = NetworkHelper.nsIURL(url);
}
let name = NetworkHelper.convertToUnicode(
unescape(url.fileName || url.filePath || "/"));
let query = NetworkHelper.convertToUnicode(unescape(url.query));
return name + (query ? "?" + query : "");
},
- _getUriHostPort: function(url) {
+ _getUriHostPort: function (url) {
if (!(url instanceof Ci.nsIURL)) {
url = NetworkHelper.nsIURL(url);
}
return NetworkHelper.convertToUnicode(unescape(url.hostPort));
},
- _getUriHost: function(url) {
+ _getUriHost: function (url) {
return this._getUriHostPort(url).replace(/:\d+$/, "");
},
/**
* Helper for getting an abbreviated string for a mime type.
*
* @param string mimeType
* @return string
*/
- _getAbbreviatedMimeType: function(mimeType) {
+ _getAbbreviatedMimeType: function (mimeType) {
if (!mimeType) {
return "";
}
return (mimeType.split(";")[0].split("/")[1] || "").split("+")[0];
},
/**
* Gets the total number of bytes representing the cumulated content size of
* a set of requests. Returns 0 for an empty set.
*
* @param array itemsArray
* @return number
*/
- _getTotalBytesOfRequests: function(itemsArray) {
+ _getTotalBytesOfRequests: function (itemsArray) {
if (!itemsArray.length) {
return 0;
}
let result = 0;
itemsArray.forEach(item => {
let size = item.attachment.contentSize;
result += (typeof size == "number") ? size : 0;
@@ -2422,33 +2422,33 @@ RequestsMenuView.prototype = Heritage.ex
/**
* Gets the oldest (first performed) request in a set. Returns null for an
* empty set.
*
* @param array itemsArray
* @return object
*/
- _getOldestRequest: function(itemsArray) {
+ _getOldestRequest: function (itemsArray) {
if (!itemsArray.length) {
return null;
}
return itemsArray.reduce((prev, curr) =>
prev.attachment.startedMillis < curr.attachment.startedMillis ?
prev : curr);
},
/**
* Gets the newest (latest performed) request in a set. Returns null for an
* empty set.
*
* @param array itemsArray
* @return object
*/
- _getNewestRequest: function(itemsArray) {
+ _getNewestRequest: function (itemsArray) {
if (!itemsArray.length) {
return null;
}
return itemsArray.reduce((prev, curr) =>
prev.attachment.startedMillis > curr.attachment.startedMillis ?
prev : curr);
},
@@ -2496,17 +2496,17 @@ function SidebarView() {
SidebarView.prototype = {
/**
* Sets this view hidden or visible. It's visible by default.
*
* @param boolean visibleFlag
* Specifies the intended visibility.
*/
- toggle: function(visibleFlag) {
+ toggle: function (visibleFlag) {
NetMonitorView.toggleDetailsPane({ visible: visibleFlag });
NetMonitorView.RequestsMenu._flushWaterfallViews(true);
},
/**
* Populates this view with the specified data.
*
* @param object data
@@ -2533,28 +2533,28 @@ SidebarView.prototype = {
function CustomRequestView() {
dumpn("CustomRequestView was instantiated");
}
CustomRequestView.prototype = {
/**
* Initialization function, called when the network monitor is started.
*/
- initialize: function() {
+ initialize: function () {
dumpn("Initializing the CustomRequestView");
this.updateCustomRequestEvent = getKeyWithEvent(this.onUpdate.bind(this));
$("#custom-pane").addEventListener("input",
this.updateCustomRequestEvent, false);
},
/**
* Destruction function, called when the network monitor is closed.
*/
- destroy: function() {
+ destroy: function () {
dumpn("Destroying the CustomRequestView");
$("#custom-pane").removeEventListener("input",
this.updateCustomRequestEvent, false);
},
/**
* Populates this view with the specified data.
@@ -2582,17 +2582,17 @@ CustomRequestView.prototype = {
}),
/**
* Handle user input in the custom request form.
*
* @param object field
* the field that the user updated.
*/
- onUpdate: function(field) {
+ onUpdate: function (field) {
let selectedItem = NetMonitorView.RequestsMenu.selectedItem;
let value;
switch (field) {
case "method":
value = $("#custom-method-value").value.trim();
selectedItem.attachment.method = value;
break;
@@ -2623,17 +2623,17 @@ CustomRequestView.prototype = {
},
/**
* Update the query string field based on the url.
*
* @param object url
* The URL to extract query string from.
*/
- updateCustomQuery: function(url) {
+ updateCustomQuery: function (url) {
let paramsArray = NetworkHelper.parseQueryString(
NetworkHelper.nsIURL(url).query);
if (!paramsArray) {
$("#custom-query").hidden = true;
return;
}
@@ -2642,17 +2642,17 @@ CustomRequestView.prototype = {
},
/**
* Update the url based on the query string field.
*
* @param object queryText
* The contents of the query string field.
*/
- updateCustomUrl: function(queryText) {
+ updateCustomUrl: function (queryText) {
let params = parseQueryText(queryText);
let queryString = writeQueryString(params);
let url = $("#custom-url-value").value;
let oldQuery = NetworkHelper.nsIURL(url).query;
let path = url.replace(oldQuery, queryString);
$("#custom-url-value").value = path;
@@ -2683,17 +2683,17 @@ NetworkDetailsView.prototype = {
dirty: [],
// the most recently received attachment data for the request
latestData: null,
},
/**
* Initialization function, called when the network monitor is started.
*/
- initialize: function() {
+ initialize: function () {
dumpn("Initializing the NetworkDetailsView");
this.widget = $("#event-details-pane");
this.sidebar = new ToolSidebar(this.widget, this, "netmonitor", {
disableTelemetry: true,
showAllTabsMenu: true
});
@@ -2729,32 +2729,32 @@ NetworkDetailsView.prototype = {
this._responseCookies = L10N.getStr("responseCookies");
$("tabpanels", this.widget).addEventListener("select", this._onTabSelect);
},
/**
* Destruction function, called when the network monitor is closed.
*/
- destroy: function() {
+ destroy: function () {
dumpn("Destroying the NetworkDetailsView");
this.sidebar.destroy();
$("tabpanels", this.widget).removeEventListener("select",
this._onTabSelect);
},
/**
* Populates this view with the specified data.
*
* @param object data
* The data source (this should be the attachment of a request item).
* @return object
* Returns a promise that resolves upon population the view.
*/
- populate: function(data) {
+ populate: function (data) {
$("#request-params-box").setAttribute("flex", "1");
$("#request-params-box").hidden = false;
$("#request-post-data-textarea-box").hidden = true;
$("#response-content-info-header").hidden = true;
$("#response-content-json-box").hidden = true;
$("#response-content-textarea-box").hidden = true;
$("#raw-headers").hidden = true;
$("#response-content-image-box").hidden = true;
@@ -2791,17 +2791,17 @@ NetworkDetailsView.prototype = {
window.emit(EVENTS.NETWORKDETAILSVIEW_POPULATED);
return promise.resolve();
},
/**
* Listener handling the tab selection event.
*/
- _onTabSelect: function() {
+ _onTabSelect: function () {
let { src, populated } = this._dataSrc || {};
let tab = this.widget.selectedIndex;
let view = this;
// Make sure the data source is valid and don't populate the same tab twice.
if (!src || populated[tab]) {
return;
}
@@ -2883,17 +2883,17 @@ NetworkDetailsView.prototype = {
},
/**
* Sets the network request summary shown in this view.
*
* @param object data
* The data source (this should be the attachment of a request item).
*/
- _setSummary: function(data) {
+ _setSummary: function (data) {
if (data.url) {
let unicodeUrl = NetworkHelper.convertToUnicode(unescape(data.url));
$("#headers-summary-url-value").setAttribute("value", unicodeUrl);
$("#headers-summary-url-value").setAttribute("tooltiptext", unicodeUrl);
$("#headers-summary-url").removeAttribute("hidden");
} else {
$("#headers-summary-url").setAttribute("hidden", "true");
}
@@ -3075,17 +3075,17 @@ NetworkDetailsView.prototype = {
}),
/**
* Sets the network request get params shown in this view.
*
* @param string url
* The request's url.
*/
- _setRequestGetParams: function(url) {
+ _setRequestGetParams: function (url) {
let query = NetworkHelper.nsIURL(url).query;
if (query) {
this._addParams(this._paramsQueryString, query);
}
},
/**
* Sets the network request post params shown in this view.
@@ -3154,17 +3154,17 @@ NetworkDetailsView.prototype = {
/**
* Populates the params container in this view with the specified data.
*
* @param string name
* The type of params to populate (get or post).
* @param string queryString
* A query string of params (e.g. "?foo=bar&baz=42").
*/
- _addParams: function(name, queryString) {
+ _addParams: function (name, queryString) {
let paramsArray = NetworkHelper.parseQueryString(queryString);
if (!paramsArray) {
return;
}
let paramsScope = this._params.addScope(name);
paramsScope.expanded = true;
for (let param of paramsArray) {
@@ -3290,17 +3290,17 @@ NetworkDetailsView.prototype = {
}),
/**
* Sets the timings information shown in this view.
*
* @param object response
* The message received from the server.
*/
- _setTimingsInformation: function(response) {
+ _setTimingsInformation: function (response) {
if (!response) {
return;
}
let { blocked, dns, connect, send, wait, receive } = response.timings;
let tabboxWidth = $("#details-pane").getAttribute("width");
// Other nodes also take some space.
@@ -3519,17 +3519,17 @@ NetworkDetailsView.prototype = {
*/
function PerformanceStatisticsView() {
}
PerformanceStatisticsView.prototype = {
/**
* Initializes and displays empty charts in this container.
*/
- displayPlaceholderCharts: function() {
+ displayPlaceholderCharts: function () {
this._createChart({
id: "#primed-cache-chart",
title: "charts.cacheEnabled"
});
this._createChart({
id: "#empty-cache-chart",
title: "charts.cacheDisabled"
});
@@ -3537,17 +3537,17 @@ PerformanceStatisticsView.prototype = {
},
/**
* Populates and displays the primed cache chart in this container.
*
* @param array items
* @see this._sanitizeChartDataSource
*/
- createPrimedCacheChart: function(items) {
+ createPrimedCacheChart: function (items) {
this._createChart({
id: "#primed-cache-chart",
title: "charts.cacheEnabled",
data: this._sanitizeChartDataSource(items),
strings: this._commonChartStrings,
totals: this._commonChartTotals,
sorted: true
});
@@ -3555,17 +3555,17 @@ PerformanceStatisticsView.prototype = {
},
/**
* Populates and displays the empty cache chart in this container.
*
* @param array items
* @see this._sanitizeChartDataSource
*/
- createEmptyCacheChart: function(items) {
+ createEmptyCacheChart: function (items) {
this._createChart({
id: "#empty-cache-chart",
title: "charts.cacheDisabled",
data: this._sanitizeChartDataSource(items, true),
strings: this._commonChartStrings,
totals: this._commonChartTotals,
sorted: true
});
@@ -3608,17 +3608,17 @@ PerformanceStatisticsView.prototype = {
/**
* Adds a specific chart to this container.
*
* @param object
* An object containing all or some the following properties:
* - id: either "#primed-cache-chart" or "#empty-cache-chart"
* - title/data/strings/totals/sorted: @see Chart.jsm for details
*/
- _createChart: function({ id, title, data, strings, totals, sorted }) {
+ _createChart: function ({ id, title, data, strings, totals, sorted }) {
let container = $(id);
// Nuke all existing charts of the specified type.
while (container.hasChildNodes()) {
container.firstChild.remove();
}
// Create a new chart.
@@ -3643,17 +3643,17 @@ PerformanceStatisticsView.prototype = {
* Sanitizes the data source used for creating charts, to follow the
* data format spec defined in Chart.jsm.
*
* @param array items
* A collection of request items used as the data source for the chart.
* @param boolean emptyCache
* True if the cache is considered enabled, false for disabled.
*/
- _sanitizeChartDataSource: function(items, emptyCache) {
+ _sanitizeChartDataSource: function (items, emptyCache) {
let data = [
"html", "css", "js", "xhr", "fonts", "images", "media", "flash", "ws",
"other"
].map(e => ({
cached: 0,
count: 0,
label: e,
size: 0,
@@ -3847,17 +3847,17 @@ function responseIsFresh({ responseHeade
*
* @param function callback
* Function to execute execute when data-key
* is present in event.target.
* @return function
* Wrapped function with the target data-key as the first argument.
*/
function getKeyWithEvent(callback) {
- return function(event) {
+ return function (event) {
let key = event.target.getAttribute("data-key");
if (key) {
callback.call(null, key);
}
};
}
/**
--- a/devtools/client/responsive.html/manager.js
+++ b/devtools/client/responsive.html/manager.js
@@ -128,17 +128,17 @@ const ResponsiveUIManager = exports.Resp
* The main browser chrome window.
* @param tab
* The browser tab.
* @param command
* The GCLI command name.
* @param args
* The GCLI command arguments.
*/
- handleGcliCommand: function(window, tab, command, args) {
+ handleGcliCommand: function (window, tab, command, args) {
let completed;
switch (command) {
case "resize to":
completed = this.openIfNeeded(window, tab);
this.activeTabs.get(tab).setViewportSize(args.width, args.height);
break;
case "resize on":
completed = this.openIfNeeded(window, tab);
@@ -306,17 +306,17 @@ function tabLoaded(tab) {
}
/**
* Waits for the next load to complete in the current browser.
*/
function waitForDocLoadComplete(gBrowser) {
let deferred = promise.defer();
let progressListener = {
- onStateChange: function(webProgress, req, flags, status) {
+ onStateChange: function (webProgress, req, flags, status) {
let docStop = Ci.nsIWebProgressListener.STATE_IS_NETWORK |
Ci.nsIWebProgressListener.STATE_STOP;
// When a load needs to be retargetted to a new process it is cancelled
// with NS_BINDING_ABORTED so ignore that case
if ((flags & docStop) == docStop && status != Cr.NS_BINDING_ABORTED) {
gBrowser.removeProgressListener(progressListener);
deferred.resolve();
--- a/devtools/client/responsive.html/reducers/devices.js
+++ b/devtools/client/responsive.html/reducers/devices.js
@@ -48,15 +48,15 @@ let reducers = {
[UPDATE_DEVICE_MODAL_OPEN](devices, { isOpen }) {
return Object.assign({}, devices, {
isModalOpen: isOpen,
});
},
};
-module.exports = function(devices = INITIAL_DEVICES, action) {
+module.exports = function (devices = INITIAL_DEVICES, action) {
let reducer = reducers[action.type];
if (!reducer) {
return devices;
}
return reducer(devices, action);
};
--- a/devtools/client/responsive.html/reducers/location.js
+++ b/devtools/client/responsive.html/reducers/location.js
@@ -11,15 +11,15 @@ const INITIAL_LOCATION = "about:blank";
let reducers = {
[CHANGE_LOCATION](_, action) {
return action.location;
},
};
-module.exports = function(location = INITIAL_LOCATION, action) {
+module.exports = function (location = INITIAL_LOCATION, action) {
let reducer = reducers[action.type];
if (!reducer) {
return location;
}
return reducer(location, action);
};
--- a/devtools/client/responsive.html/reducers/screenshot.js
+++ b/devtools/client/responsive.html/reducers/screenshot.js
@@ -17,15 +17,15 @@ let reducers = {
return Object.assign({}, screenshot, { isCapturing: false });
},
[TAKE_SCREENSHOT_START](screenshot, action) {
return Object.assign({}, screenshot, { isCapturing: true });
},
};
-module.exports = function(screenshot = INITIAL_SCREENSHOT, action) {
+module.exports = function (screenshot = INITIAL_SCREENSHOT, action) {
let reducer = reducers[action.type];
if (!reducer) {
return screenshot;
}
return reducer(screenshot, action);
};
--- a/devtools/client/responsive.html/reducers/viewports.js
+++ b/devtools/client/responsive.html/reducers/viewports.js
@@ -66,15 +66,15 @@ let reducers = {
width: viewport.height,
height: viewport.width,
});
});
},
};
-module.exports = function(viewports = INITIAL_VIEWPORTS, action) {
+module.exports = function (viewports = INITIAL_VIEWPORTS, action) {
let reducer = reducers[action.type];
if (!reducer) {
return viewports;
}
return reducer(viewports, action);
};
--- a/devtools/client/responsive.html/store.js
+++ b/devtools/client/responsive.html/store.js
@@ -4,17 +4,17 @@
"use strict";
const { combineReducers } = require("devtools/client/shared/vendor/redux");
const createStore = require("devtools/client/shared/redux/create-store");
const reducers = require("./reducers");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
-module.exports = function() {
+module.exports = function () {
let shouldLog = false;
let history;
// If testing, store the action history in an array
// we'll later attach to the store
if (DevToolsUtils.testing) {
history = [];
shouldLog = true;
--- a/devtools/client/storage/panel.js
+++ b/devtools/client/storage/panel.js
@@ -33,17 +33,17 @@ StoragePanel.prototype = {
get panelWindow() {
return this._panelWin;
},
/**
* open is effectively an asynchronous constructor
*/
- open: function() {
+ open: function () {
let targetPromise;
// We always interact with the target as if it were remote
if (!this.target.isRemote) {
targetPromise = this.target.makeRemote();
} else {
targetPromise = Promise.resolve(this.target);
}
@@ -60,17 +60,17 @@ StoragePanel.prototype = {
console.log("error while opening storage panel", e);
this.destroy();
});
},
/**
* Destroy the storage inspector.
*/
- destroy: function() {
+ destroy: function () {
if (!this._destroyed) {
this.UI.destroy();
this.UI = null;
// Destroy front to ensure packet handler is removed from client
this._front.destroy();
this._front = null;
this._destroyed = true;
--- a/devtools/client/storage/test/head.js
+++ b/devtools/client/storage/test/head.js
@@ -65,17 +65,17 @@ function* openTabAndSetupStorage(url) {
* The base window at which to start looking for child windows
* (optional).
* @return {Set}
* A set of windows.
*/
function getAllWindows(baseWindow) {
let windows = new Set();
- let _getAllWindows = function(win) {
+ let _getAllWindows = function (win) {
windows.add(win.wrappedJSObject);
for (let i = 0; i < win.length; i++) {
_getAllWindows(win[i]);
}
};
_getAllWindows(baseWindow);
@@ -195,17 +195,17 @@ function* finishTests() {
* The base window at which to start looking for child windows
* (optional).
* @return {Set}
* A set of windows.
*/
function getAllWindows(baseWindow) {
let windows = new Set();
- let _getAllWindows = function(win) {
+ let _getAllWindows = function (win) {
windows.add(win.wrappedJSObject);
for (let i = 0; i < win.length; i++) {
_getAllWindows(win[i]);
}
};
_getAllWindows(baseWindow);
@@ -380,22 +380,22 @@ function findVariableViewProperties(rule
};
variablesViewExpandTo(expandOptions).then(function onSuccess(prop) {
let name = rule.name;
let lastName = name.split(".").pop();
rule.name = lastName;
let matched = matchVariablesViewProperty(prop, rule);
- return matched.then(onMatch.bind(null, prop, rule)).then(function() {
+ return matched.then(onMatch.bind(null, prop, rule)).then(function () {
rule.name = name;
});
}, function onFailure() {
return promise.resolve(null);
- }).then(processExpandRules.bind(null, rules)).then(function() {
+ }).then(processExpandRules.bind(null, rules)).then(function () {
deferred.resolve(null);
});
return deferred.promise;
}
function onAllRulesMatched(rules) {
for (let rule of rules) {
--- a/devtools/client/storage/ui.js
+++ b/devtools/client/storage/ui.js
@@ -164,17 +164,17 @@ StorageUI.prototype = {
storageTypes: null,
shouldLoadMoreItems: true,
set animationsEnabled(value) {
this._panelDoc.documentElement.classList.toggle("no-animate", !value);
},
- destroy: function() {
+ destroy: function () {
this.table.off(TableWidget.EVENTS.ROW_SELECTED, this.displayObjectSidebar);
this.table.off(TableWidget.EVENTS.SCROLL_END, this.handleScrollEnd);
this.table.off(TableWidget.EVENTS.CELL_EDIT, this.editItem);
this.table.destroy();
this.front.off("stores-update", this.onUpdate);
this.front.off("stores-cleared", this.onCleared);
this._panelDoc.removeEventListener("keypress", this.handleKeypress);
@@ -196,51 +196,51 @@ StorageUI.prototype = {
this.onRemoveAllFrom);
this._tablePopupDeleteAll.removeEventListener("command",
this.onRemoveAll);
},
/**
* Empties and hides the object viewer sidebar
*/
- hideSidebar: function() {
+ hideSidebar: function () {
this.view.empty();
this.sidebar.hidden = true;
this.table.clearSelection();
},
- getCurrentActor: function() {
+ getCurrentActor: function () {
let type = this.table.datatype;
return this.storageTypes[type];
},
makeFieldsEditable: function* () {
let actor = this.getCurrentActor();
if (typeof actor.getEditableFields !== "undefined") {
let fields = yield actor.getEditableFields();
this.table.makeFieldsEditable(fields);
} else if (this.table._editableFieldsEngine) {
this.table._editableFieldsEngine.destroy();
}
},
- editItem: function(eventType, data) {
+ editItem: function (eventType, data) {
let actor = this.getCurrentActor();
actor.editItem(data);
},
/**
* Removes the given item from the storage table. Reselects the next item in
* the table and repopulates the sidebar with that item's data if the item
* being removed was selected.
*/
- removeItemFromTable: function(name) {
+ removeItemFromTable: function (name) {
if (this.table.isSelected(name)) {
if (this.table.selectedIndex == 0) {
this.table.selectNextRow();
} else {
this.table.selectPreviousRow();
}
this.table.remove(name);
this.displayObjectSidebar();
@@ -250,17 +250,17 @@ StorageUI.prototype = {
},
/**
* Event handler for "stores-cleared" event coming from the storage actor.
*
* @param {object} argument0
* An object containing which storage types were cleared
*/
- onCleared: function(response) {
+ onCleared: function (response) {
let [type, host] = this.tree.selectedItem;
if (response.hasOwnProperty(type) && response[type].indexOf(host) > -1) {
this.table.clear();
this.hideSidebar();
this.emit("store-objects-cleared");
}
},
@@ -282,17 +282,17 @@ StorageUI.prototype = {
* }, ...
* }
* Where store_type1 and store_type2 is one of cookies, indexedDB,
* sessionStorage and localStorage; host1, host2 are the host in which
* this change happened; and [<store_namesX] is an array of the names
* of the changed store objects. This array is empty for deleted object
* if the host was completely removed.
*/
- onUpdate: function({ changed, added, deleted }) {
+ onUpdate: function ({ changed, added, deleted }) {
if (deleted) {
this.handleDeletedItems(deleted);
}
if (added) {
this.handleAddedItems(added);
}
@@ -305,17 +305,17 @@ StorageUI.prototype = {
}
},
/**
* Handle added items received by onUpdate
*
* @param {object} See onUpdate docs
*/
- handleAddedItems: function(added) {
+ handleAddedItems: function (added) {
for (let type in added) {
for (let host in added[type]) {
this.tree.add([type, {id: host, type: "url"}]);
for (let name of added[type][host]) {
try {
name = JSON.parse(name);
if (name.length == 3) {
name.splice(2, 1);
@@ -339,17 +339,17 @@ StorageUI.prototype = {
}
},
/**
* Handle deleted items received by onUpdate
*
* @param {object} See onUpdate docs
*/
- handleDeletedItems: function(deleted) {
+ handleDeletedItems: function (deleted) {
for (let type in deleted) {
for (let host in deleted[type]) {
if (!deleted[type][host].length) {
// This means that the whole host is deleted, thus the item should
// be removed from the storage tree
if (this.tree.isSelected([type, host])) {
this.table.clear();
this.hideSidebar();
@@ -391,17 +391,17 @@ StorageUI.prototype = {
}
},
/**
* Handle changed items received by onUpdate
*
* @param {object} See onUpdate docs
*/
- handleChangedItems: function(changed) {
+ handleChangedItems: function (changed) {
let [type, host, db, objectStore] = this.tree.selectedItem;
if (!changed[type] || !changed[type][host] ||
changed[type][host].length == 0) {
return;
}
try {
let toUpdate = [];
for (let name of changed[type][host]) {
@@ -458,17 +458,17 @@ StorageUI.prototype = {
/**
* Populates the storage tree which displays the list of storages present for
* the page.
*
* @param {object} storageTypes
* List of storages and their corresponding hosts returned by the
* StorageFront.listStores call.
*/
- populateStorageTree: function(storageTypes) {
+ populateStorageTree: function (storageTypes) {
this.storageTypes = {};
for (let type in storageTypes) {
// Ignore `from` field, which is just a protocol.js implementation
// artifact.
if (type === "from") {
continue;
}
let typeLabel = type;
@@ -567,17 +567,17 @@ StorageUI.prototype = {
* object and populates the sidebar with the parsed value. The value can also
* be a key separated array.
*
* @param {string} name
* The key corresponding to the `value` string in the object
* @param {string} value
* The string to be parsed into an object
*/
- parseItemValue: function(name, value) {
+ parseItemValue: function (name, value) {
let json = null;
try {
json = JSON.parse(value);
} catch (ex) {
json = null;
}
if (!json && value) {
@@ -610,17 +610,17 @@ StorageUI.prototype = {
/**
* Tries to parse a string into an object on the basis of key-value pairs,
* separated by various separators. If failed, tries to parse for single
* separator separated values to form an array.
*
* @param {string} value
* The string to be parsed into an object or array
*/
- _extractKeyValPairs: function(value) {
+ _extractKeyValPairs: function (value) {
let makeObject = (keySep, pairSep) => {
let object = {};
for (let pair of value.split(pairSep)) {
let [key, val] = pair.split(keySep);
object[key] = val;
}
return object;
};
@@ -662,17 +662,17 @@ StorageUI.prototype = {
* from the storage details and populates the storage tree.
*
* @param {string} event
* The name of the event fired
* @param {array} item
* An array of ids which represent the location of the selected item in
* the storage tree
*/
- onHostSelect: function(event, item) {
+ onHostSelect: function (event, item) {
this.table.clear();
this.hideSidebar();
this.searchBox.value = "";
let [type, host] = item;
let names = null;
if (!host) {
return;
@@ -722,17 +722,17 @@ StorageUI.prototype = {
/**
* Populates or updates the rows in the storage table.
*
* @param {array[object]} data
* Array of objects to be populated in the storage table
* @param {Constant} reason
* See REASON constant at top of file.
*/
- populateTable: function(data, reason) {
+ populateTable: function (data, reason) {
for (let item of data) {
if (item.value) {
item.valueActor = item.value;
item.value = item.value.initial || "";
}
if (item.expires != null) {
item.expires = item.expires
? new Date(item.expires).toUTCString()
@@ -768,17 +768,17 @@ StorageUI.prototype = {
},
/**
* Handles keypress event on the body table to close the sidebar when open
*
* @param {DOMEvent} event
* The event passed by the keypress event.
*/
- handleKeypress: function(event) {
+ handleKeypress: function (event) {
if (event.keyCode == event.DOM_VK_ESCAPE && !this.sidebar.hidden) {
// Stop Propagation to prevent opening up of split console
this.hideSidebar();
event.stopPropagation();
event.preventDefault();
}
},
@@ -789,17 +789,17 @@ StorageUI.prototype = {
let value = this.searchBox.value;
this.table.filterItems(value, ["valueActor"]);
this._panelDoc.documentElement.classList.toggle("filtering", !!value);
},
/**
* Handles endless scrolling for the table
*/
- handleScrollEnd: function() {
+ handleScrollEnd: function () {
if (!this.shouldLoadMoreItems) {
return;
}
this.shouldLoadMoreItems = false;
this.itemOffset += 50;
let item = this.tree.selectedItem;
let [type, host] = item;
@@ -810,17 +810,17 @@ StorageUI.prototype = {
this.fetchStorageObjects(type, host, names, REASON.NEXT_50_ITEMS);
},
/**
* Fires before a cell context menu with the "Delete" action is shown.
* If the current storage actor doesn't support removing items, prevent
* showing the menu.
*/
- onTablePopupShowing: function(event) {
+ onTablePopupShowing: function (event) {
if (!this.getCurrentActor().removeItem) {
event.preventDefault();
return;
}
let [type] = this.tree.selectedItem;
let rowId = this.table.contextMenuRowId;
let data = this.table.items.get(rowId);
@@ -835,17 +835,17 @@ StorageUI.prototype = {
this._tablePopupDeleteAllFrom.hidden = false;
this._tablePopupDeleteAllFrom.setAttribute("label",
L10N.getFormatStr("storage.popupMenu.deleteAllFromLabel", host));
} else {
this._tablePopupDeleteAllFrom.hidden = true;
}
},
- onTreePopupShowing: function(event) {
+ onTreePopupShowing: function (event) {
let showMenu = false;
let selectedItem = this.tree.selectedItem;
if (selectedItem) {
// this.currentActor() would return wrong value here
let actor = this.storageTypes[selectedItem[0]];
let showDeleteAll = selectedItem.length == 2 && actor.removeAll;
@@ -865,50 +865,50 @@ StorageUI.prototype = {
if (!showMenu) {
event.preventDefault();
}
},
/**
* Handles removing an item from the storage
*/
- onRemoveItem: function() {
+ onRemoveItem: function () {
let [, host] = this.tree.selectedItem;
let actor = this.getCurrentActor();
let rowId = this.table.contextMenuRowId;
let data = this.table.items.get(rowId);
actor.removeItem(host, data[this.table.uniqueId]);
},
/**
* Handles removing all items from the storage
*/
- onRemoveAll: function() {
+ onRemoveAll: function () {
// Cannot use this.currentActor() if the handler is called from the
// tree context menu: it returns correct value only after the table
// data from server are successfully fetched (and that's async).
let [type, host] = this.tree.selectedItem;
let actor = this.storageTypes[type];
actor.removeAll(host);
},
/**
* Handles removing all cookies with exactly the same domain as the
* cookie in the selected row.
*/
- onRemoveAllFrom: function() {
+ onRemoveAllFrom: function () {
let [, host] = this.tree.selectedItem;
let actor = this.getCurrentActor();
let rowId = this.table.contextMenuRowId;
let data = this.table.items.get(rowId);
actor.removeAll(host, data.host);
},
- onRemoveDatabase: function() {
+ onRemoveDatabase: function () {
let [type, host, name] = this.tree.selectedItem;
let actor = this.storageTypes[type];
actor.removeDatabase(host, name);
}
};
--- a/devtools/client/styleeditor/StyleEditorUI.jsm
+++ b/devtools/client/styleeditor/StyleEditorUI.jsm
@@ -147,17 +147,17 @@ StyleEditorUI.prototype = {
"elements matching hovered selectors will not be highlighted");
}
}
}),
/**
* Build the initial UI and wire buttons with event handlers.
*/
- createUI: function() {
+ createUI: function () {
let viewRoot = this._root.parentNode.querySelector(".splitview-root");
this._view = new SplitView(viewRoot);
wire(this._view.rootElement, ".style-editor-newButton", () =>{
this._debuggee.addStyleSheet(null).then(this._onStyleSheetCreated);
});
@@ -197,40 +197,40 @@ StyleEditorUI.prototype = {
let nav = this._panelDoc.querySelector(".splitview-controller");
nav.setAttribute("width", Services.prefs.getIntPref(PREF_NAV_WIDTH));
},
/**
* Listener handling the 'gear menu' popup showing event.
* Update options menu items to reflect current preference settings.
*/
- _onOptionsPopupShowing: function() {
+ _onOptionsPopupShowing: function () {
this._optionsButton.setAttribute("open", "true");
this._sourcesItem.setAttribute("checked",
Services.prefs.getBoolPref(PREF_ORIG_SOURCES));
this._mediaItem.setAttribute("checked",
Services.prefs.getBoolPref(PREF_MEDIA_SIDEBAR));
},
/**
* Listener handling the 'gear menu' popup hiding event.
*/
- _onOptionsPopupHiding: function() {
+ _onOptionsPopupHiding: function () {
this._optionsButton.removeAttribute("open");
},
/**
* Refresh editors to reflect the stylesheets in the document.
*
* @param {string} event
* Event name
* @param {StyleSheet} styleSheet
* StyleSheet object for new sheet
*/
- _onNewDocument: function() {
+ _onNewDocument: function () {
this._debuggee.getStyleSheets().then((styleSheets) => {
return this._resetStyleSheetList(styleSheets);
}).then(null, Cu.reportError);
},
/**
* Add editors for all the given stylesheets to the UI.
*
@@ -251,17 +251,17 @@ StyleEditorUI.prototype = {
this._root.classList.remove("loading");
this.emit("stylesheets-reset");
}),
/**
* Remove all editors and add loading indicator.
*/
- _clear: function() {
+ _clear: function () {
// remember selected sheet and line number for next load
if (this.selectedEditor && this.selectedEditor.sourceEditor) {
let href = this.selectedEditor.styleSheet.href;
let {line, ch} = this.selectedEditor.sourceEditor.getCursor();
this._styleSheetToSelect = {
stylesheet: href,
line: line,
@@ -356,17 +356,17 @@ StyleEditorUI.prototype = {
* new stylesheet on the debuggee for it.
*
* @param {mixed} file
* Optional nsIFile or filename string.
* If not set a file picker will be shown.
* @param {nsIWindow} parentWindow
* Optional parent window for the file picker.
*/
- _importFromFile: function(file, parentWindow) {
+ _importFromFile: function (file, parentWindow) {
let onFileSelected = (selectedFile) => {
if (!selectedFile) {
// nothing selected
return;
}
NetUtil.asyncFetch({
uri: NetUtil.newURI(selectedFile),
loadingNode: this._window.document,
@@ -389,91 +389,91 @@ StyleEditorUI.prototype = {
showFilePicker(file, false, parentWindow, onFileSelected);
},
/**
* When a new or imported stylesheet has been added to the document.
* Add an editor for it.
*/
- _onStyleSheetCreated: function(styleSheet, file) {
+ _onStyleSheetCreated: function (styleSheet, file) {
this._addStyleSheetEditor(styleSheet, file, true);
},
/**
* Forward any error from a stylesheet.
*
* @param {string} event
* Event name
* @param {data} data
* The event data
*/
- _onError: function(event, data) {
+ _onError: function (event, data) {
this.emit("error", data);
},
/**
* Toggle the original sources pref.
*/
- _toggleOrigSources: function() {
+ _toggleOrigSources: function () {
let isEnabled = Services.prefs.getBoolPref(PREF_ORIG_SOURCES);
Services.prefs.setBoolPref(PREF_ORIG_SOURCES, !isEnabled);
},
/**
* Toggle the pref for showing a @media rules sidebar in each editor.
*/
- _toggleMediaSidebar: function() {
+ _toggleMediaSidebar: function () {
let isEnabled = Services.prefs.getBoolPref(PREF_MEDIA_SIDEBAR);
Services.prefs.setBoolPref(PREF_MEDIA_SIDEBAR, !isEnabled);
},
/**
* Toggle the @media sidebar in each editor depending on the setting.
*/
- _onMediaPrefChanged: function() {
+ _onMediaPrefChanged: function () {
this.editors.forEach(this._updateMediaList);
},
/**
* This method handles the following cases related to the context
* menu item "_openLinkNewTabItem":
*
* 1) There was a stylesheet clicked on and it is external: show and
* enable the context menu item
* 2) There was a stylesheet clicked on and it is inline: show and
* disable the context menu item
* 3) There was no stylesheet clicked on (the right click happened
* below the list): hide the context menu
*/
- _updateOpenLinkItem: function() {
+ _updateOpenLinkItem: function () {
this._openLinkNewTabItem.setAttribute("hidden",
!this._contextMenuStyleSheet);
if (this._contextMenuStyleSheet) {
this._openLinkNewTabItem.setAttribute("disabled",
!this._contextMenuStyleSheet.href);
}
},
/**
* Open a particular stylesheet in a new tab.
*/
- _openLinkNewTab: function() {
+ _openLinkNewTab: function () {
if (this._contextMenuStyleSheet) {
this._window.openUILinkIn(this._contextMenuStyleSheet.href, "tab");
}
},
/**
* Remove a particular stylesheet editor from the UI
*
* @param {StyleSheetEditor} editor
* The editor to remove.
*/
- _removeStyleSheetEditor: function(editor) {
+ _removeStyleSheetEditor: function (editor) {
if (editor.summary) {
this._view.removeItem(editor.summary);
} else {
let self = this;
this.on("editor-added", function onAdd(event, added) {
if (editor == added) {
self.off("editor-added", onAdd);
self._view.removeItem(editor.summary);
@@ -483,41 +483,41 @@ StyleEditorUI.prototype = {
editor.destroy();
this.editors.splice(this.editors.indexOf(editor), 1);
},
/**
* Clear all the editors from the UI.
*/
- _clearStyleSheetEditors: function() {
+ _clearStyleSheetEditors: function () {
for (let editor of this.editors) {
editor.destroy();
}
this.editors = [];
},
/**
* Called when a StyleSheetEditor's source has been fetched. Create a
* summary UI for the editor.
*
* @param {StyleSheetEditor} editor
* Editor to create UI for.
*/
- _sourceLoaded: function(editor) {
+ _sourceLoaded: function (editor) {
let ordinal = editor.styleSheet.styleSheetIndex;
ordinal = ordinal == -1 ? Number.MAX_SAFE_INTEGER : ordinal;
// add new sidebar item and editor to the UI
this._view.appendTemplatedItem(STYLE_EDITOR_TEMPLATE, {
data: {
editor: editor
},
disableAnimations: this._alwaysDisableAnimations,
ordinal: ordinal,
- onCreate: function(summary, details, data) {
+ onCreate: function (summary, details, data) {
let createdEditor = data.editor;
createdEditor.summary = summary;
createdEditor.details = details;
wire(summary, ".stylesheet-enabled", function onToggleDisabled(event) {
event.stopPropagation();
event.target.blur();
@@ -584,17 +584,17 @@ StyleEditorUI.prototype = {
// select a particular style sheet, select this sheet.
if (!this.selectedEditor && !this._styleSheetBoundToSelect
&& createdEditor.styleSheet.styleSheetIndex == 0) {
this._selectEditor(createdEditor);
}
this.emit("editor-added", createdEditor);
}.bind(this),
- onShow: function(summary, details, data) {
+ onShow: function (summary, details, data) {
let showEditor = data.editor;
this.selectedEditor = showEditor;
Task.spawn(function* () {
if (!showEditor.sourceEditor) {
// only initialize source editor when we switch to this view
let inputElement =
details.querySelector(".stylesheet-editor-input");
@@ -634,17 +634,17 @@ StyleEditorUI.prototype = {
},
/**
* Switch to the editor that has been marked to be selected.
*
* @return {Promise}
* Promise that will resolve when the editor is selected.
*/
- switchToSelectedSheet: function() {
+ switchToSelectedSheet: function () {
let toSelect = this._styleSheetToSelect;
for (let editor of this.editors) {
if (this._isEditorToSelect(editor)) {
// The _styleSheetBoundToSelect will always hold the latest pending
// requested style sheet (with line and column) which is not yet
// selected by the source editor. Only after we select that particular
// editor and go the required line and column, it will become null.
@@ -659,17 +659,17 @@ StyleEditorUI.prototype = {
/**
* Returns whether a given editor is the current editor to be selected. Tests
* based on href or underlying stylesheet.
*
* @param {StyleSheetEditor} editor
* The editor to test.
*/
- _isEditorToSelect: function(editor) {
+ _isEditorToSelect: function (editor) {
let toSelect = this._styleSheetToSelect;
if (!toSelect) {
return false;
}
let isHref = toSelect.stylesheet === null ||
typeof toSelect.stylesheet == "string";
return (isHref && editor.styleSheet.href == toSelect.stylesheet) ||
@@ -684,33 +684,33 @@ StyleEditorUI.prototype = {
* @param {number} line
* Line number to jump to
* @param {number} col
* Column number to jump to
* @return {Promise}
* Promise that will resolve when the editor is selected and ready
* to be used.
*/
- _selectEditor: function(editor, line, col) {
+ _selectEditor: function (editor, line, col) {
line = line || 0;
col = col || 0;
let editorPromise = editor.getSourceEditor().then(() => {
editor.sourceEditor.setCursor({line: line, ch: col});
this._styleSheetBoundToSelect = null;
});
let summaryPromise = this.getEditorSummary(editor).then((summary) => {
this._view.activeSummary = summary;
});
return promise.all([editorPromise, summaryPromise]);
},
- getEditorSummary: function(editor) {
+ getEditorSummary: function (editor) {
if (editor.summary) {
return promise.resolve(editor.summary);
}
let deferred = promise.defer();
let self = this;
this.on("editor-added", function onAdd(e, selected) {
@@ -718,17 +718,17 @@ StyleEditorUI.prototype = {
self.off("editor-added", onAdd);
deferred.resolve(editor.summary);
}
});
return deferred.promise;
},
- getEditorDetails: function(editor) {
+ getEditorDetails: function (editor) {
if (editor.details) {
return promise.resolve(editor.details);
}
let deferred = promise.defer();
let self = this;
this.on("editor-added", function onAdd(e, selected) {
@@ -742,17 +742,17 @@ StyleEditorUI.prototype = {
},
/**
* Returns an identifier for the given style sheet.
*
* @param {StyleSheet} styleSheet
* The style sheet to be identified.
*/
- getStyleSheetIdentifier: function(styleSheet) {
+ getStyleSheetIdentifier: function (styleSheet) {
// Identify inline style sheets by their host page URI and index
// at the page.
return styleSheet.href ? styleSheet.href :
"inline-" + styleSheet.styleSheetIndex + "-at-" + styleSheet.nodeHref;
},
/**
* selects a stylesheet and optionally moves the cursor to a selected line
@@ -762,17 +762,17 @@ StyleEditorUI.prototype = {
* @param {Number} [line]
* Line to which the caret should be moved (zero-indexed).
* @param {Number} [col]
* Column to which the caret should be moved (zero-indexed).
* @return {Promise}
* Promise that will resolve when the editor is selected and ready
* to be used.
*/
- selectStyleSheet: function(stylesheet, line, col) {
+ selectStyleSheet: function (stylesheet, line, col) {
this._styleSheetToSelect = {
stylesheet: stylesheet,
line: line,
col: col,
};
/* Switch to the editor for this sheet, if it exists yet.
Otherwise each editor will be checked when it's created. */
@@ -781,29 +781,29 @@ StyleEditorUI.prototype = {
/**
* Handler for an editor's 'property-changed' event.
* Update the summary in the UI.
*
* @param {StyleSheetEditor} editor
* Editor for which a property has changed
*/
- _summaryChange: function(editor) {
+ _summaryChange: function (editor) {
this._updateSummaryForEditor(editor);
},
/**
* Update split view summary of given StyleEditor instance.
*
* @param {StyleSheetEditor} editor
* @param {DOMElement} summary
* Optional item's summary element to update. If none, item
* corresponding to passed editor is used.
*/
- _updateSummaryForEditor: function(editor, summary) {
+ _updateSummaryForEditor: function (editor, summary) {
summary = summary || editor.summary;
if (!summary) {
return;
}
let ruleCount = editor.styleSheet.ruleCount;
if (editor.styleSheet.relatedStyleSheet) {
ruleCount = editor.styleSheet.relatedStyleSheet.ruleCount;
@@ -846,17 +846,17 @@ StyleEditorUI.prototype = {
/**
* Update the @media rules sidebar for an editor. Hide if there are no rules
* Display a list of the @media rules in the editor's associated style sheet.
* Emits a 'media-list-changed' event after updating the UI.
*
* @param {StyleSheetEditor} editor
* Editor to update @media sidebar of
*/
- _updateMediaList: function(editor) {
+ _updateMediaList: function (editor) {
Task.spawn(function* () {
let details = yield this.getEditorDetails(editor);
let list = details.querySelector(".stylesheet-media-list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
@@ -925,17 +925,17 @@ StyleEditorUI.prototype = {
/**
* Called when a media condition is clicked
* If a responsive mode link is clicked, it will launch it.
*
* @param {object} e
* Event object
*/
- _onMediaConditionClick: function(e) {
+ _onMediaConditionClick: function (e) {
if (!e.target.matches(".media-responsive-mode-toggle")) {
return;
}
let conditionText = e.target.textContent;
let isWidthCond = conditionText.toLowerCase().indexOf("width") > -1;
let mediaVal = parseInt(/\d+/.exec(conditionText), 10);
let options = isWidthCond ? {width: mediaVal} : {height: mediaVal};
@@ -966,22 +966,22 @@ StyleEditorUI.prototype = {
}),
/**
* Jump cursor to the editor for a stylesheet and line number for a rule.
*
* @param {object} location
* Location object with 'line', 'column', and 'source' properties.
*/
- _jumpToLocation: function(location) {
+ _jumpToLocation: function (location) {
let source = location.styleSheet || location.source;
this.selectStyleSheet(source, location.line - 1, location.column - 1);
},
- destroy: function() {
+ destroy: function () {
if (this._highlighter) {
this._highlighter.finalize();
this._highlighter = null;
}
this._clearStyleSheetEditors();
let sidebar = this._panelDoc.querySelector(".splitview-controller");
--- a/devtools/client/styleeditor/StyleEditorUtil.jsm
+++ b/devtools/client/styleeditor/StyleEditorUtil.jsm
@@ -152,17 +152,17 @@ function wire(root, selectorOrElement, d
}
if (typeof descriptor == "function") {
descriptor = {events: {click: descriptor}};
}
for (let i = 0; i < matches.length; i++) {
let element = matches[i];
- forEach(descriptor.events, function(name, handler) {
+ forEach(descriptor.events, function (name, handler) {
element.addEventListener(name, handler, false);
});
forEach(descriptor.attributes, element.setAttribute);
}
}
/**
* Show file picker and return the file user selected.
@@ -209,17 +209,17 @@ function showFilePicker(path, toSave, pa
// "path" is an nsIFile
callback(path);
return;
}
let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
let mode = toSave ? fp.modeSave : fp.modeOpen;
let key = toSave ? "saveStyleSheet" : "importStyleSheet";
- let fpCallback = function(result) {
+ let fpCallback = function (result) {
if (result == Ci.nsIFilePicker.returnCancel) {
callback(null);
} else {
callback(fp.file);
}
};
if (toSave && suggestedFilename) {
--- a/devtools/client/styleeditor/StyleSheetEditor.jsm
+++ b/devtools/client/styleeditor/StyleSheetEditor.jsm
@@ -211,17 +211,17 @@ StyleSheetEditor.prototype = {
*/
get transitionsEnabled() {
return Services.prefs.getBoolPref(TRANSITION_PREF);
},
/**
* If this is an original source, get the path of the CSS file it generated.
*/
- linkCSSFile: function() {
+ linkCSSFile: function () {
if (!this.styleSheet.isOriginalSource) {
return;
}
let relatedSheet = this.styleSheet.relatedStyleSheet;
if (!relatedSheet || !relatedSheet.href) {
return;
}
@@ -261,17 +261,17 @@ StyleSheetEditor.prototype = {
/**
* A helper function that fetches the source text from the style
* sheet. The text is possibly prettified using
* CssLogic.prettifyCSS. This also sets |this._state.text| to the
* new text.
*
* @return {Promise} a promise that resolves to the new text
*/
- _getSourceTextAndPrettify: function() {
+ _getSourceTextAndPrettify: function () {
return this.styleSheet.getText().then((longStr) => {
return longStr.string();
}).then((source) => {
let ruleCount = this.styleSheet.ruleCount;
if (!this.styleSheet.isOriginalSource) {
source = CssLogic.prettifyCSS(source, ruleCount);
}
this._state.text = source;
@@ -281,17 +281,17 @@ StyleSheetEditor.prototype = {
/**
* Start fetching the full text source for this editor's sheet.
*
* @return {Promise}
* A promise that'll resolve with the source text once the source
* has been loaded or reject on unexpected error.
*/
- fetchSource: function() {
+ fetchSource: function () {
return this._getSourceTextAndPrettify().then((source) => {
this.sourceLoaded = true;
return source;
}).then(null, e => {
if (this._isDestroyed) {
console.warn("Could not fetch the source for " +
this.styleSheet.href +
", the editor was destroyed");
@@ -306,59 +306,59 @@ StyleSheetEditor.prototype = {
/**
* Add markup to a region. UNUSED_CLASS is added to specified lines
* @param region An object shaped like
* {
* start: { line: L1, column: C1 },
* end: { line: L2, column: C2 } // optional
* }
*/
- addUnusedRegion: function(region) {
+ addUnusedRegion: function (region) {
this.sourceEditor.addLineClass(region.start.line - 1, UNUSED_CLASS);
if (region.end) {
for (let i = region.start.line; i <= region.end.line; i++) {
this.sourceEditor.addLineClass(i - 1, UNUSED_CLASS);
}
}
},
/**
* As addUnusedRegion except that it takes an array of regions
*/
- addUnusedRegions: function(regions) {
+ addUnusedRegions: function (regions) {
for (let region of regions) {
this.addUnusedRegion(region);
}
},
/**
* Remove all the unused markup regions added by addUnusedRegion
*/
- removeAllUnusedRegions: function() {
+ removeAllUnusedRegions: function () {
for (let i = 0; i < this.sourceEditor.lineCount(); i++) {
this.sourceEditor.removeLineClass(i, UNUSED_CLASS);
}
},
/**
* Forward property-change event from stylesheet.
*
* @param {string} event
* Event type
* @param {string} property
* Property that has changed on sheet
*/
- _onPropertyChange: function(property, value) {
+ _onPropertyChange: function (property, value) {
this.emit("property-change", property, value);
},
/**
* Called when the stylesheet text changes.
*/
- _onStyleApplied: function() {
+ _onStyleApplied: function () {
if (this._isUpdating) {
// We just applied an edit in the editor, so we can drop this
// notification.
this._isUpdating = false;
} else if (this.sourceEditor) {
this._getSourceTextAndPrettify().then((newText) => {
this._justSetText = true;
let firstLine = this.sourceEditor.getFirstVisibleLine();
@@ -373,17 +373,17 @@ StyleSheetEditor.prototype = {
/**
* Handles changes to the list of @media rules in the stylesheet.
* Emits 'media-rules-changed' if the list has changed.
*
* @param {array} rules
* Array of MediaRuleFronts for new media rules of sheet.
*/
- _onMediaRulesChanged: function(rules) {
+ _onMediaRulesChanged: function (rules) {
if (!rules.length && !this.mediaRules.length) {
return;
}
for (let rule of this.mediaRules) {
rule.off("matches-change", this._onMediaRuleMatchesChange);
rule.destroy();
}
this.mediaRules = rules;
@@ -392,40 +392,40 @@ StyleSheetEditor.prototype = {
rule.on("matches-change", this._onMediaRuleMatchesChange);
}
this.emit("media-rules-changed", rules);
},
/**
* Forward media-rules-changed event from stylesheet.
*/
- _onMediaRuleMatchesChange: function() {
+ _onMediaRuleMatchesChange: function () {
this.emit("media-rules-changed", this.mediaRules);
},
/**
* Forward error event from stylesheet.
*
* @param {string} event
* Event type
* @param {string} errorCode
*/
- _onError: function(event, data) {
+ _onError: function (event, data) {
this.emit("error", data);
},
/**
* Create source editor and load state into it.
* @param {DOMElement} inputElement
* Element to load source editor in
*
* @return {Promise}
* Promise that will resolve when the style editor is loaded.
*/
- load: function(inputElement) {
+ load: function (inputElement) {
if (this._isDestroyed) {
return promise.reject("Won't load source editor as the style sheet has " +
"already been removed from Style Editor.");
}
this._inputElement = inputElement;
let config = {
@@ -469,75 +469,75 @@ StyleSheetEditor.prototype = {
},
/**
* Get the source editor for this editor.
*
* @return {Promise}
* Promise that will resolve with the editor.
*/
- getSourceEditor: function() {
+ getSourceEditor: function () {
let deferred = promise.defer();
if (this.sourceEditor) {
return promise.resolve(this);
}
this.on("source-editor-load", () => {
deferred.resolve(this);
});
return deferred.promise;
},
/**
* Focus the Style Editor input.
*/
- focus: function() {
+ focus: function () {
if (this.sourceEditor) {
this.sourceEditor.focus();
} else {
this._focusOnSourceEditorReady = true;
}
},
/**
* Event handler for when the editor is shown.
*/
- onShow: function() {
+ onShow: function () {
if (this.sourceEditor) {
// CodeMirror needs refresh to restore scroll position after hiding and
// showing the editor.
this.sourceEditor.refresh();
}
this.focus();
},
/**
* Toggled the disabled state of the underlying stylesheet.
*/
- toggleDisabled: function() {
+ toggleDisabled: function () {
this.styleSheet.toggleDisabled().then(null, Cu.reportError);
},
/**
* Queue a throttled task to update the live style sheet.
*/
- updateStyleSheet: function() {
+ updateStyleSheet: function () {
if (this._updateTask) {
// cancel previous queued task not executed within throttle delay
this._window.clearTimeout(this._updateTask);
}
this._updateTask = this._window.setTimeout(this._updateStyleSheet,
UPDATE_STYLESHEET_DELAY);
},
/**
* Update live style sheet according to modifications.
*/
- _updateStyleSheet: function() {
+ _updateStyleSheet: function () {
if (this.styleSheet.disabled) {
// TODO: do we want to do this?
return;
}
if (this._justSetText) {
this._justSetText = false;
return;
@@ -557,17 +557,17 @@ StyleSheetEditor.prototype = {
this.styleSheet.update(this._state.text, this.transitionsEnabled)
.then(null, Cu.reportError);
},
/**
* Handle mousemove events, calling _highlightSelectorAt after a delay only
* and reseting the delay everytime.
*/
- _onMouseMove: function(e) {
+ _onMouseMove: function (e) {
this.highlighter.hide();
if (this.mouseMoveTimeout) {
this._window.clearTimeout(this.mouseMoveTimeout);
this.mouseMoveTimeout = null;
}
this.mouseMoveTimeout = this._window.setTimeout(() => {
@@ -612,17 +612,17 @@ StyleSheetEditor.prototype = {
* To implement 'Save' instead of 'Save as', you can pass
* savedFile here.
* @param function(nsIFile aFile) callback
* Optional callback called when the operation has finished.
* aFile has the nsIFile object for saved file or null if the operation
* has failed or has been canceled by the user.
* @see savedFile
*/
- saveToFile: function(file, callback) {
+ saveToFile: function (file, callback) {
let onFile = (returnFile) => {
if (!returnFile) {
if (callback) {
callback(null);
}
return;
}
@@ -660,17 +660,17 @@ StyleSheetEditor.prototype = {
}
showFilePicker(file || this._styleSheetFilePath, true, this._window,
onFile, defaultName);
},
/**
* Called when this source has been successfully saved to disk.
*/
- onFileSaved: function(returnFile) {
+ onFileSaved: function (returnFile) {
this._friendlyName = null;
this.savedFile = returnFile;
if (this.sourceEditor) {
this.sourceEditor.setClean();
}
this.emit("property-change");
@@ -684,17 +684,17 @@ StyleSheetEditor.prototype = {
CHECK_LINKED_SHEET_DELAY);
}
},
/**
* Check to see if our linked CSS file has changed on disk, and
* if so, update the live style sheet.
*/
- checkLinkedFileForChanges: function() {
+ checkLinkedFileForChanges: function () {
OS.File.stat(this.linkedCSSFile).then((info) => {
let lastChange = info.lastModificationDate.getTime();
if (this._fileModDate && lastChange != this._fileModDate) {
this._fileModDate = lastChange;
this._modCheckCount = 0;
this.updateLinkedStyleSheet();
@@ -714,46 +714,46 @@ StyleSheetEditor.prototype = {
/**
* Notify that the linked CSS file (if this is an original source)
* doesn't exist on disk in the place we think it does.
*
* @param string error
* The error we got when trying to access the file.
*/
- markLinkedFileBroken: function(error) {
+ markLinkedFileBroken: function (error) {
this.linkedCSSFileError = error || true;
this.emit("linked-css-file-error");
error += " querying " + this.linkedCSSFile +
" original source location: " + this.savedFile.path;
Cu.reportError(error);
},
/**
* For original sources (e.g. Sass files). Fetch contents of linked CSS
* file from disk and live update the stylesheet object with the contents.
*/
- updateLinkedStyleSheet: function() {
+ updateLinkedStyleSheet: function () {
OS.File.read(this.linkedCSSFile).then((array) => {
let decoder = new TextDecoder();
let text = decoder.decode(array);
let relatedSheet = this.styleSheet.relatedStyleSheet;
relatedSheet.update(text, this.transitionsEnabled);
}, this.markLinkedFileBroken);
},
/**
* Retrieve custom key bindings objects as expected by Editor.
* Editor action names are not displayed to the user.
*
* @return {array} key binding objects for the source editor
*/
- _getKeyBindings: function() {
+ _getKeyBindings: function () {
let bindings = {};
let keybind = Editor.accel(getString("saveStyleSheet.commandkey"));
bindings[keybind] = () => {
this.saveToFile(this.savedFile);
};
bindings["Shift-" + keybind] = () => {
@@ -763,17 +763,17 @@ StyleSheetEditor.prototype = {
bindings.Esc = false;
return bindings;
},
/**
* Clean up for this editor.
*/
- destroy: function() {
+ destroy: function () {
if (this._sourceEditor) {
this._sourceEditor.off("dirty-change", this._onPropertyChange);
this._sourceEditor.off("saveRequested", this.saveToFile);
this._sourceEditor.off("change", this.updateStyleSheet);
if (this.highlighter && this.walker && this._sourceEditor.container) {
this._sourceEditor.container.removeEventListener("mousemove",
this._onMouseMove);
}
--- a/devtools/client/styleeditor/styleeditor-commands.js
+++ b/devtools/client/styleeditor/styleeditor-commands.js
@@ -55,17 +55,18 @@ exports.items = [{
returnType: "editArgs",
exec: args => {
return { href: args.resource.name, line: args.line };
}
}, {
item: "converter",
from: "editArgs",
to: "dom",
- exec: function(args, context) {
+ exec: function (args, context) {
let target = context.environment.target;
- return gDevTools.showToolbox(target, "styleeditor").then(function(toolbox) {
+ let toolboxOpened = gDevTools.showToolbox(target, "styleeditor");
+ return toolboxOpened.then(function (toolbox) {
let styleEditor = toolbox.getCurrentPanel();
styleEditor.selectStyleSheet(args.href, args.line);
return null;
});
}
}];
--- a/devtools/client/styleeditor/styleeditor-panel.js
+++ b/devtools/client/styleeditor/styleeditor-panel.js
@@ -79,17 +79,17 @@ StyleEditorPanel.prototype = {
* Show an error message from the style editor in the toolbox
* notification box.
*
* @param {string} event
* Type of event
* @param {string} data
* The parameters to customize the error message
*/
- _showError: function(event, data) {
+ _showError: function (event, data) {
if (!this._toolbox) {
// could get an async error after we've been destroyed
return;
}
let errorMessage = getString(data.key);
if (data.append) {
errorMessage += " " + data.append;
@@ -116,27 +116,27 @@ StyleEditorPanel.prototype = {
* @param {number} line
* Line number to jump to after selecting. One-indexed
* @param {number} col
* Column number to jump to after selecting. One-indexed
* @return {Promise}
* Promise that will resolve when the editor is selected and ready
* to be used.
*/
- selectStyleSheet: function(href, line, col) {
+ selectStyleSheet: function (href, line, col) {
if (!this._debuggee || !this.UI) {
return null;
}
return this.UI.selectStyleSheet(href, line - 1, col ? col - 1 : 0);
},
/**
* Destroy the style editor.
*/
- destroy: function() {
+ destroy: function () {
if (!this._destroyed) {
this._destroyed = true;
this._target.off("close", this.destroy);
this._target = null;
this._toolbox = null;
this._panelWin = null;
this._panelDoc = null;
@@ -147,12 +147,12 @@ StyleEditorPanel.prototype = {
this.UI = null;
}
return promise.resolve(null);
},
};
XPCOMUtils.defineLazyGetter(StyleEditorPanel.prototype, "strings",
- function() {
+ function () {
return Services.strings.createBundle(
"chrome://devtools/locale/styleeditor.properties");
});
--- a/devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_740541_iframes.js
@@ -14,22 +14,22 @@ add_task(function* () {
stylesheets = stylesheets || [];
framedDocuments = framedDocuments || [];
return "data:text/html;charset=UTF-8," + encodeURIComponent(
Array.prototype.concat.call(
["<!DOCTYPE html>",
"<html>",
"<head>",
"<title>Bug 740541</title>"],
- stylesheets.map(function(sheet) {
+ stylesheets.map(function (sheet) {
return '<link rel="stylesheet" type="text/css" href="' + sheet + '">';
}),
["</head>",
"<body>"],
- framedDocuments.map(function(doc) {
+ framedDocuments.map(function (doc) {
return '<iframe src="' + doc + '"></iframe>';
}),
["</body>",
"</html>"]
).join("\n"));
}
const DOCUMENT_WITH_INLINE_STYLE = "data:text/html;charset=UTF-8," +
--- a/devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_bug_851132_middle_click.js
@@ -46,11 +46,11 @@ function* clickOnStyleSheetLink(editor,
info("Pressing button " + button + " on style sheet name link.");
EventUtils.synthesizeMouseAtCenter(link, { button }, window);
}
function onTabAdded() {
ok(false, "middle mouse click has opened a new tab");
}
-registerCleanupFunction(function() {
+registerCleanupFunction(function () {
gBrowser.tabContainer.removeEventListener("TabOpen", onTabAdded, false);
});
--- a/devtools/client/styleeditor/test/browser_styleeditor_filesave.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_filesave.js
@@ -34,17 +34,17 @@ add_task(function* () {
is(editor.sourceEditor.isClean(), false, "Editor is dirty.");
ok(editor.summary.classList.contains("unsaved"),
"Star icon is present in the corresponding summary.");
info("Saving the changes.");
dirty = editor.sourceEditor.once("dirty-change");
- editor.saveToFile(null, function(file) {
+ editor.saveToFile(null, function (file) {
ok(file, "file should get saved directly when using a file:// URI");
});
yield dirty;
is(editor.sourceEditor.isClean(), true, "Editor is clean.");
ok(!editor.summary.classList.contains("unsaved"),
"Star icon is not present in the corresponding summary.");
@@ -83,17 +83,17 @@ function write(data, file, callback) {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
let istream = converter.convertToInputStream(data);
let ostream = FileUtils.openSafeFileOutputStream(file);
- NetUtil.asyncCopy(istream, ostream, function(status) {
+ NetUtil.asyncCopy(istream, ostream, function (status) {
if (!Components.isSuccessCode(status)) {
info("Couldn't write to " + file.path);
return;
}
callback(file);
});
}
--- a/devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_highlight-selector.js
@@ -15,23 +15,23 @@ add_task(function* () {
let editor = ui.editors[0];
// Mock the highlighter so we can locally assert that things happened
// correctly instead of accessing the highlighter elements
editor.highlighter = {
isShown: false,
options: null,
- show: function(node, options) {
+ show: function (node, options) {
this.isShown = true;
this.options = options;
return promise.resolve();
},
- hide: function() {
+ hide: function () {
this.isShown = false;
}
};
info("Expecting a node-highlighted event");
let onHighlighted = editor.once("node-highlighted");
info("Simulate a mousemove event on the div selector");
--- a/devtools/client/styleeditor/test/browser_styleeditor_import.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_import.js
@@ -33,23 +33,23 @@ add_task(function* () {
function importSheet(ui, panelWindow) {
// create file to import first
let file = FileUtils.getFile("ProfD", [FILENAME]);
let ostream = FileUtils.openSafeFileOutputStream(file);
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
let istream = converter.convertToInputStream(SOURCE);
- NetUtil.asyncCopy(istream, ostream, function() {
+ NetUtil.asyncCopy(istream, ostream, function () {
FileUtils.closeSafeFileOutputStream(ostream);
// click the import button now that the file to import is ready
ui._mockImportFile = file;
- waitForFocus(function() {
+ waitForFocus(function () {
let document = panelWindow.document;
let importButton = document.querySelector(".style-editor-importButton");
ok(importButton, "import button exists");
EventUtils.synthesizeMouseAtCenter(importButton, {}, panelWindow);
}, panelWindow);
});
}
--- a/devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_inline_friendly_names.js
@@ -46,17 +46,17 @@ function testIndentifierGeneration(ui) {
}
function saveFirstInlineStyleSheet(ui) {
let deferred = promise.defer();
let editor = ui.editors[0];
let destFile = FileUtils.getFile("ProfD", [SAVE_PATH]);
- editor.saveToFile(destFile, function(file) {
+ editor.saveToFile(destFile, function (file) {
ok(file, "File was correctly saved.");
deferred.resolve();
});
return deferred.promise;
}
function testFriendlyNamesAfterSave(ui) {
--- a/devtools/client/styleeditor/test/browser_styleeditor_new.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_new.js
@@ -28,17 +28,17 @@ add_task(function* () {
function createNew(ui, panelWindow) {
info("Creating a new stylesheet now");
let deferred = promise.defer();
ui.once("editor-added", (ev, editor) => {
editor.getSourceEditor().then(deferred.resolve);
});
- waitForFocus(function() {
+ waitForFocus(function () {
// create a new style sheet
let newButton = panelWindow.document
.querySelector(".style-editor-newButton");
ok(newButton, "'new' button exists");
EventUtils.synthesizeMouseAtCenter(newButton, {}, panelWindow);
}, panelWindow);
@@ -80,17 +80,17 @@ function* testInitialState(editor) {
});
is(color, "rgb(255, 255, 255)",
"content's background color is initially white");
}
function typeInEditor(editor, panelWindow) {
let deferred = promise.defer();
- waitForFocus(function() {
+ waitForFocus(function () {
for (let c of TESTCASE_CSS_SOURCE) {
EventUtils.synthesizeKey(c, {}, panelWindow);
}
ok(editor.unsaved, "new editor has unsaved flag");
deferred.resolve();
}, panelWindow);
--- a/devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_private_perwindowpb.js
@@ -32,25 +32,25 @@ add_task(function* () {
win.close();
});
function checkDiskCacheFor(host) {
let foundPrivateData = false;
let deferred = promise.defer();
Visitor.prototype = {
- onCacheStorageInfo: function(num) {
+ onCacheStorageInfo: function (num) {
info("disk storage contains " + num + " entries");
},
- onCacheEntryInfo: function(uri) {
+ onCacheEntryInfo: function (uri) {
let urispec = uri.asciiSpec;
info(urispec);
foundPrivateData |= urispec.includes(host);
},
- onCacheEntryVisitCompleted: function() {
+ onCacheEntryVisitCompleted: function () {
is(foundPrivateData, false, "web content present in disk cache");
deferred.resolve();
}
};
function Visitor() {}
let storage = cache.diskCacheStorage(LoadContextInfo.default, false);
storage.asyncVisitStorage(new Visitor(),
--- a/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_sourcemap_watching.js
@@ -74,17 +74,17 @@ add_task(function* () {
is(color, "rgb(0, 0, 255)", "div is blue after saving file");
});
function editSCSS(editor) {
let deferred = promise.defer();
editor.sourceEditor.setText(CSS_TEXT);
- editor.saveToFile(null, function(file) {
+ editor.saveToFile(null, function (file) {
ok(file, "Scss file should be saved");
deferred.resolve();
});
return deferred.promise;
}
function editCSSFile(CSSFile) {
@@ -145,17 +145,17 @@ function write(data, file) {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
let istream = converter.convertToInputStream(data);
let ostream = FileUtils.openSafeFileOutputStream(file);
- NetUtil.asyncCopy(istream, ostream, function(status) {
+ NetUtil.asyncCopy(istream, ostream, function (status) {
if (!Components.isSuccessCode(status)) {
info("Coudln't write to " + file.path);
return;
}
deferred.resolve(file);
});
return deferred.promise;
--- a/devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_sv_keynav.js
@@ -26,17 +26,17 @@ add_task(function* () {
function getStylesheetNameLinkFor(editor) {
return editor.summary.querySelector(".stylesheet-name");
}
function testKeyboardNavigation(editor, panel) {
let panelWindow = panel.panelWindow;
let ui = panel.UI;
- waitForFocus(function() {
+ waitForFocus(function () {
let summary = editor.summary;
EventUtils.synthesizeMouseAtCenter(summary, {}, panelWindow);
let item = getStylesheetNameLinkFor(ui.editors[0]);
is(panelWindow.document.activeElement, item,
"editor 0 item is the active element");
EventUtils.synthesizeKey("VK_DOWN", {}, panelWindow);
--- a/devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js
+++ b/devtools/client/styleeditor/test/browser_styleeditor_syncIntoRuleView.js
@@ -31,17 +31,17 @@ add_task(function* () {
let value = getRuleViewPropertyValue(view, "#testid", "color");
is(value, "chartreuse", "check that edits were synced to rule view");
});
function typeInEditor(editor, panelWindow) {
let deferred = promise.defer();
- waitForFocus(function() {
+ waitForFocus(function () {
for (let c of TESTCASE_CSS_SOURCE) {
EventUtils.synthesizeKey(c, {}, panelWindow);
}
ok(editor.unsaved, "new editor has unsaved flag");
deferred.resolve();
}, panelWindow);
--- a/devtools/client/styleeditor/test/head.js
+++ b/devtools/client/styleeditor/test/head.js
@@ -16,17 +16,17 @@ const TEST_BASE_HTTPS = "https://example
const TEST_HOST = "mochi.test:8888";
/**
* 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
* @param {Window} win The window to add the tab to (default: current window).
* @return a promise that resolves to the tab object when the url is loaded
*/
-var addTab = function(url, win) {
+var addTab = function (url, win) {
info("Adding a new tab with URL: '" + url + "'");
let def = promise.defer();
let targetWindow = win || window;
let targetBrowser = targetWindow.gBrowser;
let tab = targetBrowser.selectedTab = targetBrowser.addTab(url);
targetBrowser.selectedBrowser.addEventListener("load", function onload() {
@@ -107,15 +107,15 @@ var openStyleEditorForURL = Task.async(f
* The selector used to obtain the element.
* @param {String} pseudo
* pseudo id to query, or null.
* @param {String} name
* name of the property.
*/
var getComputedStyleProperty = function* (args) {
return yield ContentTask.spawn(gBrowser.selectedBrowser, args,
- function({selector, pseudo, name}) {
+ function ({selector, pseudo, name}) {
let element = content.document.querySelector(selector);
let style = content.getComputedStyle(element, pseudo);
return style.getPropertyValue(name);
}
);
};
--- a/devtools/client/styleeditor/utils.js
+++ b/devtools/client/styleeditor/utils.js
@@ -23,20 +23,20 @@ function PrefObserver(branchName) {
this.branch.addObserver("", this, false);
EventEmitter.decorate(this);
}
exports.PrefObserver = PrefObserver;
PrefObserver.prototype = {
- observe: function(subject, topic, data) {
+ observe: function (subject, topic, data) {
if (topic == "nsPref:changed") {
this.emit(this.branchName + data);
}
},
- destroy: function() {
+ destroy: function () {
if (this.branch) {
this.branch.removeObserver("", this);
}
}
};
--- a/devtools/shared/webconsole/client.js
+++ b/devtools/shared/webconsole/client.js
@@ -79,17 +79,17 @@ WebConsoleClient.prototype = {
* the UI for displaying.
*
* @private
* @param string type
* Message type.
* @param object packet
* The message received from the server.
*/
- _onNetworkEvent: function(type, packet) {
+ _onNetworkEvent: function (type, packet) {
if (packet.from == this._actor) {
let actor = packet.eventActor;
let networkInfo = {
_type: "NetworkEvent",
timeStamp: actor.timeStamp,
node: null,
actor: actor.actor,
discardRequestBody: true,
@@ -119,17 +119,17 @@ WebConsoleClient.prototype = {
* the UI for displaying.
*
* @private
* @param string type
* Message type.
* @param object packet
* The message received from the server.
*/
- _onNetworkEventUpdate: function(type, packet) {
+ _onNetworkEventUpdate: function (type, packet) {
let networkInfo = this.getNetworkRequest(packet.from);
if (!networkInfo) {
return;
}
networkInfo.updates.push(packet.updateType);
switch (packet.updateType) {
@@ -176,34 +176,34 @@ WebConsoleClient.prototype = {
*
* @see this.CACHED_MESSAGES
* @param array types
* The array of message types you want from the server. See
* this.CACHED_MESSAGES for known types.
* @param function onResponse
* The function invoked when the response is received.
*/
- getCachedMessages: function(types, onResponse) {
+ getCachedMessages: function (types, onResponse) {
let packet = {
to: this._actor,
type: "getCachedMessages",
messageTypes: types,
};
this._client.request(packet, onResponse);
},
/**
* Inspect the properties of an object.
*
* @param string actor
* The WebConsoleObjectActor ID to send the request to.
* @param function onResponse
* The function invoked when the response is received.
*/
- inspectObjectProperties: function(actor, onResponse) {
+ inspectObjectProperties: function (actor, onResponse) {
let packet = {
to: actor,
type: "inspectProperties",
};
this._client.request(packet, onResponse);
},
/**
@@ -238,17 +238,17 @@ WebConsoleClient.prototype = {
* "debugger eval code".
*
* - selectedNodeActor: the NodeActor ID of the current
* selection in the Inspector, if such a selection
* exists. This is used by helper functions that can
* reference the currently selected node in the Inspector,
* like $0.
*/
- evaluateJS: function(string, onResponse, options = {}) {
+ evaluateJS: function (string, onResponse, options = {}) {
let packet = {
to: this._actor,
type: "evaluateJS",
text: string,
bindObjectActor: options.bindObjectActor,
frameActor: options.frameActor,
url: options.url,
selectedNodeActor: options.selectedNodeActor,
@@ -256,17 +256,17 @@ WebConsoleClient.prototype = {
};
this._client.request(packet, onResponse);
},
/**
* Evaluate a JavaScript expression asynchronously.
* See evaluateJS for parameter and response information.
*/
- evaluateJSAsync: function(string, onResponse, options = {}) {
+ evaluateJSAsync: function (string, onResponse, options = {}) {
// Pre-37 servers don't support async evaluation.
if (!this.traits.evaluateJSAsync) {
this.evaluateJS(string, onResponse, options);
return;
}
let packet = {
to: this._actor,
@@ -286,17 +286,17 @@ WebConsoleClient.prototype = {
this.pendingEvaluationResults.set(response.resultID, onResponse);
}
});
},
/**
* Handler for the actors's unsolicited evaluationResult packet.
*/
- onEvaluationResult: function(notification, packet) {
+ onEvaluationResult: function (notification, packet) {
// The client on the main thread can receive notification packets from
// multiple webconsole actors: the one on the main thread and the ones
// on worker threads. So make sure we should be handling this request.
if (packet.from !== this._actor) {
return;
}
// Find the associated callback based on this ID, and fire it.
@@ -320,209 +320,209 @@ WebConsoleClient.prototype = {
* The code you want to autocomplete.
* @param number cursor
* Cursor location inside the string. Index starts from 0.
* @param function onResponse
* The function invoked when the response is received.
* @param string frameActor
* The id of the frame actor that made the call.
*/
- autocomplete: function(string, cursor, onResponse, frameActor) {
+ autocomplete: function (string, cursor, onResponse, frameActor) {
let packet = {
to: this._actor,
type: "autocomplete",
text: string,
cursor: cursor,
frameActor: frameActor,
};
this._client.request(packet, onResponse);
},
/**
* Clear the cache of messages (page errors and console API calls).
*/
- clearMessagesCache: function() {
+ clearMessagesCache: function () {
let packet = {
to: this._actor,
type: "clearMessagesCache",
};
this._client.request(packet);
},
/**
* Get Web Console-related preferences on the server.
*
* @param array preferences
* An array with the preferences you want to retrieve.
* @param function [onResponse]
* Optional function to invoke when the response is received.
*/
- getPreferences: function(preferences, onResponse) {
+ getPreferences: function (preferences, onResponse) {
let packet = {
to: this._actor,
type: "getPreferences",
preferences: preferences,
};
this._client.request(packet, onResponse);
},
/**
* Set Web Console-related preferences on the server.
*
* @param object preferences
* An object with the preferences you want to change.
* @param function [onResponse]
* Optional function to invoke when the response is received.
*/
- setPreferences: function(preferences, onResponse) {
+ setPreferences: function (preferences, onResponse) {
let packet = {
to: this._actor,
type: "setPreferences",
preferences: preferences,
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the request headers from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getRequestHeaders: function(actor, onResponse) {
+ getRequestHeaders: function (actor, onResponse) {
let packet = {
to: actor,
type: "getRequestHeaders",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the request cookies from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getRequestCookies: function(actor, onResponse) {
+ getRequestCookies: function (actor, onResponse) {
let packet = {
to: actor,
type: "getRequestCookies",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the request post data from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getRequestPostData: function(actor, onResponse) {
+ getRequestPostData: function (actor, onResponse) {
let packet = {
to: actor,
type: "getRequestPostData",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the response headers from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getResponseHeaders: function(actor, onResponse) {
+ getResponseHeaders: function (actor, onResponse) {
let packet = {
to: actor,
type: "getResponseHeaders",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the response cookies from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getResponseCookies: function(actor, onResponse) {
+ getResponseCookies: function (actor, onResponse) {
let packet = {
to: actor,
type: "getResponseCookies",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the response content from the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getResponseContent: function(actor, onResponse) {
+ getResponseContent: function (actor, onResponse) {
let packet = {
to: actor,
type: "getResponseContent",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the timing information for the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getEventTimings: function(actor, onResponse) {
+ getEventTimings: function (actor, onResponse) {
let packet = {
to: actor,
type: "getEventTimings",
};
this._client.request(packet, onResponse);
},
/**
* Retrieve the security information for the given NetworkEventActor.
*
* @param string actor
* The NetworkEventActor ID.
* @param function onResponse
* The function invoked when the response is received.
*/
- getSecurityInfo: function(actor, onResponse) {
+ getSecurityInfo: function (actor, onResponse) {
let packet = {
to: actor,
type: "getSecurityInfo",
};
this._client.request(packet, onResponse);
},
/**
* Send a HTTP request with the given data.
*
* @param string data
* The details of the HTTP request.
* @param function onResponse
* The function invoked when the response is received.
*/
- sendHTTPRequest: function(data, onResponse) {
+ sendHTTPRequest: function (data, onResponse) {
let packet = {
to: this._actor,
type: "sendHTTPRequest",
request: data
};
this._client.request(packet, onResponse);
},
@@ -531,17 +531,17 @@ WebConsoleClient.prototype = {
*
* @see this.LISTENERS
* @param array listeners
* Array of listeners you want to start. See this.LISTENERS for
* known listeners.
* @param function onResponse
* Function to invoke when the server response is received.
*/
- startListeners: function(listeners, onResponse) {
+ startListeners: function (listeners, onResponse) {
let packet = {
to: this._actor,
type: "startListeners",
listeners: listeners,
};
this._client.request(packet, onResponse);
},
@@ -550,80 +550,80 @@ WebConsoleClient.prototype = {
*
* @see this.LISTENERS
* @param array listeners
* Array of listeners you want to stop. See this.LISTENERS for
* known listeners.
* @param function onResponse
* Function to invoke when the server response is received.
*/
- stopListeners: function(listeners, onResponse) {
+ stopListeners: function (listeners, onResponse) {
let packet = {
to: this._actor,
type: "stopListeners",
listeners: listeners,
};
this._client.request(packet, onResponse);
},
/**
* Return an instance of LongStringClient for the given long string grip.
*
* @param object grip
* The long string grip returned by the protocol.
* @return object
* The LongStringClient for the given long string grip.
*/
- longString: function(grip) {
+ longString: function (grip) {
if (grip.actor in this._longStrings) {
return this._longStrings[grip.actor];
}
let client = new LongStringClient(this._client, grip);
this._longStrings[grip.actor] = client;
return client;
},
/**
* Close the WebConsoleClient. This stops all the listeners on the server and
* detaches from the console actor.
*
* @param function onResponse
* Function to invoke when the server response is received.
*/
- detach: function(onResponse) {
+ detach: function (onResponse) {
this._client.removeListener("evaluationResult", this.onEvaluationResult);
this._client.removeListener("networkEvent", this.onNetworkEvent);
this._client.removeListener("networkEventUpdate",
this.onNetworkEventUpdate);
this.stopListeners(null, onResponse);
this._longStrings = null;
this._client = null;
this.pendingEvaluationResults.clear();
this.pendingEvaluationResults = null;
this.clearNetworkRequests();
this._networkRequests = null;
},
- clearNetworkRequests: function() {
+ clearNetworkRequests: function () {
this._networkRequests.clear();
},
/**
* Fetches the full text of a LongString.
*
* @param object | string stringGrip
* The long string grip containing the corresponding actor.
* If you pass in a plain string (by accident or because you're lazy),
* then a promise of the same string is simply returned.
* @return object Promise
* A promise that is resolved when the full string contents
* are available, or rejected if something goes wrong.
*/
- getString: function(stringGrip) {
+ getString: function (stringGrip) {
// Make sure this is a long string.
if (typeof stringGrip != "object" || stringGrip.type != "longString") {
// Go home string, you're drunk.
return promise.resolve(stringGrip);
}
// Fetch the long string only once.
if (stringGrip._fullText) {
--- a/devtools/shared/webconsole/js-property-provider.js
+++ b/devtools/shared/webconsole/js-property-provider.js
@@ -457,67 +457,67 @@ function getExactMatchImpl(obj, name, {c
var JSObjectSupport = {
chainIterator: function* (obj) {
while (obj) {
yield obj;
obj = Object.getPrototypeOf(obj);
}
},
- getProperties: function(obj) {
+ getProperties: function (obj) {
return Object.getOwnPropertyNames(obj);
},
- getProperty: function() {
+ getProperty: function () {
// getProperty is unsafe with raw JS objects.
throw new Error("Unimplemented!");
},
};
var DebuggerObjectSupport = {
chainIterator: function* (obj) {
while (obj) {
yield obj;
obj = obj.proto;
}
},
- getProperties: function(obj) {
+ getProperties: function (obj) {
return obj.getOwnPropertyNames();
},
- getProperty: function(obj, name, rootObj) {
+ getProperty: function (obj, name, rootObj) {
// This is left unimplemented in favor to DevToolsUtils.getProperty().
throw new Error("Unimplemented!");
},
};
var DebuggerEnvironmentSupport = {
chainIterator: function* (obj) {
while (obj) {
yield obj;
obj = obj.parent;
}
},
- getProperties: function(obj) {
+ getProperties: function (obj) {
let names = obj.names();
// Include 'this' in results (in sorted order)
for (let i = 0; i < names.length; i++) {
if (i === names.length - 1 || names[i + 1] > "this") {
names.splice(i + 1, 0, "this");
break;
}
}
return names;
},
- getProperty: function(obj, name) {
+ getProperty: function (obj, name) {
let result;
// Try/catch since name can be anything, and getVariable throws if
// it's not a valid ECMAScript identifier name
try {
// TODO: we should use getVariableDescriptor() here - bug 725815.
result = obj.getVariable(name);
} catch (e) {
// Ignore.
--- a/devtools/shared/webconsole/network-helper.js
+++ b/devtools/shared/webconsole/network-helper.js
@@ -79,17 +79,17 @@ var NetworkHelper = {
*
* @param string text
* Text to convert.
* @param string charset
* Charset to convert the text to.
* @returns string
* Converted text.
*/
- convertToUnicode: function(text, charset) {
+ convertToUnicode: function (text, charset) {
let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
try {
conv.charset = charset || "UTF-8";
return conv.ConvertToUnicode(text);
} catch (ex) {
return text;
}
@@ -98,17 +98,17 @@ var NetworkHelper = {
/**
* Reads all available bytes from stream and converts them to charset.
*
* @param nsIInputStream stream
* @param string charset
* @returns string
* UTF-16 encoded string based on the content of stream and charset.
*/
- readAndConvertFromStream: function(stream, charset) {
+ readAndConvertFromStream: function (stream, charset) {
let text = null;
try {
text = NetUtil.readInputStreamToString(stream, stream.available());
return this.convertToUnicode(text, charset);
} catch (err) {
return text;
}
},
@@ -118,17 +118,17 @@ var NetworkHelper = {
*
* @param nsIHttpChannel request
* @param string charset
* The content document charset, used when reading the POSTed data.
* @returns string or null
* Returns the posted string if it was possible to read from request
* otherwise null.
*/
- readPostTextFromRequest: function(request, charset) {
+ readPostTextFromRequest: function (request, charset) {
if (request instanceof Ci.nsIUploadChannel) {
let iStream = request.uploadStream;
let isSeekableStream = false;
if (iStream instanceof Ci.nsISeekableStream) {
isSeekableStream = true;
}
@@ -156,32 +156,32 @@ var NetworkHelper = {
* Reads the posted text from the page's cache.
*
* @param nsIDocShell docShell
* @param string charset
* @returns string or null
* Returns the posted string if it was possible to read from
* docShell otherwise null.
*/
- readPostTextFromPage: function(docShell, charset) {
+ readPostTextFromPage: function (docShell, charset) {
let webNav = docShell.QueryInterface(Ci.nsIWebNavigation);
return this.readPostTextFromPageViaWebNav(webNav, charset);
},
/**
* Reads the posted text from the page's cache, given an nsIWebNavigation
* object.
*
* @param nsIWebNavigation webNav
* @param string charset
* @returns string or null
* Returns the posted string if it was possible to read from
* webNav, otherwise null.
*/
- readPostTextFromPageViaWebNav: function(webNav, charset) {
+ readPostTextFromPageViaWebNav: function (webNav, charset) {
if (webNav instanceof Ci.nsIWebPageDescriptor) {
let descriptor = webNav.currentDescriptor;
if (descriptor instanceof Ci.nsISHEntry && descriptor.postData &&
descriptor instanceof Ci.nsISeekableStream) {
descriptor.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
return this.readAndConvertFromStream(descriptor, charset);
@@ -192,17 +192,17 @@ var NetworkHelper = {
/**
* Gets the web appId that is associated with request.
*
* @param nsIHttpChannel request
* @returns number|null
* The appId for the given request, if available.
*/
- getAppIdForRequest: function(request) {
+ getAppIdForRequest: function (request) {
try {
return this.getRequestLoadContext(request).appId;
} catch (ex) {
// request loadContent is not always available.
}
return null;
},
@@ -210,48 +210,48 @@ var NetworkHelper = {
* Gets the topFrameElement that is associated with request. This
* works in single-process and multiprocess contexts. It may cross
* the content/chrome boundary.
*
* @param nsIHttpChannel request
* @returns nsIDOMElement|null
* The top frame element for the given request.
*/
- getTopFrameForRequest: function(request) {
+ getTopFrameForRequest: function (request) {
try {
return this.getRequestLoadContext(request).topFrameElement;
} catch (ex) {
// request loadContent is not always available.
}
return null;
},
/**
* Gets the nsIDOMWindow that is associated with request.
*
* @param nsIHttpChannel request
* @returns nsIDOMWindow or null
*/
- getWindowForRequest: function(request) {
+ getWindowForRequest: function (request) {
try {
return this.getRequestLoadContext(request).associatedWindow;
} catch (ex) {
// TODO: bug 802246 - getWindowForRequest() throws on b2g: there is no
// associatedWindow property.
}
return null;
},
/**
* Gets the nsILoadContext that is associated with request.
*
* @param nsIHttpChannel request
* @returns nsILoadContext or null
*/
- getRequestLoadContext: function(request) {
+ getRequestLoadContext: function (request) {
try {
return request.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex) {
// Ignore.
}
try {
return request.loadGroup.notificationCallbacks
@@ -264,17 +264,17 @@ var NetworkHelper = {
},
/**
* Determines whether the request has been made for the top level document.
*
* @param nsIHttpChannel request
* @returns Boolean True if the request represents the top level document.
*/
- isTopLevelLoad: function(request) {
+ isTopLevelLoad: function (request) {
if (request instanceof Ci.nsIChannel) {
let loadInfo = request.loadInfo;
if (loadInfo && loadInfo.parentOuterWindowID == loadInfo.outerWindowID) {
return (request.loadFlags & Ci.nsIChannel.LOAD_DOCUMENT_URI);
}
}
return false;
@@ -287,17 +287,17 @@ var NetworkHelper = {
* URL to load the cached content for.
* @param string charset
* Assumed charset of the cached content. Used if there is no charset
* on the channel directly.
* @param function callback
* Callback that is called with the loaded cached content if available
* or null if something failed while getting the cached content.
*/
- loadFromCache: function(url, charset, callback) {
+ loadFromCache: function (url, charset, callback) {
let channel = NetUtil.newChannel({uri: url,
loadUsingSystemPrincipal: true});
// Ensure that we only read from the cache and not the server.
channel.loadFlags = Ci.nsIRequest.LOAD_FROM_CACHE |
Ci.nsICachingChannel.LOAD_ONLY_FROM_CACHE |
Ci.nsICachingChannel.LOAD_BYPASS_LOCAL_CACHE_IF_BUSY;
@@ -323,21 +323,21 @@ var NetworkHelper = {
* Parse a raw Cookie header value.
*
* @param string header
* The raw Cookie header value.
* @return array
* Array holding an object for each cookie. Each object holds the
* following properties: name and value.
*/
- parseCookieHeader: function(header) {
+ parseCookieHeader: function (header) {
let cookies = header.split(";");
let result = [];
- cookies.forEach(function(cookie) {
+ cookies.forEach(function (cookie) {
let equal = cookie.indexOf("=");
let name = cookie.substr(0, equal);
let value = cookie.substr(equal + 1);
result.push({name: unescape(name.trim()),
value: unescape(value.trim())});
});
return result;
@@ -348,29 +348,29 @@ var NetworkHelper = {
*
* @param string header
* The raw Set-Cookie header value.
* @return array
* Array holding an object for each cookie. Each object holds the
* following properties: name, value, secure (boolean), httpOnly
* (boolean), path, domain and expires (ISO date string).
*/
- parseSetCookieHeader: function(header) {
+ parseSetCookieHeader: function (header) {
let rawCookies = header.split(/\r\n|\n|\r/);
let cookies = [];
- rawCookies.forEach(function(cookie) {
+ rawCookies.forEach(function (cookie) {
let equal = cookie.indexOf("=");
let name = unescape(cookie.substr(0, equal).trim());
let parts = cookie.substr(equal + 1).split(";");
let value = unescape(parts.shift().trim());
cookie = {name: name, value: value};
- parts.forEach(function(part) {
+ parts.forEach(function (part) {
part = part.trim();
if (part.toLowerCase() == "secure") {
cookie.secure = true;
} else if (part.toLowerCase() == "httponly") {
cookie.httpOnly = true;
} else if (part.indexOf("=") > -1) {
let pair = part.split("=");
pair[0] = pair[0].toLowerCase();
@@ -469,17 +469,17 @@ var NetworkHelper = {
},
/**
* Check if the given MIME type is a text-only MIME type.
*
* @param string mimeType
* @return boolean
*/
- isTextMimeType: function(mimeType) {
+ isTextMimeType: function (mimeType) {
if (mimeType.indexOf("text/") == 0) {
return true;
}
// XML and JSON often come with custom MIME types, so in addition to the
// standard "application/xml" and "application/json", we also look for
// variants like "application/x-bigcorp+xml". For JSON we allow "+json" and
// "-json" as suffixes.
@@ -532,17 +532,17 @@ var NetworkHelper = {
* See parseCertificateInfo for the contents.
* - hsts: true if host uses Strict Transport Security,
* false otherwise
* - hpkp: true if host uses Public Key Pinning, false otherwise
* If state == weak: Same as state == secure and
* - weaknessReasons: list of reasons that cause the request to be
* considered weak. See getReasonsForWeakness.
*/
- parseSecurityInfo: function(securityInfo, httpActivity) {
+ parseSecurityInfo: function (securityInfo, httpActivity) {
const info = {
state: "insecure",
};
// The request did not contain any security info.
if (!securityInfo) {
return info;
}
@@ -666,17 +666,17 @@ var NetworkHelper = {
* An object with following format:
* {
* subject: { commonName, organization, organizationalUnit },
* issuer: { commonName, organization, organizationUnit },
* validity: { start, end },
* fingerprint: { sha1, sha256 }
* }
*/
- parseCertificateInfo: function(cert) {
+ parseCertificateInfo: function (cert) {
let info = {};
if (cert) {
info.subject = {
commonName: cert.commonName,
organization: cert.organization,
organizationalUnit: cert.organizationalUnit,
};
@@ -708,17 +708,17 @@ var NetworkHelper = {
* description.
*
* @param Number version
* One of nsISSLStatus version constants.
* @return string
* One of TLSv1, TLSv1.1, TLSv1.2 if @param version is valid,
* Unknown otherwise.
*/
- formatSecurityProtocol: function(version) {
+ formatSecurityProtocol: function (version) {
switch (version) {
case Ci.nsISSLStatus.TLS_VERSION_1:
return "TLSv1";
case Ci.nsISSLStatus.TLS_VERSION_1_1:
return "TLSv1.1";
case Ci.nsISSLStatus.TLS_VERSION_1_2:
return "TLSv1.2";
default:
@@ -734,17 +734,17 @@ var NetworkHelper = {
*
* @param Number state
* nsITransportSecurityInfo.securityState.
*
* @return Array[String]
* List of weakness reasons. A subset of { cipher } where
* * cipher: The cipher suite is consireded to be weak (RC4).
*/
- getReasonsForWeakness: function(state) {
+ getReasonsForWeakness: function (state) {
const wpl = Ci.nsIWebProgressListener;
// If there's non-fatal security issues the request has STATE_IS_BROKEN
// flag set. See http://hg.mozilla.org/mozilla-central/file/44344099d119
// /security/manager/ssl/nsNSSCallbacks.cpp#l1233
let reasons = [];
if (state & wpl.STATE_IS_BROKEN) {
@@ -766,17 +766,17 @@ var NetworkHelper = {
/**
* Parse a url's query string into its components
*
* @param string queryString
* The query part of a url
* @return array
* Array of query params {name, value}
*/
- parseQueryString: function(queryString) {
+ parseQueryString: function (queryString) {
// Make sure there's at least one param available.
// Be careful here, params don't necessarily need to have values, so
// no need to verify the existence of a "=".
if (!queryString) {
return null;
}
// Turn the params string into an array containing { name: value } tuples.
@@ -791,17 +791,17 @@ var NetworkHelper = {
});
return paramsArray;
},
/**
* Helper for getting an nsIURL instance out of a string.
*/
- nsIURL: function(url, store = gNSURLStore) {
+ nsIURL: function (url, store = gNSURLStore) {
if (store.has(url)) {
return store.get(url);
}
let uri = Services.io.newURI(url, null, null).QueryInterface(Ci.nsIURL);
store.set(url, uri);
return uri;
}
--- a/devtools/shared/webconsole/network-monitor.js
+++ b/devtools/shared/webconsole/network-monitor.js
@@ -161,17 +161,17 @@ NetworkResponseListener.prototype = {
* @param nsIAsyncInputStream stream
* The input stream from where we are waiting for data to come in.
* @param nsIInputStreamCallback listener
* The input stream callback you want. This is an object that must have
* the onInputStreamReady() method. If the argument is null, then the
* current callback is removed.
* @return void
*/
- setAsyncListener: function(stream, listener) {
+ setAsyncListener: function (stream, listener) {
// Asynchronously wait for the stream to be readable or closed.
stream.asyncWait(listener, 0, 0, Services.tm.mainThread);
},
/**
* Stores the received data, if request/response body logging is enabled. It
* also does limit the number of stored bytes, based on the
* RESPONSE_BODY_LIMIT constant.
@@ -180,17 +180,17 @@ NetworkResponseListener.prototype = {
* https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIStreamListener
*
* @param nsIRequest request
* @param nsISupports context
* @param nsIInputStream inputStream
* @param unsigned long offset
* @param unsigned long count
*/
- onDataAvailable: function(request, context, inputStream, offset, count) {
+ onDataAvailable: function (request, context, inputStream, offset, count) {
this._findOpenResponse();
let data = NetUtil.readInputStreamToString(inputStream, count);
this.bodySize += count;
if (!this.httpActivity.discardResponseBody &&
this.receivedData.length < RESPONSE_BODY_LIMIT) {
this.receivedData +=
@@ -200,17 +200,17 @@ NetworkResponseListener.prototype = {
/**
* See documentation at
* https://developer.mozilla.org/En/NsIRequestObserver
*
* @param nsIRequest request
* @param nsISupports context
*/
- onStartRequest: function(request) {
+ onStartRequest: function (request) {
// Converter will call this again, we should just ignore that.
if (this.request) {
return;
}
this.request = request;
this._getSecurityInfo();
this._findOpenResponse();
@@ -250,65 +250,65 @@ NetworkResponseListener.prototype = {
}
// Asynchronously wait for the data coming from the request.
this.setAsyncListener(this.sink.inputStream, this);
},
/**
* Parse security state of this request and report it to the client.
*/
- _getSecurityInfo: DevToolsUtils.makeInfallible(function() {
+ _getSecurityInfo: DevToolsUtils.makeInfallible(function () {
// Take the security information from the original nsIHTTPChannel instead of
// the nsIRequest received in onStartRequest. If response to this request
// was a redirect from http to https, the request object seems to contain
// security info for the https request after redirect.
let secinfo = this.httpActivity.channel.securityInfo;
let info = NetworkHelper.parseSecurityInfo(secinfo, this.httpActivity);
this.httpActivity.owner.addSecurityInfo(info);
}),
/**
* Handle the onStopRequest by closing the sink output stream.
*
* For more documentation about nsIRequestObserver go to:
* https://developer.mozilla.org/En/NsIRequestObserver
*/
- onStopRequest: function() {
+ onStopRequest: function () {
this._findOpenResponse();
this.sink.outputStream.close();
},
// nsIProgressEventSink implementation
/**
* Handle progress event as data is transferred. This is used to record the
* size on the wire, which may be compressed / encoded.
*/
- onProgress: function(request, context, progress, progressMax) {
+ onProgress: function (request, context, progress, progressMax) {
this.transferredSize = progress;
// Need to forward as well to keep things like Download Manager's progress
// bar working properly.
this._forwardNotification(Ci.nsIProgressEventSink, "onProgress", arguments);
},
- onStatus: function() {
+ onStatus: function () {
this._forwardNotification(Ci.nsIProgressEventSink, "onStatus", arguments);
},
/**
* Find the open response object associated to the current request. The
* NetworkMonitor._httpResponseExaminer() method saves the response headers in
* NetworkMonitor.openResponses. This method takes the data from the open
* response object and puts it into the HTTP activity object, then sends it to
* the remote Web Console instance.
*
* @private
*/
- _findOpenResponse: function() {
+ _findOpenResponse: function () {
if (!this.owner || this._foundOpenResponse) {
return;
}
let openResponse = null;
for (let id in this.owner.openResponses) {
let item = this.owner.openResponses[id];
@@ -330,17 +330,17 @@ NetworkResponseListener.prototype = {
},
/**
* Clean up the response listener once the response input stream is closed.
* This is called from onStopRequest() or from onInputStreamReady() when the
* stream is closed.
* @return void
*/
- onStreamClose: function() {
+ onStreamClose: function () {
if (!this.httpActivity) {
return;
}
// Remove our listener from the request input stream.
this.setAsyncListener(this.sink.inputStream, null);
this._findOpenResponse();
@@ -360,17 +360,17 @@ NetworkResponseListener.prototype = {
/**
* Handler for when the response completes. This function cleans up the
* response listener.
*
* @param string [data]
* Optional, the received data coming from the response listener or
* from the cache.
*/
- _onComplete: function(data) {
+ _onComplete: function (data) {
let response = {
mimeType: "",
text: data || "",
};
response.size = response.text.length;
response.transferredSize = this.transferredSize;
@@ -415,17 +415,17 @@ NetworkResponseListener.prototype = {
/**
* The nsIInputStreamCallback for when the request input stream is ready -
* either it has more data or it is closed.
*
* @param nsIAsyncInputStream stream
* The sink input stream from which data is coming.
* @returns void
*/
- onInputStreamReady: function(stream) {
+ onInputStreamReady: function (stream) {
if (!(stream instanceof Ci.nsIAsyncInputStream) || !this.httpActivity) {
return;
}
let available = -1;
try {
// This may throw if the stream is closed normally or due to an error.
available = stream.available();
@@ -540,17 +540,17 @@ NetworkMonitor.prototype = {
/**
* Object that holds response headers coming from this._httpResponseExaminer.
*/
openResponses: null,
/**
* The network monitor initializer.
*/
- init: function() {
+ init: function () {
this.responsePipeSegmentSize = Services.prefs
.getIntPref("network.buffer.cache.size");
this.interceptedChannels = new Set();
if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
gActivityDistributor.addObserver(this);
Services.obs.addObserver(this._httpResponseExaminer,
"http-on-examine-response", false);
@@ -558,17 +558,17 @@ NetworkMonitor.prototype = {
"http-on-examine-cached-response", false);
}
// In child processes, only watch for service worker requests
// everything else only happens in the parent process
Services.obs.addObserver(this._serviceWorkerRequest,
"service-worker-synthesized-response", false);
},
- _serviceWorkerRequest: function(subject, topic, data) {
+ _serviceWorkerRequest: function (subject, topic, data) {
let channel = subject.QueryInterface(Ci.nsIHttpChannel);
if (!this._matchRequest(channel)) {
return;
}
this.interceptedChannels.add(subject);
@@ -582,17 +582,17 @@ NetworkMonitor.prototype = {
* Observe notifications for the http-on-examine-response topic, coming from
* the nsIObserverService.
*
* @private
* @param nsIHttpChannel subject
* @param string topic
* @returns void
*/
- _httpResponseExaminer: function(subject, topic) {
+ _httpResponseExaminer: function (subject, topic) {
// The httpResponseExaminer is used to retrieve the uncached response
// headers. The data retrieved is stored in openResponses. The
// NetworkResponseListener is responsible with updating the httpActivity
// object with the data from the new object in openResponses.
if (!this.owner ||
(topic != "http-on-examine-response" &&
topic != "http-on-examine-cached-response") ||
@@ -611,17 +611,17 @@ NetworkMonitor.prototype = {
channel: channel,
headers: [],
cookies: [],
};
let setCookieHeader = null;
channel.visitResponseHeaders({
- visitHeader: function(name, value) {
+ visitHeader: function (name, value) {
let lowerName = name.toLowerCase();
if (lowerName == "set-cookie") {
setCookieHeader = value;
}
response.headers.push({ name: name, value: value });
}
});
@@ -685,17 +685,17 @@ NetworkMonitor.prototype = {
* @param nsIHttpChannel channel
* @param number activityType
* @param number activitySubtype
* @param number timestamp
* @param number extraSizeData
* @param string extraStringData
*/
observeActivity:
- DevToolsUtils.makeInfallible(function(channel, activityType, activitySubtype,
+ DevToolsUtils.makeInfallible(function (channel, activityType, activitySubtype,
timestamp, extraSizeData,
extraStringData) {
if (!this.owner ||
activityType != gActivityDistributor.ACTIVITY_TYPE_HTTP_TRANSACTION &&
activityType != gActivityDistributor.ACTIVITY_TYPE_SOCKET_TRANSPORT) {
return;
}
@@ -761,17 +761,17 @@ NetworkMonitor.prototype = {
* instance based on the current filters.
*
* @private
* @param nsIHttpChannel channel
* Request to check.
* @return boolean
* True if the network request should be logged, false otherwise.
*/
- _matchRequest: function(channel) {
+ _matchRequest: function (channel) {
if (this._logEverything) {
return true;
}
// Ignore requests from chrome or add-on code when we are monitoring
// content.
// TODO: one particular test (browser_styleeditor_fetch-from-cache.js) needs
// the DevToolsUtils.testing check. We will move to a better way to serve
@@ -832,17 +832,17 @@ NetworkMonitor.prototype = {
}
return false;
},
/**
*
*/
- _createNetworkEvent: function(channel, { timestamp, extraStringData,
+ _createNetworkEvent: function (channel, { timestamp, extraStringData,
fromCache, fromServiceWorker }) {
let win = NetworkHelper.getWindowForRequest(channel);
let httpActivity = this.createActivityObject(channel);
// see _onRequestBodySent()
httpActivity.charset = win ? win.document.characterSet : null;
channel.QueryInterface(Ci.nsIPrivateBrowsingChannel);
@@ -891,17 +891,17 @@ NetworkMonitor.prototype = {
event.discardResponseBody = !this.saveRequestAndResponseBodies;
let headers = [];
let cookies = [];
let cookieHeader = null;
// Copy the request header data.
channel.visitRequestHeaders({
- visitHeader: function(name, value) {
+ visitHeader: function (name, value) {
if (name == "Cookie") {
cookieHeader = value;
}
headers.push({ name: name, value: value });
}
});
if (cookieHeader) {
@@ -926,17 +926,17 @@ NetworkMonitor.prototype = {
* collected through its lifetime.
*
* @private
* @param nsIHttpChannel channel
* @param number timestamp
* @param string extraStringData
* @return void
*/
- _onRequestHeader: function(channel, timestamp, extraStringData) {
+ _onRequestHeader: function (channel, timestamp, extraStringData) {
if (!this._matchRequest(channel)) {
return;
}
this._createNetworkEvent(channel, { timestamp: timestamp,
extraStringData: extraStringData });
},
@@ -948,17 +948,17 @@ NetworkMonitor.prototype = {
* this point.
*
* @see http://www.softwareishard.com/blog/har-12-spec
* @param nsIHttpChannel channel
* The HTTP channel for which the HTTP activity object is created.
* @return object
* The new HTTP activity object.
*/
- createActivityObject: function(channel) {
+ createActivityObject: function (channel) {
return {
id: gSequenceId(),
channel: channel,
// see _onRequestHeader()
charset: null,
url: channel.URI.spec,
// needed for host specific security info
hostname: channel.URI.host,
@@ -976,17 +976,17 @@ NetworkMonitor.prototype = {
/**
* Setup the network response listener for the given HTTP activity. The
* NetworkResponseListener is responsible for storing the response body.
*
* @private
* @param object httpActivity
* The HTTP activity object we are tracking.
*/
- _setupResponseListener: function(httpActivity) {
+ _setupResponseListener: function (httpActivity) {
let channel = httpActivity.channel;
channel.QueryInterface(Ci.nsITraceableChannel);
// The response will be written into the outputStream of this pipe.
// This allows us to buffer the data we are receiving and read it
// asynchronously.
// Both ends of the pipe must be blocking.
let sink = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
@@ -1013,17 +1013,17 @@ NetworkMonitor.prototype = {
/**
* Handler for ACTIVITY_SUBTYPE_REQUEST_BODY_SENT. The request body is logged
* here.
*
* @private
* @param object httpActivity
* The HTTP activity object we are working with.
*/
- _onRequestBodySent: function(httpActivity) {
+ _onRequestBodySent: function (httpActivity) {
if (httpActivity.discardRequestBody) {
return;
}
let sentBody = NetworkHelper.readPostTextFromRequest(httpActivity.channel,
httpActivity.charset);
if (!sentBody && this.window &&
@@ -1051,17 +1051,17 @@ NetworkMonitor.prototype = {
* information about the response headers.
*
* @private
* @param object httpActivity
* The HTTP activity object we are working with.
* @param string extraStringData
* The uncached response headers.
*/
- _onResponseHeader: function(httpActivity, extraStringData) {
+ _onResponseHeader: function (httpActivity, extraStringData) {
// extraStringData contains the uncached response headers. The first line
// contains the response status (e.g. HTTP/1.1 200 OK).
//
// Note: The response header is not saved here. Calling the
// channel.visitResponseHeaders() method at this point sometimes causes an
// NS_ERROR_NOT_AVAILABLE exception.
//
// We could parse extraStringData to get the headers and their values, but
@@ -1101,17 +1101,17 @@ NetworkMonitor.prototype = {
* Handler for ACTIVITY_SUBTYPE_TRANSACTION_CLOSE. This method updates the HAR
* timing information on the HTTP activity object and clears the request
* from the list of known open requests.
*
* @private
* @param object httpActivity
* The HTTP activity object we work with.
*/
- _onTransactionClose: function(httpActivity) {
+ _onTransactionClose: function (httpActivity) {
let result = this._setupHarTimings(httpActivity);
httpActivity.owner.addEventTimings(result.total, result.timings);
delete this.openRequests[httpActivity.id];
},
/**
* Update the HTTP activity object to include timing information as in the HAR
* spec. The HTTP activity object holds the raw timing information in
@@ -1123,17 +1123,17 @@ NetworkMonitor.prototype = {
* The HTTP activity object we are working with.
* @param boolean fromCache
* Indicates that the result was returned from the browser cache
* @return object
* This object holds two properties:
* - total - the total time for all of the request and response.
* - timings - the HAR timings object.
*/
- _setupHarTimings: function(httpActivity, fromCache) {
+ _setupHarTimings: function (httpActivity, fromCache) {
if (fromCache) {
// If it came from the browser cache, we have no timing
// information and these should all be 0
return {
total: 0,
timings: {
blocked: 0,
dns: 0,
@@ -1206,17 +1206,17 @@ NetworkMonitor.prototype = {
timings: harTimings,
};
},
/**
* Suspend Web Console activity. This is called when all Web Consoles are
* closed.
*/
- destroy: function() {
+ destroy: function () {
if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
gActivityDistributor.removeObserver(this);
Services.obs.removeObserver(this._httpResponseExaminer,
"http-on-examine-response");
Services.obs.removeObserver(this._httpResponseExaminer,
"http-on-examine-cached-response");
}
@@ -1283,17 +1283,17 @@ NetworkMonitorChild.prototype = {
appId: this.appId,
action: "setPreferences",
preferences: {
saveRequestAndResponseBodies: this._saveRequestAndResponseBodies,
},
});
},
- init: function() {
+ init: function () {
let mm = this._messageManager;
mm.addMessageListener("debug:netmonitor:" + this.connID + ":newEvent",
this._onNewEvent);
mm.addMessageListener("debug:netmonitor:" + this.connID + ":updateEvent",
this._onUpdateEvent);
mm.sendAsyncMessage("debug:netmonitor:" + this.connID, {
appId: this.appId,
action: "start",
@@ -1318,17 +1318,17 @@ NetworkMonitorChild.prototype = {
if (!(method in actor)) {
Cu.reportError("Received debug:netmonitor:updateEvent unsupported " +
"method: " + method);
return;
}
actor[method].apply(actor, args);
}),
- destroy: function() {
+ destroy: function () {
let mm = this._messageManager;
try {
mm.removeMessageListener("debug:netmonitor:" + this.connID + ":newEvent",
this._onNewEvent);
mm.removeMessageListener("debug:netmonitor:" + this.connID +
":updateEvent",
this._onUpdateEvent);
} catch (e) {
@@ -1363,18 +1363,18 @@ NetworkMonitorChild.prototype = {
*/
function NetworkEventActorProxy(messageManager, connID) {
this.id = gSequenceId();
this.connID = connID;
this.messageManager = messageManager;
}
exports.NetworkEventActorProxy = NetworkEventActorProxy;
-NetworkEventActorProxy.methodFactory = function(method) {
- return DevToolsUtils.makeInfallible(function() {
+NetworkEventActorProxy.methodFactory = function (method) {
+ return DevToolsUtils.makeInfallible(function () {
let args = Array.slice(arguments);
let mm = this.messageManager;
mm.sendAsyncMessage("debug:netmonitor:" + this.connID + ":updateEvent", {
id: this.id,
method: method,
args: args,
});
}, "NetworkEventActorProxy." + method);
@@ -1385,27 +1385,27 @@ NetworkEventActorProxy.prototype = {
* Initialize the network event. This method sends the network request event
* to the content process.
*
* @param object event
* Object describing the network request.
* @return object
* This object.
*/
- init: DevToolsUtils.makeInfallible(function(event) {
+ init: DevToolsUtils.makeInfallible(function (event) {
let mm = this.messageManager;
mm.sendAsyncMessage("debug:netmonitor:" + this.connID + ":newEvent", {
id: this.id,
event: event,
});
return this;
}),
};
-(function() {
+(function () {
// Listeners for new network event data coming from the NetworkMonitor.
let methods = ["addRequestHeaders", "addRequestCookies", "addRequestPostData",
"addResponseStart", "addSecurityInfo", "addResponseHeaders",
"addResponseCookies", "addResponseContent", "addEventTimings"];
let factory = NetworkEventActorProxy.methodFactory;
for (let method of methods) {
NetworkEventActorProxy.prototype[method] = factory(method);
}
@@ -1442,17 +1442,17 @@ NetworkMonitorManager.prototype = {
/**
* Handler for "debug:monitor" messages received through the message manager
* from the content process.
*
* @param object msg
* Message from the content.
*/
- onNetMonitorMessage: DevToolsUtils.makeInfallible(function(msg) {
+ onNetMonitorMessage: DevToolsUtils.makeInfallible(function (msg) {
let { action, appId } = msg.json;
// Pipe network monitor data from parent to child via the message manager.
switch (action) {
case "start":
if (!this.netMonitor) {
this.netMonitor = new NetworkMonitor({
topFrame: this.frame,
appId: appId,
@@ -1493,17 +1493,17 @@ NetworkMonitorManager.prototype = {
* @return object
* A NetworkEventActorProxy instance which is notified when further
* data about the request is available.
*/
onNetworkEvent: DevToolsUtils.makeInfallible(function _onNetworkEvent(event) {
return new NetworkEventActorProxy(this.messageManager, this.id).init(event);
}),
- destroy: function() {
+ destroy: function () {
if (this.messageManager) {
this.messageManager.removeMessageListener("debug:netmonitor:" + this.id,
this.onNetMonitorMessage);
}
this.messageManager = null;
this.filters = null;
if (this.netMonitor) {
@@ -1571,17 +1571,17 @@ ConsoleProgressListener.prototype = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference]),
/**
* Initialize the ConsoleProgressListener.
* @private
*/
- _init: function() {
+ _init: function () {
if (this._initialized) {
return;
}
this._webProgress = this.window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIWebProgress);
this._webProgress.addProgressListener(this,
@@ -1596,17 +1596,17 @@ ConsoleProgressListener.prototype = {
*
* @param number monitor
* Tells what you want to track. Available constants:
* - this.MONITOR_FILE_ACTIVITY
* Track file loads.
* - this.MONITOR_LOCATION_CHANGE
* Track location changes for the top window.
*/
- startMonitor: function(monitor) {
+ startMonitor: function (monitor) {
switch (monitor) {
case this.MONITOR_FILE_ACTIVITY:
this._fileActivity = true;
break;
case this.MONITOR_LOCATION_CHANGE:
this._locationChange = true;
break;
default:
@@ -1618,17 +1618,17 @@ ConsoleProgressListener.prototype = {
/**
* Stop a monitor.
*
* @param number monitor
* Tells what you want to stop tracking. See this.startMonitor() for
* the list of constants.
*/
- stopMonitor: function(monitor) {
+ stopMonitor: function (monitor) {
switch (monitor) {
case this.MONITOR_FILE_ACTIVITY:
this._fileActivity = false;
break;
case this.MONITOR_LOCATION_CHANGE:
this._locationChange = false;
break;
default:
@@ -1636,17 +1636,17 @@ ConsoleProgressListener.prototype = {
monitor + "!");
}
if (!this._fileActivity && !this._locationChange) {
this.destroy();
}
},
- onStateChange: function(progress, request, state, status) {
+ onStateChange: function (progress, request, state, status) {
if (!this.owner) {
return;
}
if (this._fileActivity) {
this._checkFileActivity(progress, request, state, status);
}
@@ -1656,17 +1656,17 @@ ConsoleProgressListener.prototype = {
},
/**
* Check if there is any file load, given the arguments of
* nsIWebProgressListener.onStateChange. If the state change tells that a file
* URI has been loaded, then the remote Web Console instance is notified.
* @private
*/
- _checkFileActivity: function(progress, request, state, status) {
+ _checkFileActivity: function (progress, request, state, status) {
if (!(state & Ci.nsIWebProgressListener.STATE_START)) {
return;
}
let uri = null;
if (request instanceof Ci.imgIRequest) {
let imgIRequest = request.QueryInterface(Ci.imgIRequest);
uri = imgIRequest.URI;
@@ -1683,17 +1683,17 @@ ConsoleProgressListener.prototype = {
},
/**
* Check if the current window.top location is changing, given the arguments
* of nsIWebProgressListener.onStateChange. If that is the case, the remote
* Web Console instance is notified.
* @private
*/
- _checkLocationChange: function(progress, request, state) {
+ _checkLocationChange: function (progress, request, state) {
let isStart = state & Ci.nsIWebProgressListener.STATE_START;
let isStop = state & Ci.nsIWebProgressListener.STATE_STOP;
let isNetwork = state & Ci.nsIWebProgressListener.STATE_IS_NETWORK;
let isWindow = state & Ci.nsIWebProgressListener.STATE_IS_WINDOW;
// Skip non-interesting states.
if (!isNetwork || !isWindow || progress.DOMWindow != this.window) {
return;
@@ -1702,25 +1702,25 @@ ConsoleProgressListener.prototype = {
if (isStart && request instanceof Ci.nsIChannel) {
this.owner.onLocationChange("start", request.URI.spec, "");
} else if (isStop) {
this.owner.onLocationChange("stop", this.window.location.href,
this.window.document.title);
}
},
- onLocationChange: function() {},
- onStatusChange: function() {},
- onProgressChange: function() {},
- onSecurityChange: function() {},
+ onLocationChange: function () {},
+ onStatusChange: function () {},
+ onProgressChange: function () {},
+ onSecurityChange: function () {},
/**
* Destroy the ConsoleProgressListener.
*/
- destroy: function() {
+ destroy: function () {
if (!this._initialized) {
return;
}
this._initialized = false;
this._fileActivity = false;
this._locationChange = false;
--- a/devtools/shared/webconsole/server-logger-monitor.js
+++ b/devtools/shared/webconsole/server-logger-monitor.js
@@ -11,17 +11,17 @@ const Services = require("Services");
const {DebuggerServer} = require("devtools/server/main");
const {makeInfallible} = require("devtools/shared/DevToolsUtils");
loader.lazyGetter(this, "NetworkHelper", () => require("devtools/shared/webconsole/network-helper"));
// Helper tracer. Should be generic sharable by other modules (bug 1171927)
const trace = {
- log: function(...args) {
+ log: function (...args) {
}
};
const acceptableHeaders = ["x-chromelogger-data"];
/**
* This object represents HTTP events observer. It's intended to be
* used in e10s enabled browser only.
@@ -34,31 +34,31 @@ const acceptableHeaders = ["x-chromelogg
* forwards it into the right child process.
*
* Read more about the architecture:
* https://github.com/mozilla/gecko-dev/blob/fx-team/devtools/server/docs/actor-e10s-handling.md
*/
var ServerLoggerMonitor = {
// Initialization
- initialize: function() {
+ initialize: function () {
this.onChildMessage = this.onChildMessage.bind(this);
this.onDisconnectChild = this.onDisconnectChild.bind(this);
this.onExamineResponse = this.onExamineResponse.bind(this);
// Set of tracked message managers.
this.messageManagers = new Set();
// Set of registered child frames (loggers).
this.targets = new Set();
},
// Parent Child Relationship
- attach: makeInfallible(function({mm, prefix}) {
+ attach: makeInfallible(function ({mm, prefix}) {
let size = this.messageManagers.size;
trace.log("ServerLoggerMonitor.attach; ", size, arguments);
if (this.messageManagers.has(mm)) {
return;
}
@@ -68,59 +68,59 @@ var ServerLoggerMonitor = {
// living in the child process.
mm.addMessageListener("debug:server-logger", this.onChildMessage);
// Listen to the disconnection message to clean-up.
DebuggerServer.once("disconnected-from-child:" + prefix,
this.onDisconnectChild);
}),
- detach: function(mm) {
+ detach: function (mm) {
let size = this.messageManagers.size;
trace.log("ServerLoggerMonitor.detach; ", size);
// Unregister message listeners
mm.removeMessageListener("debug:server-logger", this.onChildMessage);
},
- onDisconnectChild: function(event, mm) {
+ onDisconnectChild: function (event, mm) {
let size = this.messageManagers.size;
trace.log("ServerLoggerMonitor.onDisconnectChild; ",
size, arguments);
if (!this.messageManagers.has(mm)) {
return;
}
this.detach(mm);
this.messageManagers.delete(mm);
},
// Child Message Handling
- onChildMessage: function(msg) {
+ onChildMessage: function (msg) {
let method = msg.data.method;
trace.log("ServerLoggerMonitor.onChildMessage; ", method, msg);
switch (method) {
case "attachChild":
return this.onAttachChild(msg);
case "detachChild":
return this.onDetachChild(msg);
default:
trace.log("Unknown method name: ", method);
return undefined;
}
},
- onAttachChild: function(event) {
+ onAttachChild: function (event) {
let target = event.target;
let size = this.targets.size;
trace.log("ServerLoggerMonitor.onAttachChild; size: ", size, target);
// If this is the first child attached, register global HTTP observer.
if (!size) {
trace.log("ServerLoggerMonitor.onAttatchChild; Add HTTP Observer");
@@ -128,17 +128,17 @@ var ServerLoggerMonitor = {
"http-on-examine-response", false);
}
// Collect child loggers. The frame element where the
// window/document lives.
this.targets.add(target);
},
- onDetachChild: function(event) {
+ onDetachChild: function (event) {
let target = event.target;
this.targets.delete(target);
let size = this.targets.size;
trace.log("ServerLoggerMonitor.onDetachChild; size: ", size, target);
// If this is the last child process attached, unregister
// the global HTTP observer.
@@ -146,17 +146,17 @@ var ServerLoggerMonitor = {
trace.log("ServerLoggerMonitor.onDetachChild; Remove HTTP Observer");
Services.obs.removeObserver(this.onExamineResponse,
"http-on-examine-response", false);
}
},
// HTTP Observer
- onExamineResponse: makeInfallible(function(subject, topic) {
+ onExamineResponse: makeInfallible(function (subject, topic) {
let httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
trace.log("ServerLoggerMonitor.onExamineResponse; ", httpChannel.name,
this.targets);
// Ignore requests from chrome or add-on code when we are monitoring
// content.
if (!httpChannel.loadInfo &&
--- a/devtools/shared/webconsole/server-logger.js
+++ b/devtools/shared/webconsole/server-logger.js
@@ -12,17 +12,17 @@ const Services = require("Services");
const {DebuggerServer} = require("devtools/server/main");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
loader.lazyGetter(this, "NetworkHelper", () => require("devtools/shared/webconsole/network-helper"));
// Helper tracer. Should be generic sharable by other modules (bug 1171927)
const trace = {
- log: function() {
+ log: function () {
}
};
// Constants
const makeInfallible = DevToolsUtils.makeInfallible;
const acceptableHeaders = ["x-chromelogger-data"];
/**
@@ -42,45 +42,45 @@ var ServerLoggingListener = Class({
* process is registering a listener for "http-on-examine-response" event.
*
* @param {Object} win (nsIDOMWindow):
* filter network requests by the associated window object.
* If null (i.e. in the browser context) log everything
* @param {Object} owner
* The {@WebConsoleActor} instance
*/
- initialize: function(win, owner) {
+ initialize: function (win, owner) {
trace.log("ServerLoggingListener.initialize; ", owner.actorID,
", child process: ", DebuggerServer.isInChildProcess);
this.owner = owner;
this.window = win;
this.onExamineResponse = this.onExamineResponse.bind(this);
this.onExamineHeaders = this.onExamineHeaders.bind(this);
this.onParentMessage = this.onParentMessage.bind(this);
this.attach();
},
/**
* The destroy is called by the parent WebConsoleActor actor.
*/
- destroy: function() {
+ destroy: function () {
trace.log("ServerLoggingListener.destroy; ", this.owner.actorID,
", child process: ", DebuggerServer.isInChildProcess);
this.detach();
},
/**
* The main responsibility of this method is registering a listener for
* "http-on-examine-response" events.
*/
- attach: makeInfallible(function() {
+ attach: makeInfallible(function () {
trace.log("ServerLoggingListener.attach; child process: ",
DebuggerServer.isInChildProcess);
// Setup the child <-> parent communication if this actor module
// is running in a child process. If e10s is disabled (this actor
// running in the same process as everything else) register observer
// listener just like in good old pre e10s days.
if (DebuggerServer.isInChildProcess) {
@@ -89,30 +89,30 @@ var ServerLoggingListener = Class({
Services.obs.addObserver(this.onExamineResponse,
"http-on-examine-response", false);
}
}),
/**
* Remove the "http-on-examine-response" listener.
*/
- detach: makeInfallible(function() {
+ detach: makeInfallible(function () {
trace.log("ServerLoggingListener.detach; ", this.owner.actorID);
if (DebuggerServer.isInChildProcess) {
this.detachParentProcess();
} else {
Services.obs.removeObserver(this.onExamineResponse,
"http-on-examine-response", false);
}
}),
// Parent Child Relationship
- attachParentProcess: function() {
+ attachParentProcess: function () {
trace.log("ServerLoggingListener.attachParentProcess;");
this.owner.conn.setupInParent({
module: "devtools/shared/webconsole/server-logger-monitor",
setupParent: "setupParentProcess"
});
let mm = this.owner.conn.parentMessageManager;
@@ -125,30 +125,30 @@ var ServerLoggingListener = Class({
addMessageListener("debug:server-logger", this.onParentMessage);
// Attach to the {@ServerLoggerMonitor} object to subscribe events.
sendSyncMessage("debug:server-logger", {
method: "attachChild"
});
},
- detachParentProcess: makeInfallible(function() {
+ detachParentProcess: makeInfallible(function () {
trace.log("ServerLoggingListener.detachParentProcess;");
let mm = this.owner.conn.parentMessageManager;
let { removeMessageListener, sendSyncMessage } = mm;
sendSyncMessage("debug:server-logger", {
method: "detachChild",
});
removeMessageListener("debug:server-logger", this.onParentMessage);
}),
- onParentMessage: makeInfallible(function(msg) {
+ onParentMessage: makeInfallible(function (msg) {
if (!msg.data) {
return;
}
let method = msg.data.method;
trace.log("ServerLogger.onParentMessage; ", method, msg.data);
switch (method) {
@@ -157,17 +157,17 @@ var ServerLoggingListener = Class({
break;
default:
trace.log("Unknown method name: ", method);
}
}),
// HTTP Observer
- onExamineHeaders: function(event) {
+ onExamineHeaders: function (event) {
let headers = event.data.headers;
trace.log("ServerLoggingListener.onExamineHeaders;", headers);
let parsedMessages = [];
for (let item of headers) {
let header = item.header;
@@ -183,17 +183,17 @@ var ServerLoggingListener = Class({
return;
}
for (let message of parsedMessages) {
this.sendMessage(message);
}
},
- onExamineResponse: makeInfallible(function(subject) {
+ onExamineResponse: makeInfallible(function (subject) {
let httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
trace.log("ServerLoggingListener.onExamineResponse; ", httpChannel.name,
", ", this.owner.actorID, httpChannel);
if (!this._matchRequest(httpChannel)) {
trace.log("ServerLoggerMonitor.onExamineResponse; No matching request!");
return;
@@ -220,17 +220,17 @@ var ServerLoggingListener = Class({
* instance based on the current filters.
*
* @private
* @param nsIHttpChannel channel
* Request to check.
* @return boolean
* True if the network request should be logged, false otherwise.
*/
- _matchRequest: function(channel) {
+ _matchRequest: function (channel) {
trace.log("_matchRequest ", this.window, ", ", this.topFrame);
// Log everything if the window is null (it's null in the browser context)
if (!this.window) {
return true;
}
// Ignore requests from chrome or add-on code when we are monitoring
@@ -260,17 +260,17 @@ var ServerLoggingListener = Class({
// Server Logs
/**
* Search through HTTP headers to catch all server side logs.
* Learn more about the data structure:
* https://craig.is/writing/chrome-logger/techspecs
*/
- parse: function(header, value) {
+ parse: function (header, value) {
let data;
try {
let result = decodeURIComponent(escape(atob(value)));
data = JSON.parse(result);
} catch (err) {
Cu.reportError("Failed to parse HTTP log data! " + err);
return null;
@@ -317,45 +317,45 @@ var ServerLoggingListener = Class({
location: location,
type: type
});
}
return parsedMessage;
},
- parseBacktrace: function(backtrace) {
+ parseBacktrace: function (backtrace) {
if (!backtrace) {
return null;
}
let result = backtrace.match(/\s*(\d+)$/);
if (!result || result.length < 2) {
return backtrace;
}
return {
url: backtrace.slice(0, -result[0].length),
line: result[1]
};
},
- getColumnMap: function(data) {
+ getColumnMap: function (data) {
let columnMap = new Map();
let columnName;
for (let key in data.columns) {
columnName = data.columns[key];
columnMap.set(columnName, key);
}
return columnMap;
},
- sendMessage: function(msg) {
+ sendMessage: function (msg) {
trace.log("ServerLoggingListener.sendMessage; message", msg);
let formatted = format(msg);
trace.log("ServerLoggingListener.sendMessage; formatted", formatted);
let win = this.window;
let innerID = win ? getInnerId(win) : null;
let location = msg.location;
--- a/devtools/shared/webconsole/utils.js
+++ b/devtools/shared/webconsole/utils.js
@@ -41,30 +41,30 @@ const CONSOLE_WORKER_IDS = exports.CONSO
var WebConsoleUtils = {
/**
* Wrap a string in an nsISupportsString object.
*
* @param string string
* @return nsISupportsString
*/
- supportsString: function(string) {
+ supportsString: function (string) {
let str = Cc["@mozilla.org/supports-string;1"]
.createInstance(Ci.nsISupportsString);
str.data = string;
return str;
},
/**
* Given a message, return one of CONSOLE_WORKER_IDS if it matches
* one of those.
*
* @return string
*/
- getWorkerType: function(message) {
+ getWorkerType: function (message) {
let id = message ? message.innerID : null;
return CONSOLE_WORKER_IDS[CONSOLE_WORKER_IDS.indexOf(id)] || null;
},
/**
* Clone an object.
*
* @param object object
@@ -75,26 +75,26 @@ var WebConsoleUtils = {
* @param function [filter]
* Optional, filter function, called for every property. Three
* arguments are passed: key, value and object. Return true if the
* property should be added to the cloned object. Return false to skip
* the property.
* @return object
* The cloned object.
*/
- cloneObject: function(object, recursive, filter) {
+ cloneObject: function (object, recursive, filter) {
if (typeof object != "object") {
return object;
}
let temp;
if (Array.isArray(object)) {
temp = [];
- Array.forEach(object, function(value, index) {
+ Array.forEach(object, function (value, index) {
if (!filter || filter(index, value, object)) {
temp.push(recursive ? WebConsoleUtils.cloneObject(value) : value);
}
});
} else {
temp = {};
for (let key in object) {
let value = object[key];
@@ -111,46 +111,46 @@ var WebConsoleUtils = {
/**
* Copies certain style attributes from one element to another.
*
* @param nsIDOMNode from
* The target node.
* @param nsIDOMNode to
* The destination node.
*/
- copyTextStyles: function(from, to) {
+ copyTextStyles: function (from, to) {
let win = from.ownerDocument.defaultView;
let style = win.getComputedStyle(from);
to.style.fontFamily = style.getPropertyCSSValue("font-family").cssText;
to.style.fontSize = style.getPropertyCSSValue("font-size").cssText;
to.style.fontWeight = style.getPropertyCSSValue("font-weight").cssText;
to.style.fontStyle = style.getPropertyCSSValue("font-style").cssText;
},
/**
* Gets the ID of the inner window of this DOM window.
*
* @param nsIDOMWindow window
* @return integer
* Inner ID for the given window.
*/
- getInnerWindowId: function(window) {
+ getInnerWindowId: function (window) {
return window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils).currentInnerWindowID;
},
/**
* Recursively gather a list of inner window ids given a
* top level window.
*
* @param nsIDOMWindow window
* @return Array
* list of inner window ids.
*/
- getInnerWindowIDsForFrames: function(window) {
+ getInnerWindowIDsForFrames: function (window) {
let innerWindowID = this.getInnerWindowId(window);
let ids = [innerWindowID];
if (window.frames) {
for (let i = 0; i < window.frames.length; i++) {
let frame = window.frames[i];
ids = ids.concat(this.getInnerWindowIDsForFrames(frame));
}
@@ -161,45 +161,45 @@ var WebConsoleUtils = {
/**
* Gets the ID of the outer window of this DOM window.
*
* @param nsIDOMWindow window
* @return integer
* Outer ID for the given window.
*/
- getOuterWindowId: function(window) {
+ getOuterWindowId: function (window) {
return window.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
},
/**
* Tells if the given function is native or not.
*
* @param function func
* The function you want to check if it is native or not.
* @return boolean
* True if the given function is native, false otherwise.
*/
- isNativeFunction: function(func) {
+ isNativeFunction: function (func) {
return typeof func == "function" && !("prototype" in func);
},
/**
* Tells if the given property of the provided object is a
* non-native getter or not.
*
* @param object object
* The object that contains the property.
* @param string prop
* The property you want to check if it is a getter or not.
* @return boolean
* True if the given property is a getter, false otherwise.
*/
- isNonNativeGetter: function(object, prop) {
+ isNonNativeGetter: function (object, prop) {
if (typeof object != "object") {
return false;
}
let desc = this.getPropertyDescriptor(object, prop);
return desc && desc.get && !this.isNativeFunction(desc.get);
},
/**
@@ -207,17 +207,17 @@ var WebConsoleUtils = {
*
* @param object object
* The object that contains the property.
* @param string prop
* The property you want to get the descriptor for.
* @return object
* Property descriptor.
*/
- getPropertyDescriptor: function(object, prop) {
+ getPropertyDescriptor: function (object, prop) {
let desc = null;
while (object) {
try {
if ((desc = Object.getOwnPropertyDescriptor(object, prop))) {
break;
}
} catch (ex) {
// Native getters throw here. See bug 520882.
@@ -248,17 +248,17 @@ var WebConsoleUtils = {
* Property descriptor.
* @param object b
* Property descriptor.
* @return integer
* -1 if a.name < b.name,
* 1 if a.name > b.name,
* 0 otherwise.
*/
- propertiesSort: function(a, b) {
+ propertiesSort: function (a, b) {
// Convert the pair.name to a number for later sorting.
let number = parseFloat(a.name);
let bNumber = parseFloat(b.name);
// Sort numbers, then string.
if (!isNaN(number) && isNaN(bNumber)) {
return -1;
} else if (isNaN(number) && !isNaN(bNumber)) {
@@ -281,17 +281,17 @@ var WebConsoleUtils = {
* The value you want to create a grip for, before sending it to the
* client.
* @param function objectWrapper
* If the value is an object then the objectWrapper function is
* invoked to give us an object grip. See this.getObjectGrip().
* @return mixed
* The value grip.
*/
- createValueGrip: function(value, objectWrapper) {
+ createValueGrip: function (value, objectWrapper) {
switch (typeof value) {
case "boolean":
return value;
case "string":
return objectWrapper(value);
case "number":
if (value === Infinity) {
return { type: "Infinity" };
@@ -323,17 +323,17 @@ var WebConsoleUtils = {
* Check if the given object is an iterator or a generator.
*
* @param object object
* The object you want to check.
* @return boolean
* True if the given object is an iterator or a generator, otherwise
* false is returned.
*/
- isIteratorOrGenerator: function(object) {
+ isIteratorOrGenerator: function (object) {
if (object === null) {
return false;
}
if (typeof object == "object") {
if (typeof object.__iterator__ == "function" ||
object.constructor && object.constructor.name == "Iterator") {
return true;
@@ -359,17 +359,17 @@ var WebConsoleUtils = {
*
* @param string request
* Location of the requested content.
* @param string location
* Location of the current page.
* @return boolean
* True if the content is mixed, false if not.
*/
- isMixedHTTPSRequest: function(request, location) {
+ isMixedHTTPSRequest: function (request, location) {
try {
let requestURI = Services.io.newURI(request, null, null);
let contentURI = Services.io.newURI(location, null, null);
return (contentURI.scheme == "https" && requestURI.scheme != "https");
} catch (ex) {
return false;
}
},
@@ -377,17 +377,17 @@ var WebConsoleUtils = {
/**
* Helper function to deduce the name of the provided function.
*
* @param funtion function
* The function whose name will be returned.
* @return string
* Function name.
*/
- getFunctionName: function(func) {
+ getFunctionName: function (func) {
let name = null;
if (func.name) {
name = func.name;
} else {
let desc;
try {
desc = func.getOwnPropertyDescriptor("displayName");
} catch (ex) {
@@ -412,17 +412,17 @@ var WebConsoleUtils = {
* Get the object class name. For example, the |window| object has the Window
* class name (based on [object Window]).
*
* @param object object
* The object you want to get the class name for.
* @return string
* The object class name.
*/
- getObjectClassName: function(object) {
+ getObjectClassName: function (object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
let type = typeof object;
@@ -452,17 +452,17 @@ var WebConsoleUtils = {
/**
* Check if the given value is a grip with an actor.
*
* @param mixed grip
* Value you want to check if it is a grip with an actor.
* @return boolean
* True if the given value is a grip with an actor.
*/
- isActorGrip: function(grip) {
+ isActorGrip: function (grip) {
return grip && typeof (grip) == "object" && grip.actor;
},
/**
* Value of devtools.selfxss.count preference
*
* @type number
* @private
@@ -488,33 +488,33 @@ var WebConsoleUtils = {
* The inputNode "paste" event handler generator. Helps prevent
* self-xss attacks
*
* @param nsIDOMElement inputField
* @param nsIDOMElement notificationBox
* @returns A function to be added as a handler to 'paste' and
*'drop' events on the input field
*/
- pasteHandlerGen: function(inputField, notificationBox, msg, okstring) {
- let handler = function(event) {
+ pasteHandlerGen: function (inputField, notificationBox, msg, okstring) {
+ let handler = function (event) {
if (WebConsoleUtils.usageCount >= CONSOLE_ENTRY_THRESHOLD) {
inputField.removeEventListener("paste", handler);
inputField.removeEventListener("drop", handler);
return true;
}
if (notificationBox.getNotificationWithValue("selfxss-notification")) {
event.preventDefault();
event.stopPropagation();
return false;
}
let notification = notificationBox.appendNotification(msg,
"selfxss-notification", null,
notificationBox.PRIORITY_WARNING_HIGH, null,
- function(eventType) {
+ function (eventType) {
// Cleanup function if notification is dismissed
if (eventType == "removed") {
inputField.removeEventListener("keyup", pasteKeyUpHandler);
}
});
function pasteKeyUpHandler(event2) {
let value = inputField.value || inputField.textContent;
@@ -535,17 +535,17 @@ var WebConsoleUtils = {
};
exports.Utils = WebConsoleUtils;
// ////////////////////////////////////////////////////////////////////////
// Localization
// ////////////////////////////////////////////////////////////////////////
-WebConsoleUtils.L10n = function(bundleURI) {
+WebConsoleUtils.L10n = function (bundleURI) {
this._bundleUri = bundleURI;
};
WebConsoleUtils.L10n.prototype = {
_stringBundle: null,
get stringBundle() {
if (!this._stringBundle) {
@@ -558,34 +558,34 @@ WebConsoleUtils.L10n.prototype = {
* Generates a formatted timestamp string for displaying in console messages.
*
* @param integer [milliseconds]
* Optional, allows you to specify the timestamp in milliseconds since
* the UNIX epoch.
* @return string
* The timestamp formatted for display.
*/
- timestampString: function(milliseconds) {
+ timestampString: function (milliseconds) {
let d = new Date(milliseconds ? milliseconds : null);
let hours = d.getHours(), minutes = d.getMinutes();
let seconds = d.getSeconds();
milliseconds = d.getMilliseconds();
let parameters = [hours, minutes, seconds, milliseconds];
return this.getFormatStr("timestampFormat", parameters);
},
/**
* Retrieve a localized string.
*
* @param string name
* The string name you want from the Web Console string bundle.
* @return string
* The localized string.
*/
- getStr: function(name) {
+ getStr: function (name) {
let result;
try {
result = this.stringBundle.GetStringFromName(name);
} catch (ex) {
Cu.reportError("Failed to get string: " + name);
throw ex;
}
return result;
@@ -597,17 +597,17 @@ WebConsoleUtils.L10n.prototype = {
*
* @param string name
* The string name you want from the Web Console string bundle.
* @param array array
* The array of values you want in the formatted string.
* @return string
* The formatted local string.
*/
- getFormatStr: function(name, array) {
+ getFormatStr: function (name, array) {
let result;
try {
result = this.stringBundle.formatStringFromName(name, array,
array.length);
} catch (ex) {
Cu.reportError("Failed to format string: " + name);
throw ex;
}
@@ -652,29 +652,29 @@ ConsoleServiceListener.prototype =
* The listener object which is notified of messages from the console service.
* @type object
*/
listener: null,
/**
* Initialize the nsIConsoleService listener.
*/
- init: function() {
+ init: function () {
Services.console.registerListener(this);
},
/**
* The nsIConsoleService observer. This method takes all the script error
* messages belonging to the current window and sends them to the remote Web
* Console instance.
*
* @param nsIConsoleMessage message
* The message object coming from the nsIConsoleService.
*/
- observe: function(message) {
+ observe: function (message) {
if (!this.listener) {
return;
}
if (this.window) {
if (!(message instanceof Ci.nsIScriptError) ||
!message.outerWindowID ||
!this.isCategoryAllowed(message.category)) {
@@ -694,17 +694,17 @@ ConsoleServiceListener.prototype =
* Check if the given message category is allowed to be tracked or not.
* We ignore chrome-originating errors as we only care about content.
*
* @param string category
* The message category you want to check.
* @return boolean
* True if the category is allowed to be logged, false otherwise.
*/
- isCategoryAllowed: function(category) {
+ isCategoryAllowed: function (category) {
if (!category) {
return false;
}
switch (category) {
case "XPConnect JavaScript":
case "component javascript":
case "chrome javascript":
@@ -724,17 +724,17 @@ ConsoleServiceListener.prototype =
*
* @param boolean [includePrivate=false]
* Tells if you want to also retrieve messages coming from private
* windows. Defaults to false.
* @return array
* The array of cached messages. Each element is an nsIScriptError or
* an nsIConsoleMessage
*/
- getCachedMessages: function(includePrivate = false) {
+ getCachedMessages: function (includePrivate = false) {
let errors = Services.console.getMessageArray() || [];
// if !this.window, we're in a browser console. Still need to filter
// private messages.
if (!this.window) {
return errors.filter((error) => {
if (error instanceof Ci.nsIScriptError) {
if (!includePrivate && error.isFromPrivateWindow) {
@@ -766,17 +766,17 @@ ConsoleServiceListener.prototype =
return true;
});
},
/**
* Remove the nsIConsoleService listener.
*/
- destroy: function() {
+ destroy: function () {
Services.console.unregisterListener(this);
this.listener = this.window = null;
},
};
// /////////////////////////////////////////////////////////////////////////////
// The window.console API observer
// /////////////////////////////////////////////////////////////////////////////
@@ -829,32 +829,32 @@ ConsoleAPIListener.prototype =
* The addonId that we listen for. If not null then only messages from this
* console will be returned.
*/
addonId: null,
/**
* Initialize the window.console API observer.
*/
- init: function() {
+ init: function () {
// Note that the observer is process-wide. We will filter the messages as
// needed, see CAL_observe().
Services.obs.addObserver(this, "console-api-log-event", false);
},
/**
* The console API message observer. When messages are received from the
* observer service we forward them to the remote Web Console instance.
*
* @param object message
* The message object receives from the observer service.
* @param string topic
* The message topic received from the observer service.
*/
- observe: function(message, topic) {
+ observe: function (message, topic) {
if (!this.owner) {
return;
}
// Here, wrappedJSObject is not a security wrapper but a property defined
// by the XPCOM component which allows us to unwrap the XPCOM interface and
// access the underlying JSObject.
let apiMessage = message.wrappedJSObject;
@@ -870,17 +870,17 @@ ConsoleAPIListener.prototype =
* Given a message, return true if this window should show it and false
* if it should be ignored.
*
* @param message
* The message from the Storage Service
* @return bool
* Do we care about this message?
*/
- isMessageRelevant: function(message) {
+ isMessageRelevant: function (message) {
let workerType = WebConsoleUtils.getWorkerType(message);
if (this.window && workerType === "ServiceWorker") {
// For messages from Service Workers, message.ID is the
// scope, which can be used to determine whether it's controlling
// a window.
let scope = message.ID;
@@ -926,17 +926,17 @@ ConsoleAPIListener.prototype =
* Get the cached messages for the current inner window and its (i)frames.
*
* @param boolean [includePrivate=false]
* Tells if you want to also retrieve messages coming from private
* windows. Defaults to false.
* @return array
* The array of cached messages.
*/
- getCachedMessages: function(includePrivate = false) {
+ getCachedMessages: function (includePrivate = false) {
let messages = [];
let ConsoleAPIStorage = Cc["@mozilla.org/consoleAPI-storage;1"]
.getService(Ci.nsIConsoleAPIStorage);
// if !this.window, we're in a browser console. Retrieve all events
// for filtering based on privacy.
if (!this.window) {
messages = ConsoleAPIStorage.getEvents();
@@ -960,17 +960,17 @@ ConsoleAPIListener.prototype =
}
return messages.filter((m) => !m.private);
},
/**
* Destroy the console API listener.
*/
- destroy: function() {
+ destroy: function () {
Services.obs.removeObserver(this, "console-api-log-event");
this.window = this.owner = null;
},
};
/**
* WebConsole commands manager.
*
@@ -984,17 +984,17 @@ var WebConsoleCommands = {
/**
* @private
* Reserved for built-in commands. To register a command from the code of an
* add-on, see WebConsoleCommands.register instead.
*
* @see WebConsoleCommands.register
*/
- _registerOriginal: function(name, command) {
+ _registerOriginal: function (name, command) {
this.register(name, command);
this._originalCommands.set(name, this.getCommand(name));
},
/**
* Register a new command.
* @param {string} name The command name (exemple: "$")
* @param {(function|object)} command The command to register.
@@ -1016,54 +1016,54 @@ var WebConsoleCommands = {
* });
*
* WebConsoleCommands.register("$0", {
* get: function(owner) {
* return owner.makeDebuggeeValue(owner.selectedNode);
* }
* });
*/
- register: function(name, command) {
+ register: function (name, command) {
this._registeredCommands.set(name, command);
},
/**
* Unregister a command.
*
* If the command being unregister overrode a built-in command,
* the latter is restored.
*
* @param {string} name The name of the command
*/
- unregister: function(name) {
+ unregister: function (name) {
this._registeredCommands.delete(name);
if (this._originalCommands.has(name)) {
this.register(name, this._originalCommands.get(name));
}
},
/**
* Returns a command by its name.
*
* @param {string} name The name of the command.
*
* @return {(function|object)} The command.
*/
- getCommand: function(name) {
+ getCommand: function (name) {
return this._registeredCommands.get(name);
},
/**
* Returns true if a command is registered with the given name.
*
* @param {string} name The name of the command.
*
* @return {boolean} True if the command is registered.
*/
- hasCommand: function(name) {
+ hasCommand: function (name) {
return this._registeredCommands.has(name);
},
};
exports.WebConsoleCommands = WebConsoleCommands;
/*
* Built-in commands.
@@ -1075,29 +1075,29 @@ exports.WebConsoleCommands = WebConsoleC
/**
* Find a node by ID.
*
* @param string id
* The ID of the element you want.
* @return nsIDOMNode or null
* The result of calling document.querySelector(selector).
*/
-WebConsoleCommands._registerOriginal("$", function(owner, selector) {
+WebConsoleCommands._registerOriginal("$", function (owner, selector) {
return owner.window.document.querySelector(selector);
});
/**
* Find the nodes matching a CSS selector.
*
* @param string selector
* A string that is passed to window.document.querySelectorAll.
* @return nsIDOMNodeList
* Returns the result of document.querySelectorAll(selector).
*/
-WebConsoleCommands._registerOriginal("$$", function(owner, selector) {
+WebConsoleCommands._registerOriginal("$$", function (owner, selector) {
let nodes = owner.window.document.querySelectorAll(selector);
// Calling owner.window.Array.from() doesn't work without accessing the
// wrappedJSObject, so just loop through the results instead.
let result = new owner.window.Array();
for (let i = 0; i < nodes.length; i++) {
result.push(nodes[i]);
}
@@ -1106,31 +1106,31 @@ WebConsoleCommands._registerOriginal("$$
/**
* Returns the result of the last console input evaluation
*
* @return object|undefined
* Returns last console evaluation or undefined
*/
WebConsoleCommands._registerOriginal("$_", {
- get: function(owner) {
+ get: function (owner) {
return owner.consoleActor.getLastConsoleInputEvaluation();
}
});
/**
* Runs an xPath query and returns all matched nodes.
*
* @param string xPath
* xPath search query to execute.
* @param [optional] nsIDOMNode context
* Context to run the xPath query on. Uses window.document if not set.
* @return array of nsIDOMNode
*/
-WebConsoleCommands._registerOriginal("$x", function(owner, xPath, context) {
+WebConsoleCommands._registerOriginal("$x", function (owner, xPath, context) {
let nodes = new owner.window.Array();
// Not waiving Xrays, since we want the original Document.evaluate function,
// instead of anything that's been redefined.
let doc = owner.window.document;
context = context || doc;
let results = doc.evaluate(xPath, context, null,
@@ -1145,90 +1145,90 @@ WebConsoleCommands._registerOriginal("$x
/**
* Returns the currently selected object in the highlighter.
*
* @return Object representing the current selection in the
* Inspector, or null if no selection exists.
*/
WebConsoleCommands._registerOriginal("$0", {
- get: function(owner) {
+ get: function (owner) {
return owner.makeDebuggeeValue(owner.selectedNode);
}
});
/**
* Clears the output of the WebConsole.
*/
-WebConsoleCommands._registerOriginal("clear", function(owner) {
+WebConsoleCommands._registerOriginal("clear", function (owner) {
owner.helperResult = {
type: "clearOutput",
};
});
/**
* Clears the input history of the WebConsole.
*/
-WebConsoleCommands._registerOriginal("clearHistory", function(owner) {
+WebConsoleCommands._registerOriginal("clearHistory", function (owner) {
owner.helperResult = {
type: "clearHistory",
};
});
/**
* Returns the result of Object.keys(object).
*
* @param object object
* Object to return the property names from.
* @return array of strings
*/
-WebConsoleCommands._registerOriginal("keys", function(owner, object) {
+WebConsoleCommands._registerOriginal("keys", function (owner, object) {
// Need to waive Xrays so we can iterate functions and accessor properties
return Cu.cloneInto(Object.keys(Cu.waiveXrays(object)), owner.window);
});
/**
* Returns the values of all properties on object.
*
* @param object object
* Object to display the values from.
* @return array of string
*/
-WebConsoleCommands._registerOriginal("values", function(owner, object) {
+WebConsoleCommands._registerOriginal("values", function (owner, object) {
let values = [];
// Need to waive Xrays so we can iterate functions and accessor properties
let waived = Cu.waiveXrays(object);
let names = Object.getOwnPropertyNames(waived);
for (let name of names) {
values.push(waived[name]);
}
return Cu.cloneInto(values, owner.window);
});
/**
* Opens a help window in MDN.
*/
-WebConsoleCommands._registerOriginal("help", function(owner) {
+WebConsoleCommands._registerOriginal("help", function (owner) {
owner.helperResult = { type: "help" };
});
/**
* Change the JS evaluation scope.
*
* @param DOMElement|string|window window
* The window object to use for eval scope. This can be a string that
* is used to perform document.querySelector(), to find the iframe that
* you want to cd() to. A DOMElement can be given as well, the
* .contentWindow property is used. Lastly, you can directly pass
* a window object. If you call cd() with no arguments, the current
* eval scope is cleared back to its default (the top window).
*/
-WebConsoleCommands._registerOriginal("cd", function(owner, window) {
+WebConsoleCommands._registerOriginal("cd", function (owner, window) {
if (!window) {
owner.consoleActor.evalWindow = null;
owner.helperResult = { type: "cd" };
return;
}
if (typeof window == "string") {
window = owner.window.document.querySelector(window);
@@ -1249,34 +1249,34 @@ WebConsoleCommands._registerOriginal("cd
});
/**
* Inspects the passed object. This is done by opening the PropertyPanel.
*
* @param object object
* Object to inspect.
*/
-WebConsoleCommands._registerOriginal("inspect", function(owner, object) {
+WebConsoleCommands._registerOriginal("inspect", function (owner, object) {
let dbgObj = owner.makeDebuggeeValue(object);
let grip = owner.createValueGrip(dbgObj);
owner.helperResult = {
type: "inspectObject",
input: owner.evalInput,
object: grip,
};
});
/**
* Prints object to the output.
*
* @param object object
* Object to print to the output.
* @return string
*/
-WebConsoleCommands._registerOriginal("pprint", function(owner, object) {
+WebConsoleCommands._registerOriginal("pprint", function (owner, object) {
if (object === null || object === undefined || object === true ||
object === false) {
owner.helperResult = {
type: "error",
message: "helperFuncUnsupportedTypeError",
};
return null;
}
@@ -1311,17 +1311,17 @@ WebConsoleCommands._registerOriginal("pp
/**
* Print the String representation of a value to the output, as-is.
*
* @param any value
* A value you want to output as a string.
* @return void
*/
-WebConsoleCommands._registerOriginal("print", function(owner, value) {
+WebConsoleCommands._registerOriginal("print", function (owner, value) {
owner.helperResult = { rawOutput: true };
if (typeof value === "symbol") {
return Symbol.prototype.toString.call(value);
}
// Waiving Xrays here allows us to see a closer representation of the
// underlying object. This may execute arbitrary content code, but that
// code will run with content privileges, and the result will be rendered
// inert by coercing it to a String.
@@ -1330,17 +1330,17 @@ WebConsoleCommands._registerOriginal("pr
/**
* Copy the String representation of a value to the clipboard.
*
* @param any value
* A value you want to copy as a string.
* @return void
*/
-WebConsoleCommands._registerOriginal("copy", function(owner, value) {
+WebConsoleCommands._registerOriginal("copy", function (owner, value) {
let payload;
try {
if (value instanceof Ci.nsIDOMElement) {
payload = value.outerHTML;
} else if (typeof value == "string") {
payload = value;
} else {
payload = JSON.stringify(value, null, " ");
@@ -1421,17 +1421,17 @@ ConsoleReflowListener.prototype =
/**
* Forward reflow event to listener.
*
* @param DOMHighResTimeStamp start
* @param DOMHighResTimeStamp end
* @param boolean interruptible
*/
- sendReflow: function(start, end, interruptible) {
+ sendReflow: function (start, end, interruptible) {
let frame = components.stack.caller.caller;
let filename = frame ? frame.filename : null;
if (filename) {
// Because filename could be of the form "xxx.js -> xxx.js -> xxx.js",
// we only take the last part.
filename = filename.split(" ").pop();
@@ -1448,34 +1448,34 @@ ConsoleReflowListener.prototype =
},
/**
* On uninterruptible reflow
*
* @param DOMHighResTimeStamp start
* @param DOMHighResTimeStamp end
*/
- reflow: function(start, end) {
+ reflow: function (start, end) {
this.sendReflow(start, end, false);
},
/**
* On interruptible reflow
*
* @param DOMHighResTimeStamp start
* @param DOMHighResTimeStamp end
*/
- reflowInterruptible: function(start, end) {
+ reflowInterruptible: function (start, end) {
this.sendReflow(start, end, true);
},
/**
* Unregister listener.
*/
- destroy: function() {
+ destroy: function () {
this.docshell.removeWeakReflowObserver(this);
this.listener = this.docshell = null;
},
};
function gSequenceId() {
return gSequenceId.n++;
}
--- a/devtools/shared/webconsole/worker-utils.js
+++ b/devtools/shared/webconsole/worker-utils.js
@@ -7,14 +7,14 @@
"use strict";
// XXXworkers This file is loaded on the server side for worker debugging.
// Since the server is running in the worker thread, it doesn't
// have access to Services / Components. This functionality
// is stubbed out to prevent errors, and will need to implemented
// for Bug 1209353.
-exports.Utils = { L10n: function() {} };
-exports.ConsoleServiceListener = function() {};
-exports.ConsoleAPIListener = function() {};
-exports.addWebConsoleCommands = function() {};
-exports.ConsoleReflowListener = function() {};
+exports.Utils = { L10n: function () {} };
+exports.ConsoleServiceListener = function () {};
+exports.ConsoleAPIListener = function () {};
+exports.addWebConsoleCommands = function () {};
+exports.ConsoleReflowListener = function () {};
exports.CONSOLE_WORKER_IDS = [];