Commit 8521257c authored by dpapad's avatar dpapad Committed by Commit Bot

SyncInternals WebUI: Fix style violations and enable PRESUBMIT checks.

Specifically:
 - Replace var with let/const (using lebab)
 - Fix missing/extra semicolon violations
 - Fix missing curly braces violations
 - Fix double quotes violations
 - Fix JS naming violations
 - clang-format
 - Add PRESUBMIT to catch these automatically moving forward.

Bug: 986001,792774
Change-Id: I1d180fd3557243e08b0009c4fdc122ffa742b505
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1716094
Auto-Submit: Demetrios Papadopoulos <dpapad@chromium.org>
Commit-Queue: Marc Treib <treib@chromium.org>
Reviewed-by: default avatarMarc Treib <treib@chromium.org>
Cr-Commit-Position: refs/heads/master@{#680372}
parent 6fc9fbac
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def CheckChangeOnUpload(input_api, output_api):
return _CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
return _CommonChecks(input_api, output_api)
def _CommonChecks(input_api, output_api):
results = []
results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api,
check_js=True)
try:
import sys
old_sys_path = sys.path[:]
cwd = input_api.PresubmitLocalPath()
sys.path += [input_api.os_path.join(cwd, '..', '..', '..', '..', 'tools')]
from web_dev_style import presubmit_support
results += presubmit_support.CheckStyle(input_api, output_api)
finally:
sys.path = old_sys_path
return results
......@@ -11,8 +11,8 @@ cr.define('chrome.sync.about_tab', function() {
this.removeAttribute('highlighted');
}
var oldStr = oldVal.toString();
var newStr = newVal.toString();
const oldStr = oldVal.toString();
const newStr = newVal.toString();
if (oldStr != '' && oldStr != newStr) {
// Note the addListener function does not end up creating duplicate
// listeners. There can be only one listener per event at a time.
......@@ -24,7 +24,7 @@ cr.define('chrome.sync.about_tab', function() {
function refreshAboutInfo(aboutInfo) {
chrome.sync.aboutInfo = aboutInfo;
var aboutInfoDiv = $('about-info');
const aboutInfoDiv = $('about-info');
jstProcess(new JsEvalContext(aboutInfo), aboutInfoDiv);
}
......@@ -33,13 +33,13 @@ cr.define('chrome.sync.about_tab', function() {
}
function onAboutInfoCountersUpdated(e) {
var details = e.details;
const details = e.details;
var modelType = details.modelType;
var counters = details.counters;
const modelType = details.modelType;
const counters = details.counters;
var type_status_array = chrome.sync.aboutInfo.type_status;
type_status_array.forEach(function(row) {
const typeStatusArray = chrome.sync.aboutInfo.type_status;
typeStatusArray.forEach(function(row) {
if (row.name == modelType) {
// There are three types of counters, only "status" counters have these
// fields. Keep the old values if updated fields are not present.
......@@ -52,8 +52,7 @@ cr.define('chrome.sync.about_tab', function() {
}
});
jstProcess(
new JsEvalContext({ type_status: type_status_array }),
$('typeInfo'));
new JsEvalContext({type_status: typeStatusArray}), $('typeInfo'));
}
/**
......@@ -74,17 +73,17 @@ cr.define('chrome.sync.about_tab', function() {
}
/** Container for accumulated sync protocol events. */
var protocolEvents = [];
const protocolEvents = [];
/** We may receive re-delivered events. Keep a record of ones we've seen. */
var knownEventTimestamps = {};
const knownEventTimestamps = {};
/**
* Callback for incoming protocol events.
* @param {Event} e The protocol event.
*/
function onReceivedProtocolEvent(e) {
var details = e.details;
const details = e.details;
// Return early if we've seen this event before. Assumes that timestamps
// are sufficiently high resolution to uniquely identify an event.
......@@ -95,24 +94,25 @@ cr.define('chrome.sync.about_tab', function() {
knownEventTimestamps[details.time] = true;
protocolEvents.push(details);
var trafficContainer = $('traffic-event-container');
const trafficContainer = $('traffic-event-container');
// Scroll to the bottom if we were already at the bottom. Otherwise, leave
// the scrollbar alone.
var shouldScrollDown = isScrolledToBottom(trafficContainer);
const shouldScrollDown = isScrolledToBottom(trafficContainer);
var context = new JsEvalContext({ events: protocolEvents });
const context = new JsEvalContext({events: protocolEvents});
jstProcess(context, trafficContainer);
if (shouldScrollDown)
if (shouldScrollDown) {
scrollToBottom(trafficContainer);
}
}
/**
* Initializes state and callbacks for the protocol event log UI.
*/
function initProtocolEventLog() {
var includeSpecificsCheckbox = $('capture-specifics');
const includeSpecificsCheckbox = $('capture-specifics');
includeSpecificsCheckbox.addEventListener('change', function(event) {
chrome.sync.setIncludeSpecifics(includeSpecificsCheckbox.checked);
});
......@@ -123,7 +123,7 @@ cr.define('chrome.sync.about_tab', function() {
// Make the prototype jscontent element disappear.
jstProcess({}, $('traffic-event-container'));
var triggerRefreshButton = $('trigger-refresh');
const triggerRefreshButton = $('trigger-refresh');
triggerRefreshButton.addEventListener('click', function(event) {
chrome.sync.triggerRefresh();
});
......@@ -135,15 +135,15 @@ cr.define('chrome.sync.about_tab', function() {
function initStatusDumpButton() {
$('status-data').hidden = true;
var dumpStatusButton = $('dump-status');
const dumpStatusButton = $('dump-status');
dumpStatusButton.addEventListener('click', function(event) {
var aboutInfo = chrome.sync.aboutInfo;
const aboutInfo = chrome.sync.aboutInfo;
if (!$('include-ids').checked) {
aboutInfo.details = chrome.sync.aboutInfo.details.filter(function(el) {
return !el.is_sensitive;
});
}
var data = '';
let data = '';
data += new Date().toString() + '\n';
data += '======\n';
data += 'Status\n';
......@@ -154,7 +154,7 @@ cr.define('chrome.sync.about_tab', function() {
$('status-data').hidden = false;
});
var importStatusButton = $('import-status');
const importStatusButton = $('import-status');
importStatusButton.addEventListener('click', function(event) {
$('status-data').hidden = false;
if ($('status-text').value.length == 0) {
......@@ -164,8 +164,8 @@ cr.define('chrome.sync.about_tab', function() {
}
// First remove any characters before the '{'.
var data = $('status-text').value;
var firstBrace = data.indexOf('{');
let data = $('status-text').value;
const firstBrace = data.indexOf('{');
if (firstBrace < 0) {
$('status-text').value = 'Invalid sync status dump.';
return;
......@@ -181,7 +181,7 @@ cr.define('chrome.sync.about_tab', function() {
'onCountersUpdated',
onAboutInfoCountersUpdated);
var aboutInfo = JSON.parse(data);
const aboutInfo = JSON.parse(data);
refreshAboutInfo(aboutInfo);
});
}
......@@ -195,12 +195,12 @@ cr.define('chrome.sync.about_tab', function() {
// We ignore proto clicks to keep it copyable.
return;
}
var traffic_event_div = e.target;
let trafficEventDiv = e.target;
// Click might be on div's child.
if (traffic_event_div.nodeName != "DIV") {
traffic_event_div = traffic_event_div.parentNode;
if (trafficEventDiv.nodeName != 'DIV') {
trafficEventDiv = trafficEventDiv.parentNode;
}
traffic_event_div.classList.toggle('traffic-event-entry-expanded');
trafficEventDiv.classList.toggle('traffic-event-entry-expanded');
}
/**
......
......@@ -30,7 +30,7 @@ cr.define('chrome.sync', function() {
};
/** @return {!Timer} An object which measures elapsed time. */
var makeTimer = function() {
const makeTimer = function() {
return new Timer;
};
......@@ -38,8 +38,8 @@ cr.define('chrome.sync', function() {
* @param {string} name The name of the event type.
* @param {!Object} details A collection of event-specific details.
*/
var dispatchEvent = function(name, details) {
var e = new Event(name);
const dispatchEvent = function(name, details) {
const e = new Event(name);
e.details = details;
chrome.sync.events.dispatchEvent(e);
};
......@@ -48,7 +48,7 @@ cr.define('chrome.sync', function() {
* Registers to receive a stream of events through
* chrome.sync.dispatchEvent().
*/
var registerForEvents = function() {
const registerForEvents = function() {
chrome.send('registerForEvents');
};
......@@ -56,15 +56,15 @@ cr.define('chrome.sync', function() {
* Registers to receive a stream of status counter update events
* chrome.sync.dispatchEvent().
*/
var registerForPerTypeCounters = function() {
const registerForPerTypeCounters = function() {
chrome.send('registerForPerTypeCounters');
}
};
/**
* Asks the browser to refresh our snapshot of sync state. Should result
* in an onAboutInfoUpdated event being emitted.
*/
var requestUpdatedAboutInfo = function() {
const requestUpdatedAboutInfo = function() {
chrome.send('requestUpdatedAboutInfo');
};
......@@ -72,7 +72,7 @@ cr.define('chrome.sync', function() {
* Asks the browser to send us the list of registered types. Should result
* in an onReceivedListOfTypes event being emitted.
*/
var requestListOfTypes = function() {
const requestListOfTypes = function() {
chrome.send('requestListOfTypes');
};
......@@ -81,14 +81,14 @@ cr.define('chrome.sync', function() {
* flag. Should result in an onReceivedIncludeSpecificsInitialState event
* being emitted.
*/
var requestIncludeSpecificsInitialState = function() {
const requestIncludeSpecificsInitialState = function() {
chrome.send('requestIncludeSpecificsInitialState');
}
};
/**
* Asks the browser if we should show the User Events tab or not.
*/
var requestUserEventsVisibility = function() {
const requestUserEventsVisibility = function() {
chrome.send('requestUserEventsVisibility');
};
......@@ -99,7 +99,7 @@ cr.define('chrome.sync', function() {
* @param {boolean} includeSpecifics Whether protocol events include
* specifics.
*/
var setIncludeSpecifics = function(includeSpecifics) {
const setIncludeSpecifics = function(includeSpecifics) {
chrome.send('setIncludeSpecifics', [includeSpecifics]);
};
......@@ -109,35 +109,35 @@ cr.define('chrome.sync', function() {
* @param {string} eventTimeUsec Timestamp for the new event.
* @param {string} navigationId Timestamp of linked sessions navigation.
*/
var writeUserEvent = function(eventTimeUsec, navigationId) {
const writeUserEvent = function(eventTimeUsec, navigationId) {
chrome.send('writeUserEvent', [eventTimeUsec, navigationId]);
};
/**
* Triggers a RequestStart call on the SyncService.
*/
var requestStart = function() {
const requestStart = function() {
chrome.send('requestStart');
};
/**
* Triggers a RequestStop(KEEP_DATA) call on the SyncService.
*/
var requestStopKeepData = function() {
const requestStopKeepData = function() {
chrome.send('requestStopKeepData');
};
/**
* Triggers a RequestStop(CLEAR_DATA) call on the SyncService.
*/
var requestStopClearData = function() {
const requestStopClearData = function() {
chrome.send('requestStopClearData');
};
/**
* Triggers a GetUpdates call for all enabled datatypes.
*/
var triggerRefresh = function() {
const triggerRefresh = function() {
chrome.send('triggerRefresh');
};
......@@ -145,14 +145,14 @@ cr.define('chrome.sync', function() {
* Counter to uniquely identify requests while they're in progress.
* Used in the implementation of GetAllNodes.
*/
var requestId = 0;
let requestId = 0;
/**
* A map from counter values to asynchronous request callbacks.
* Used in the implementation of GetAllNodes.
* @type {!Object<!Function>}
*/
var requestCallbacks = {};
const requestCallbacks = {};
/**
* Asks the browser to send us a copy of all existing sync nodes.
......@@ -160,7 +160,7 @@ cr.define('chrome.sync', function() {
*
* @param {function(!Object)} callback The function to call with the response.
*/
var getAllNodes = function(callback) {
const getAllNodes = function(callback) {
requestId++;
requestCallbacks[requestId] = callback;
chrome.send('getAllNodes', [requestId]);
......@@ -172,7 +172,7 @@ cr.define('chrome.sync', function() {
* @param {number} id The requestId passed in with the request.
* @param {Object} response The response to the request.
*/
var getAllNodesCallback = function(id, response) {
const getAllNodesCallback = function(id, response) {
requestCallbacks[id](response);
delete requestCallbacks[id];
};
......
......@@ -3,12 +3,12 @@
// found in the LICENSE file.
(function() {
var dumpToTextButton = $('dump-to-text');
var dataDump = $('data-dump');
const dumpToTextButton = $('dump-to-text');
const dataDump = $('data-dump');
dumpToTextButton.addEventListener('click', function(event) {
// TODO(akalin): Add info like Chrome version, OS, date dumped, etc.
var data = '';
let data = '';
data += '======\n';
data += 'Status\n';
data += '======\n';
......@@ -32,7 +32,7 @@ dumpToTextButton.addEventListener('click', function(event) {
dataDump.textContent = data;
});
var allFields = [
const allFields = [
'ID',
'IS_UNSYNCED',
'IS_UNAPPLIED_UPDATE',
......@@ -51,9 +51,9 @@ var allFields = [
function versionToDateString(version) {
// TODO(mmontgomery): ugly? Hacky? Is there a better way?
var epochLength = Date.now().toString().length;
var epochTime = parseInt(version.slice(0, epochLength), 10);
var date = new Date(epochTime);
const epochLength = Date.now().toString().length;
const epochTime = parseInt(version.slice(0, epochLength), 10);
const date = new Date(epochTime);
return date.toString();
}
......@@ -63,22 +63,25 @@ function versionToDateString(version) {
*/
function serializeNode(node) {
return allFields.map(function(field) {
var fieldVal;
let fieldVal;
if (field == 'SERVER_VERSION_TIME') {
var version = node['SERVER_VERSION'];
const version = node['SERVER_VERSION'];
if (version != null) {
fieldVal = versionToDateString(version);
}
} if (field == 'BASE_VERSION_TIME') {
var version = node['BASE_VERSION'];
}
if (field == 'BASE_VERSION_TIME') {
const version = node['BASE_VERSION'];
if (version != null) {
fieldVal = versionToDateString(version);
}
} else if ((field == 'SERVER_SPECIFICS' || field == 'SPECIFICS') &&
(!$('include-specifics').checked)) {
} else if (
(field == 'SERVER_SPECIFICS' || field == 'SPECIFICS') &&
(!$('include-specifics').checked)) {
fieldVal = 'REDACTED';
} else if ((field == 'SERVER_SPECIFICS' || field == 'SPECIFICS') &&
$('include-specifics').checked) {
} else if (
(field == 'SERVER_SPECIFICS' || field == 'SPECIFICS') &&
$('include-specifics').checked) {
fieldVal = JSON.stringify(node[field]);
} else {
fieldVal = node[field];
......@@ -92,7 +95,7 @@ function serializeNode(node) {
* @return {boolean} True if the type's checkbox is selected.
*/
function isSelectedDatatype(type) {
var typeCheckbox = $(type);
const typeCheckbox = $(type);
// Some types, such as 'Top level folder', appear in the list of nodes
// but not in the list of selectable items.
if (typeCheckbox == null) {
......@@ -102,28 +105,26 @@ function isSelectedDatatype(type) {
}
function makeBlobUrl(data) {
var textBlob = new Blob([data], {type: 'octet/stream'});
var blobUrl = window.URL.createObjectURL(textBlob);
const textBlob = new Blob([data], {type: 'octet/stream'});
const blobUrl = window.URL.createObjectURL(textBlob);
return blobUrl;
}
function makeDownloadName() {
// Format is sync-data-dump-$epoch-$year-$month-$day-$OS.csv.
var now = new Date();
var friendlyDate = [now.getFullYear(),
now.getMonth() + 1,
now.getDate()].join('-');
var name = ['sync-data-dump',
friendlyDate,
Date.now(),
navigator.platform].join('-');
const now = new Date();
const friendlyDate =
[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-');
const name = [
'sync-data-dump', friendlyDate, Date.now(), navigator.platform
].join('-');
return [name, 'csv'].join('.');
}
function makeDateUserAgentHeader() {
var now = new Date();
var userAgent = window.navigator.userAgent;
var dateUaHeader = [now.toISOString(), userAgent].join(',');
const now = new Date();
const userAgent = window.navigator.userAgent;
const dateUaHeader = [now.toISOString(), userAgent].join(',');
return dateUaHeader;
}
......@@ -135,14 +136,14 @@ function makeDateUserAgentHeader() {
*/
function triggerDataDownload(nodesMap) {
// Prepend a header with ISO date and useragent.
var output = [makeDateUserAgentHeader()];
let output = [makeDateUserAgentHeader()];
output.push('=====');
var aboutInfo = JSON.stringify(chrome.sync.aboutInfo, null, 2);
const aboutInfo = JSON.stringify(chrome.sync.aboutInfo, null, 2);
output.push(aboutInfo);
// Filter out non-selected types.
var selectedTypesNodes = nodesMap.filter(function(x) {
const selectedTypesNodes = nodesMap.filter(function(x) {
return isSelectedDatatype(x.type);
});
......@@ -154,25 +155,25 @@ function triggerDataDownload(nodesMap) {
output = output.join('\n');
var anchor = $('dump-to-file-anchor');
const anchor = $('dump-to-file-anchor');
anchor.href = makeBlobUrl(output);
anchor.download = makeDownloadName();
anchor.click();
}
function createTypesCheckboxes(types) {
var containerElt = $('node-type-checkboxes');
const containerElt = $('node-type-checkboxes');
types.map(function(type) {
var div = document.createElement('div');
const div = document.createElement('div');
var checkbox = document.createElement('input');
const checkbox = document.createElement('input');
checkbox.id = type;
checkbox.type = 'checkbox';
checkbox.checked = 'yes';
div.appendChild(checkbox);
var label = document.createElement('label');
const label = document.createElement('label');
// Assigning to label.for doesn't work.
label.setAttribute('for', type);
label.innerText = type;
......@@ -183,7 +184,7 @@ function createTypesCheckboxes(types) {
}
function onReceivedListOfTypes(e) {
var types = e.details.types;
const types = e.details.types;
types.sort();
createTypesCheckboxes(types);
chrome.sync.events.removeEventListener(
......@@ -207,7 +208,7 @@ document.addEventListener('DOMContentLoaded', function() {
chrome.sync.requestIncludeSpecificsInitialState();
});
var dumpToFileLink = $('dump-to-file');
const dumpToFileLink = $('dump-to-file');
dumpToFileLink.addEventListener('click', function(event) {
chrome.sync.getAllNodes(triggerDataDownload);
});
......
......@@ -6,14 +6,14 @@ cr.define('chrome.sync.events_tab', function() {
'use strict';
function toggleDisplay(event) {
var originatingButton = event.target;
const originatingButton = event.target;
if (originatingButton.className != 'toggle-button') {
return;
}
var detailsNode = originatingButton.parentNode.getElementsByClassName(
'details')[0];
var detailsColumn = detailsNode.parentNode;
var detailsRow = detailsColumn.parentNode;
const detailsNode =
originatingButton.parentNode.getElementsByClassName('details')[0];
const detailsColumn = detailsNode.parentNode;
const detailsRow = detailsColumn.parentNode;
if (!detailsRow.classList.contains('expanded')) {
detailsRow.classList.toggle('expanded');
......@@ -24,16 +24,16 @@ cr.define('chrome.sync.events_tab', function() {
detailsColumn.removeAttribute('colspan');
detailsRow.classList.toggle('expanded');
}
};
}
function displaySyncEvents() {
var entries = chrome.sync.log.entries;
var eventTemplateContext = {
const entries = chrome.sync.log.entries;
const eventTemplateContext = {
eventList: entries,
};
var context = new JsEvalContext(eventTemplateContext);
const context = new JsEvalContext(eventTemplateContext);
jstProcess(context, $('sync-events'));
};
}
function onLoad() {
$('sync-events').addEventListener('click', toggleDisplay);
......
......@@ -13,7 +13,7 @@
cr.define('chrome.sync', function() {
'use strict';
var eventsByCategory = {
const eventsByCategory = {
notifier: [
'onIncomingNotification',
'onNotificationStateChange',
......@@ -50,7 +50,7 @@ cr.define('chrome.sync', function() {
class Log extends cr.EventTarget {
constructor() {
super();
var self = this;
const self = this;
/**
* The recorded log entries.
......@@ -61,15 +61,15 @@ cr.define('chrome.sync', function() {
/**
* Creates a callback function to be invoked when an event arrives.
*/
var makeCallback = function(categoryName, eventName) {
const makeCallback = function(categoryName, eventName) {
return function(e) {
self.log_(categoryName, eventName, e.details);
};
};
for (var categoryName in eventsByCategory) {
for (var i = 0; i < eventsByCategory[categoryName].length; ++i) {
var eventName = eventsByCategory[categoryName][i];
for (const categoryName in eventsByCategory) {
for (let i = 0; i < eventsByCategory[categoryName].length; ++i) {
const eventName = eventsByCategory[categoryName][i];
chrome.sync.events.addEventListener(
eventName,
makeCallback(categoryName, eventName));
......@@ -86,7 +86,7 @@ cr.define('chrome.sync', function() {
* @param {!Object} details A dictionary of event-specific details.
*/
log_(submodule, event, details) {
var entry = {
const entry = {
submodule: submodule,
event: event,
date: new Date(),
......@@ -96,7 +96,7 @@ cr.define('chrome.sync', function() {
entry.textDetails = JSON.stringify(entry.details, null, 2);
this.entries.push(entry);
// Fire append event.
var e = cr.doc.createEvent('CustomEvent');
const e = cr.doc.createEvent('CustomEvent');
e.initCustomEvent('append', false, false, entry);
this.dispatchEvent(e);
}
......
......@@ -12,7 +12,7 @@
*
* @param {!Object} node The node to check.
*/
var isTypeRootNode = function(node) {
const isTypeRootNode = function(node) {
return node.PARENT_ID == 'r' && node.UNIQUE_SERVER_TAG != '';
};
......@@ -22,11 +22,10 @@
* @param {!Object} parent node.
* @param {!Object} node The node to check.
*/
var isChildOf = function(parentNode, node) {
const isChildOf = function(parentNode, node) {
if (node.PARENT_ID != '') {
return node.PARENT_ID == parentNode.ID;
}
else {
} else {
return node.modelType == parentNode.modelType;
}
};
......@@ -40,7 +39,7 @@
* If this proves to be slow and expensive, we should experiment with moving
* this functionality to C++ instead.
*/
var nodeComparator = function(nodeA, nodeB) {
const nodeComparator = function(nodeA, nodeB) {
if (nodeA.hasOwnProperty('positionIndex') &&
nodeB.hasOwnProperty('positionIndex')) {
return nodeA.positionIndex - nodeB.positionIndex;
......@@ -56,7 +55,7 @@
* @param {!Object} node The struct representing the node we want to display.
*/
function updateNodeDetailView(node) {
var nodeDetailsView = $('node-details');
const nodeDetailsView = $('node-details');
nodeDetailsView.hidden = false;
jstProcess(new JsEvalContext(node.entry_), nodeDetailsView);
}
......@@ -77,8 +76,8 @@
* chrome.sync.getAllNodes().
* @extends {cr.ui.TreeItem}
*/
var SyncNodeTreeItem = function(node) {
var treeItem = new cr.ui.TreeItem();
const SyncNodeTreeItem = function(node) {
const treeItem = new cr.ui.TreeItem();
treeItem.__proto__ = SyncNodeTreeItem.prototype;
treeItem.entry_ = node;
......@@ -103,14 +102,14 @@
* Finds the children of this node and appends them to the tree.
*/
handleExpand_: function(event) {
var treeItem = this;
const treeItem = this;
if (treeItem.expanded_) {
return;
}
treeItem.expanded_ = true;
var children = treeItem.tree.allNodes.filter(
const children = treeItem.tree.allNodes.filter(
isChildOf.bind(undefined, treeItem.entry_));
children.sort(nodeComparator);
......@@ -129,7 +128,7 @@
* @constructor
* @extends {cr.ui.Tree}
*/
var SyncNodeTree = cr.ui.define('tree');
const SyncNodeTree = cr.ui.define('tree');
SyncNodeTree.prototype = {
__proto__: cr.ui.Tree.prototype,
......@@ -141,12 +140,12 @@
},
populate: function(nodes) {
var tree = this;
const tree = this;
// We store the full set of nodes in the SyncNodeTree object.
tree.allNodes = nodes;
var roots = tree.allNodes.filter(isTypeRootNode);
const roots = tree.allNodes.filter(isTypeRootNode);
roots.sort(nodeComparator);
roots.forEach(function(typeRoot) {
......@@ -165,12 +164,12 @@
* Clears any existing UI state. Useful prior to a refresh.
*/
function clear() {
var treeContainer = $('sync-node-tree-container');
const treeContainer = $('sync-node-tree-container');
while (treeContainer.firstChild) {
treeContainer.removeChild(treeContainer.firstChild);
}
var nodeDetailsView = $('node-details');
const nodeDetailsView = $('node-details');
nodeDetailsView.hidden = true;
}
......@@ -185,12 +184,16 @@
chrome.sync.getAllNodes(function(nodeMap) {
// Put all nodes into one big list that ignores the type.
var nodes = nodeMap.
map(function(x) { return x.nodes; }).
reduce(function(a, b) { return a.concat(b); });
var treeContainer = $('sync-node-tree-container');
var tree = document.createElement('tree');
const nodes = nodeMap
.map(function(x) {
return x.nodes;
})
.reduce(function(a, b) {
return a.concat(b);
});
const treeContainer = $('sync-node-tree-container');
const tree = document.createElement('tree');
tree.setAttribute('id', 'sync-node-tree');
tree.setAttribute('icon-visibility', 'parent');
treeContainer.appendChild(tree);
......@@ -205,16 +208,16 @@
document.addEventListener('DOMContentLoaded', function(e) {
$('node-browser-refresh-button').addEventListener('click', refresh);
var Splitter = cr.ui.Splitter;
var customSplitter = cr.ui.define('div');
const Splitter = cr.ui.Splitter;
const customSplitter = cr.ui.define('div');
customSplitter.prototype = {
__proto__: Splitter.prototype,
handleSplitterDragEnd: function(e) {
Splitter.prototype.handleSplitterDragEnd.apply(this, arguments);
var treeElement = $("sync-node-tree-container");
var newWidth = parseFloat(treeElement.style.width);
const treeElement = $('sync-node-tree-container');
const newWidth = parseFloat(treeElement.style.width);
treeElement.style.minWidth = Math.max(newWidth, 50) + "px";
}
};
......
......@@ -5,13 +5,13 @@
// require: cr.js
cr.define('chrome.sync', function() {
var currSearchId = 0;
let currSearchId = 0;
var setQueryString = function(queryControl, query) {
const setQueryString = function(queryControl, query) {
queryControl.value = query;
};
var createDoQueryFunction = function(queryControl, submitControl, query) {
const createDoQueryFunction = function(queryControl, submitControl, query) {
return function() {
setQueryString(queryControl, query);
submitControl.click();
......@@ -27,12 +27,12 @@ cr.define('chrome.sync', function() {
* @param {!HTMLInputElement} queryControl The <input> object of
* type=search where user's query is typed.
*/
var decorateQuickQueryControls = function(quickLinkArray, submitControl,
queryControl) {
for (var index = 0; index < quickLinkArray.length; ++index) {
var quickQuery = quickLinkArray[index].getAttribute('data-query');
var quickQueryFunction = createDoQueryFunction(queryControl,
submitControl, quickQuery);
const decorateQuickQueryControls = function(
quickLinkArray, submitControl, queryControl) {
for (let index = 0; index < quickLinkArray.length; ++index) {
const quickQuery = quickLinkArray[index].getAttribute('data-query');
const quickQueryFunction =
createDoQueryFunction(queryControl, submitControl, quickQuery);
quickLinkArray[index].addEventListener('click', quickQueryFunction);
}
};
......@@ -44,15 +44,19 @@ cr.define('chrome.sync', function() {
* @param {!Function} callback The callback called with the search results.
* not called if doSearch() is called again while the search is running.
*/
var doSearch = function(query, callback) {
var searchId = ++currSearchId;
const doSearch = function(query, callback) {
const searchId = ++currSearchId;
try {
var regex = new RegExp(query);
const regex = new RegExp(query);
chrome.sync.getAllNodes(function(node_map) {
// Put all nodes into one big list that ignores the type.
var nodes = node_map.
map(function(x) { return x.nodes; }).
reduce(function(a, b) { return a.concat(b); });
const nodes = node_map
.map(function(x) {
return x.nodes;
})
.reduce(function(a, b) {
return a.concat(b);
});
if (currSearchId != searchId) {
return;
......@@ -84,10 +88,10 @@ cr.define('chrome.sync', function() {
*/
function decorateSearchControls(queryControl, submitControl, statusControl,
resultsControl, detailsControl) {
var resultsDataModel = new cr.ui.ArrayDataModel([]);
const resultsDataModel = new cr.ui.ArrayDataModel([]);
var searchFunction = function() {
var query = queryControl.value;
const searchFunction = function() {
const query = queryControl.value;
statusControl.textContent = '';
resultsDataModel.splice(0, resultsDataModel.length);
if (!query) {
......@@ -95,7 +99,7 @@ cr.define('chrome.sync', function() {
}
statusControl.textContent = 'Searching for ' + query + '...';
queryControl.removeAttribute('error');
var timer = chrome.sync.makeTimer();
const timer = chrome.sync.makeTimer();
doSearch(query, function(nodes, error) {
if (error) {
statusControl.textContent = 'Error: ' + error;
......@@ -107,7 +111,7 @@ cr.define('chrome.sync', function() {
queryControl.removeAttribute('error');
// TODO(akalin): Write a nicer list display.
for (var i = 0; i < nodes.length; ++i) {
for (let i = 0; i < nodes.length; ++i) {
nodes[i].toString = function() {
return this.NON_UNIQUE_NAME;
};
......@@ -129,7 +133,7 @@ cr.define('chrome.sync', function() {
resultsControl.dataModel = resultsDataModel;
resultsControl.selectionModel.addEventListener('change', function(event) {
detailsControl.textContent = '';
var selected = resultsControl.selectedItem;
const selected = resultsControl.selectedItem;
if (selected) {
detailsControl.textContent = JSON.stringify(selected, null, 2);
}
......
......@@ -2,95 +2,97 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.exportPath('chrome.sync.traffic_log_tab', new class {
constructor() {
this.protocolEvents = [];
this.knownEventTimestamps = new Set();
/** @type {!HTMLElement} */
this.container;
}
/**
* Helper to determine if the window is scrolled to its bottom limit.
* @return {boolean} true if the container is scrolled to the bottom
* @private
*/
_isScrolledToBottom() {
return (window.innerHeight + window.scrollY) >= document.body.offsetHeight;
}
/**
* Helper to scroll the window to its bottom.
* @private
*/
_scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
/**
* Callback for incoming protocol events.
* @param {Event} e The protocol event.
* @private
*/
_onReceivedProtocolEvent(e) {
var details = e.details;
if (this.knownEventTimestamps.has(details.time)) {
return;
}
this.knownEventTimestamps.add(details.time);
this.protocolEvents.push(details);
var shouldScrollDown = this._isScrolledToBottom();
jstProcess(
new JsEvalContext({ events: this.protocolEvents }),
this.container);
if (shouldScrollDown) {
this._scrollToBottom();
}
}
/**
* Toggles the given traffic event entry div's "expanded" state.
* @param {!Event} e the click event that triggered the toggle.
* @private
*/
_expandListener(e) {
if (e.target.classList.contains("proto")) {
// We ignore proto clicks to keep it copyable.
return;
}
var traffic_event_div = e.target;
// Click might be on div's child.
if (traffic_event_div.nodeName != "DIV") {
traffic_event_div = traffic_event_div.parentNode;
}
traffic_event_div.classList.toggle(
'traffic-event-entry-expanded-fullscreen');
}
/**
* Attaches a listener to the given traffic event entry div.
* @param {HTMLElement} element
*/
addExpandListener(element) {
element.addEventListener('click', this._expandListener, false);
}
onLoad() {
this.container = getRequiredElement('traffic-event-fullscreen-container');
chrome.sync.events.addEventListener(
'onProtocolEvent', this._onReceivedProtocolEvent.bind(this));
// Make the prototype jscontent element disappear.
jstProcess(new JsEvalContext({}), this.container);
}
});
cr.exportPath(
'chrome.sync.traffic_log_tab', new (class {
constructor() {
this.protocolEvents = [];
this.knownEventTimestamps = new Set();
/** @type {!HTMLElement} */
this.container;
}
/**
* Helper to determine if the window is scrolled to its bottom limit.
* @return {boolean} true if the container is scrolled to the bottom
* @private
*/
_isScrolledToBottom() {
return (window.innerHeight + window.scrollY) >=
document.body.offsetHeight;
}
/**
* Helper to scroll the window to its bottom.
* @private
*/
_scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
/**
* Callback for incoming protocol events.
* @param {Event} e The protocol event.
* @private
*/
_onReceivedProtocolEvent(e) {
const details = e.details;
if (this.knownEventTimestamps.has(details.time)) {
return;
}
this.knownEventTimestamps.add(details.time);
this.protocolEvents.push(details);
const shouldScrollDown = this._isScrolledToBottom();
jstProcess(
new JsEvalContext({events: this.protocolEvents}), this.container);
if (shouldScrollDown) {
this._scrollToBottom();
}
}
/**
* Toggles the given traffic event entry div's "expanded" state.
* @param {!Event} e the click event that triggered the toggle.
* @private
*/
_expandListener(e) {
if (e.target.classList.contains('proto')) {
// We ignore proto clicks to keep it copyable.
return;
}
let trafficEventDiv = e.target;
// Click might be on div's child.
if (trafficEventDiv.nodeName != 'DIV') {
trafficEventDiv = trafficEventDiv.parentNode;
}
trafficEventDiv.classList.toggle(
'traffic-event-entry-expanded-fullscreen');
}
/**
* Attaches a listener to the given traffic event entry div.
* @param {HTMLElement} element
*/
addExpandListener(element) {
element.addEventListener('click', this._expandListener, false);
}
onLoad() {
this.container =
getRequiredElement('traffic-event-fullscreen-container');
chrome.sync.events.addEventListener(
'onProtocolEvent', this._onReceivedProtocolEvent.bind(this));
// Make the prototype jscontent element disappear.
jstProcess(new JsEvalContext({}), this.container);
}
}));
document.addEventListener(
'DOMContentLoaded',
......
......@@ -3,7 +3,7 @@
// found in the LICENSE file.
cr.define('chrome.sync.types', function() {
var typeCountersMap = {};
const typeCountersMap = {};
/**
* Redraws the counters table taking advantage of the most recent
......@@ -11,8 +11,8 @@ cr.define('chrome.sync.types', function() {
*
* Makes use of typeCountersMap, which is defined in the containing scope.
*/
var refreshTypeCountersDisplay = function() {
var typeCountersArray = [];
const refreshTypeCountersDisplay = function() {
const typeCountersArray = [];
// Transform our map into an array to make jstemplate happy.
Object.keys(typeCountersMap).sort().forEach(function(t) {
......@@ -34,8 +34,8 @@ cr.define('chrome.sync.types', function() {
*
* @param {!Object} e An event containing the list of known sync types.
*/
var onReceivedListOfTypes = function(e) {
var types = e.details.types;
const onReceivedListOfTypes = function(e) {
const types = e.details.types;
types.map(function(type) {
if (!typeCountersMap.hasOwnProperty(type)) {
typeCountersMap[type] = {};
......@@ -52,23 +52,24 @@ cr.define('chrome.sync.types', function() {
*
* @param {!Object} e An event containing an updated counter.
*/
var onCountersUpdated = function(e) {
var details = e.details;
const onCountersUpdated = function(e) {
const details = e.details;
var modelType = details.modelType;
var counters = details.counters;
const modelType = details.modelType;
const counters = details.counters;
if (typeCountersMap.hasOwnProperty(modelType))
for (var k in counters) {
if (typeCountersMap.hasOwnProperty(modelType)) {
for (const k in counters) {
typeCountersMap[modelType][k] = counters[k];
}
}
refreshTypeCountersDisplay();
};
/**
* Initializes state and callbacks for the per-type counters and status UI.
*/
var initTypeCounters = function() {
const initTypeCounters = function() {
chrome.sync.events.addEventListener(
'onCountersUpdated',
onCountersUpdated);
......@@ -80,7 +81,7 @@ cr.define('chrome.sync.types', function() {
chrome.sync.registerForPerTypeCounters();
};
var onLoad = function() {
const onLoad = function() {
initTypeCounters();
};
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment