code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the explore page.
*
* @author phu@google.com (Po Hu)
*/
goog.require('bite.server.Helper');
goog.require('goog.testing.asserts');
function setUp() {
}
function tearDown() {
}
function testGetUrl() {
var serverUrl = '';
var requestPath = '/run/get';
var paramMap = {'page': 'set'};
var url = bite.server.Helper.getUrl(serverUrl, requestPath, paramMap);
assertEquals('/run/get?page=set', url);
}
function testGetUrlHash() {
var serverUrl = '';
var requestPath = '/run/get';
var paramMap = {'page': 'set'};
var url = bite.server.Helper.getUrlHash(serverUrl, requestPath, paramMap);
assertEquals('/run/get#page=set', url);
}
function testSplitAndTrim() {
var str = 'hello, yes, hi ';
var delimiter = ',';
var results = bite.server.Helper.splitAndTrim(str, delimiter);
assertObjectEquals(['hello', 'yes', 'hi'], results);
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the details page's tests tab.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.set.Tests');
goog.require('bite.server.Helper');
goog.require('bite.server.set.Tab');
goog.require('bite.server.TestSrcHelper');
goog.require('bite.server.templates.details');
goog.require('goog.dom');
goog.require('goog.net.XhrIo');
/**
* A class for set runs functions.
* @param {function():Object} getInfoFunc The getter for set's info.
* @extends {bite.server.set.Tab}
* @constructor
* @export
*/
bite.server.set.Tests = function(getInfoFunc) {
/**
* To get the selected item's info.
* @type {function():Object}
* @private
*/
this.getInfoFunc_ = getInfoFunc;
/**
* The tests source depot.
* @type {string}
*/
this.loadFrom = '';
var loadTestsFunc = goog.bind(this.loadTestsFromBackend, this);
/**
* The current selected helper.
* @type {bite.server.TestSrcHelper}
* @private
*/
this.selectedHelper_ = new bite.server.TestSrcHelper(loadTestsFunc);
/**
* The helpers map object.
* @type {Object}
* @private
*/
this.helperMap_ = {
'': new bite.server.TestSrcHelper(loadTestsFunc)
};
};
goog.inherits(bite.server.set.Tests, bite.server.set.Tab);
/**
* Inits the setting's overview page.
* @param {Element} tabDetailsDiv The tab details div.
* @export
*/
bite.server.set.Tests.prototype.init = function(tabDetailsDiv) {
tabDetailsDiv.innerHTML = bite.server.templates.details.showTabTests({});
bite.server.Helper.addListenersToElems(
[goog.dom.getElement('acc')],
goog.bind(this.handleSrcSelection, this));
this.loadSetting();
};
/**
* Handles selecting a tests source.
* @param {Event} event The event object.
* @export
*/
bite.server.set.Tests.prototype.handleSrcSelection = function(event) {
this.loadTestsFrom(event.target.id);
};
/**
* Saves the previous page settings.
* @export
*/
bite.server.set.Tests.prototype.saveSetting = function() {
this.selectedHelper_.saveFields();
};
/**
* Loads the page's tests settings.
* @export
*/
bite.server.set.Tests.prototype.loadSetting = function() {
if (this.loadFrom) {
goog.dom.getElement(this.loadFrom).checked = true;
this.loadTestsFrom(this.loadFrom);
} else {
this.clearTestSrcButtons();
this.clearSetTestsPage();
}
};
/**
* Clears the set tests page.
* @export
*/
bite.server.set.Tests.prototype.clearSetTestsPage = function() {
goog.dom.getElement('loadTestsFromDiv').innerHTML = '';
goog.dom.getElement('showTestsDiv').innerHTML = '';
};
/**
* Clears the test sources radio buttons.
* @export
*/
bite.server.set.Tests.prototype.clearTestSrcButtons = function() {
var buttons = goog.dom.getDocument().getElementsByName('testsSrc');
for (var i = 0, len = buttons.length; i < len; i++) {
buttons[i].checked = false;
}
};
/**
* Sets the default properties.
* @param {Object} params The parameter map.
* @export
*/
bite.server.set.Tests.prototype.setProperties = function(params) {
this.loadFrom = params['testSource'];
this.selectedHelper_ = this.helperMap_[this.loadFrom];
this.selectedHelper_.setFields(params);
};
/**
* Loads tests from a the given source.
* @param {string} requestUrl The request url.
* @param {string} parameters The parameter string.
* @export
*/
bite.server.set.Tests.prototype.loadTestsFromBackend = function(
requestUrl, parameters) {
var that = this;
goog.net.XhrIo.send(requestUrl, function() {
if (this.isSuccess()) {
var tests = null;
var tests_obj = this.getResponseJson();
if (tests_obj) {
var loadSrcDiv = goog.dom.getElement('showTestsDiv');
loadSrcDiv.innerHTML = bite.server.templates.details.showTestList(
tests_obj);
}
} else {
throw new Error('Failed to get the tests. Error status: ' +
this.getStatus());
}
}, 'POST', parameters);
};
/**
* Loads tests from a source and displays the UI.
* @param {string} src The source depot.
* @export
*/
bite.server.set.Tests.prototype.loadTestsFrom = function(src) {
this.selectedHelper_ = this.helperMap_[src];
this.loadFrom = src;
this.clearSetTestsPage();
var loadSrcDiv = goog.dom.getElement('loadTestsFromDiv');
this.selectedHelper_.showQueryFields(loadSrcDiv);
};
/**
* Adds the properties to the given map.
* @param {Object} params The parameter map.
* @export
*/
bite.server.set.Tests.prototype.addProperties = function(params) {
params['testSource'] = this.loadFrom;
for (var testSrc in this.helperMap_) {
this.helperMap_[testSrc].addProperties(params);
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* The expected ID of the install BITE link.
*/
var BITE_BUTTON_ID = 'bite-install-link';
/**
* Simplified implementation of goog.bind
*
* @param {Function} func The function to bind.
* @param {Object} inst The class instance to bind the function to.
* @param {Array} args Additional arguments to pass to the function.
* @return {Function} The function bound to the specified instance.
*/
function biteFuncBind(func, inst, args) {
return function() {
return func.apply(inst, Array.prototype.slice.call(arguments, 2));
};
}
/**
* Bug Details Popup class constructor.
* @param {string} id The id of the element to tag the BITE popup to.
* @constructor
* @export
*/
function bitePopup(id) {
/**
* The id of the element this popup will appear beneath.
* @type {string}
* @private
*/
this.parentElementId_ = id;
// Only load the popup if the browser is chrome.
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
// Attach the initial listeners to the parent element for this popup.
var parentLink = document.getElementById(id);
parentLink.addEventListener('mouseover', biteFuncBind(this.create, this),
[true, false]);
parentLink.addEventListener('mouseout', biteFuncBind(this.remove, this),
[true, false]);
}
}
/**
* The x offset of the popup from it's parent element.
* @type {number}
* @private
*/
bitePopup.OFFSET_X_ = -205;
/**
* The y offset of the popup from it's parent element.
* @type {number}
* @private
*/
bitePopup.OFFSET_Y_ = 26;
/**
* A flag to remove the popup.
* @type {boolean}
* @private
*/
bitePopup.prototype.removeFlag_ = false;
/**
* The amount of time (in ms) the popup will stay up after the user leaves it.
* @type {number}
* @private
*/
bitePopup.BITE_POPUP_DURATION_MS_ = 250;
/**
* The id of the BITE popup container.
* @type {string}
* @export
*/
bitePopup.BITE_POPUP_CONTAINER_ID = 'bite-download-popup-container';
/**
* Finds the position of an element by using the accumulated offset position
* of the element and it's ancestors.
* @param {!Element} element The HTML element to find the position of.
* @return {!{x: number, y: number}} The x, y coordinates of the element.
* @private
*/
bitePopup.findPosition_ = function(element) {
var elementLeft = element.offsetLeft;
var elementTop = element.offsetTop;
if (element.offsetParent) {
while (element = element.offsetParent) {
elementLeft += element.offsetLeft;
elementTop += element.offsetTop;
}
}
return {x: elementLeft, y: elementTop};
};
/**
* Creates the popup underneath the "parent" element.
* @export
*/
bitePopup.prototype.create = function() {
this.removeFlag_ = false;
// Don't create a duplicate popup if one already exists.
if (this.isOpen_()) {
return;
}
// Retrieve the parent element to append the popup to.
var parent = document.getElementById(this.parentElementId_);
if (!parent) {
console.error('Unable to find the specified parent element provided: ' +
this.parentElementId_);
return;
}
// Retrieve the position of the parent element, and computes the position
// of the popup.
//TODO(bustamante): Handle cases when this doesn't appear in the viewport.
var parentPosition = bitePopup.findPosition_(parent);
var popupLeft = parentPosition['x'] + bitePopup.OFFSET_X_;
var popupTop = parentPosition['y'] + bitePopup.OFFSET_Y_;
// Create the popup container.
var popup = document.createElement('div');
popup.setAttribute('id', bitePopup.BITE_POPUP_CONTAINER_ID);
popup.setAttribute('style',
'position:absolute; top:' + popupTop + 'px; ' +
'left: ' + popupLeft + 'px; width: 355px; ' +
'height: 130px; background-color: #fff; ' +
'border: 1px solid rgba(0,0,0,0.2); ' +
'-webkit-border-radius: 2px; ' +
'-moz-border-radius: 2px; ' +
'border-radius: 2px; ' +
'box-shadow: 0 2px 4px rgba(0,0,0,0.2); ' +
'-moz-box-shadow: 0 2px 4px rgba(0,0,0,0.2); ' +
'-webkit-box-shadow: 0 2px 4px rgba(0,0,0,0.2); ' +
'z-index: 999999;');
// Create the logo and append it to the popup container.
var logo = document.createElement('img');
logo.setAttribute('style', 'position: absolute; top: 10px; left: 10px; ' +
'width:150px; height: 80px');
logo.setAttribute('src', 'https://YOUR_SERVER/imgs/' +
'bite_logo_google.png');
popup.appendChild(logo);
// Create the BITE title and append it to the popup container.
var title = document.createElement('span');
title.setAttribute('style', 'position: absolute; left: 180px; top: 10px; ' +
'font-weight: BOLD; font-family: arial; ' +
'font-size: 13px;');
title.innerHTML = 'File your bugs with BITE';
popup.appendChild(title);
// Create a bullet point and append it to the popup container.
var simplifyBullet = document.createElement('span');
simplifyBullet.setAttribute('style', 'position: absolute; left: 185px; ' +
'top: 35px; font-family: arial; ' +
'font-size: 13px;');
simplifyBullet.innerHTML = '<li>Simplifies Bug Filing</li>';
popup.appendChild(simplifyBullet);
// Create another bullet point and append it to the popup container.
var attachesBullet = document.createElement('span');
attachesBullet.setAttribute('style', 'position: absolute; left: 185px; ' +
'top: 52px; font-family: arial; ' +
'font-size: 13px;');
attachesBullet.innerHTML = '<li>Attaches Debug Data</li>';
popup.appendChild(attachesBullet);
// Create a final bullet point and append it to the popup container.
var learnMoreBullet = document.createElement('span');
learnMoreBullet.setAttribute('style', 'position: absolute; left: 185px; ' +
'top: 69px; font-family: arial; ' +
'font-size: 13px;');
learnMoreBullet.innerHTML = '<li>Learn more at <a style="color: #22A" ' +
'href="" target="_blank">' +
'go/bite</a></li>';
popup.appendChild(learnMoreBullet);
// Create a download link and append it to the popup container.
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', 'http://YOUR_SERVER/' +
'get_latest_extension');
downloadLink.setAttribute('style', 'position: absolute; top: 104px; ' +
'left: 40px; color: #22A; font-family: ' +
'arial; font-size: 11px; ' +
'cursor:pointer');
downloadLink.setAttribute('target', '_blank');
downloadLink.innerHTML = 'Download and Install the BITE chrome extension';
downloadLink.addEventListener('click', biteFuncBind(this.remove, this),
false);
popup.appendChild(downloadLink);
// Create the arrow effect at the top of the top this is done in two phases,
// with this being the base
var arrowBase = document.createElement('div');
arrowBase.setAttribute('style', 'position: absolute; top: -20px; ' +
'left: 260px; width: 0; height: 0; ' +
'border-width: 10px; border-style: solid; ' +
'border-color: transparent transparent ' +
'rgba(0,0,0,0.2) transparent');
popup.appendChild(arrowBase);
// Create the white area of the arrow to overlay on top of the base.
var arrow = document.createElement('div');
arrow.setAttribute('style', 'position: absolute; top: -18px; left: 260px; ' +
'width: 0; height: 0; border-width: 10px; ' +
'border-style: solid; border-color: ' +
'transparent transparent #fff transparent');
popup.appendChild(arrow);
// Add the event listeners for mouse-in and mouse-out.
popup.addEventListener('mouseover', biteFuncBind(this.create, this),
false);
popup.addEventListener('mouseout', biteFuncBind(this.remove, this),
false);
// Finally attach the popup to the document body, not the "parent" element
// itself as that can result in the popup being clipped and not displaying
// properly.
document.body.appendChild(popup);
};
/**
* Determines whether the popup exists by doing a getElementById.
* @return {boolean} Whether the popup exists or not.
* @private
*/
bitePopup.prototype.isOpen_ = function() {
var popup = document.getElementById(bitePopup.BITE_POPUP_CONTAINER_ID);
return !!popup;
};
/**
* Flags the popup for removal and kicks off a thread to conditionally
* destroy it.
* @export
*/
bitePopup.prototype.remove = function() {
this.removeFlag_ = true;
setTimeout(biteFuncBind(this.destroyPopupIfFlagged_, this),
bitePopup.BITE_POPUP_DURATION_MS_);
};
/**
* Destroys the BITE popup if it's flagged for removal.
* @private
*/
bitePopup.prototype.destroyPopupIfFlagged_ = function() {
if (this.removeFlag_) {
this.destroy_();
}
};
/**
* Destroys the BITE popup.
* @private
*/
bitePopup.prototype.destroy_ = function() {
var popup = document.getElementById(bitePopup.BITE_POPUP_CONTAINER_ID);
if (popup) {
popup.parentNode.removeChild(popup);
}
};
// Create an instance of the BITE popup.
var popupInstance = new bitePopup(BITE_BUTTON_ID);
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the Set's details page.
*
* @author phu@google.com (Po Hu)
*/
goog.require('bite.server.Set');
goog.require('goog.Uri.QueryData');
goog.require('goog.dom');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.net.XhrIo');
var stubs_ = new goog.testing.PropertyReplacer();
var mockControl_ = null;
function setUp() {
mockControl_ = new goog.testing.MockControl();
stubs_.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send);
}
function tearDown() {
mockControl_.$tearDown();
mockControl_ = null;
goog.testing.net.XhrIo.sendInstances_ = [];
stubs_.reset();
}
function testLoadSuiteFromServer() {
var set = new bite.server.Set();
set.loadSuiteFromServer('a', 'b', 'c');
var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0];
var sentUri = sendInstance.getLastUri();
assertEquals('/suite/load', sentUri);
}
function testSaveSetToServer() {
var elem = goog.dom.createDom('div', {'id': 'setName',
'value': 'abc'});
goog.dom.appendChild(goog.dom.getDocument().body, elem);
var set = new bite.server.Set();
set.saveSetToServer();
var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0];
var sentUri = sendInstance.getLastUri();
assertEquals('/suite/add', sentUri);
}
function testParseParams() {
var elem = goog.dom.createDom('div', {'id': 'mainnav-overview',
'value': 'abc',
'class': 'mainnav-item'});
goog.dom.appendChild(goog.dom.getDocument().body, elem);
var elem2 = goog.dom.createDom('div', {'id': 'setTabDetailDiv',
'value': 'abc',
'innerHTML': ''});
goog.dom.appendChild(goog.dom.getDocument().body, elem2);
mockControl_.$replayAll();
var set = new bite.server.Set();
set.parseParams_(goog.Uri.QueryData.createFromMap({'suiteKey': 'abc'}));
mockControl_.$verifyAll();
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the tests source base class, which
* handles loading and saving tests from and to a specified source depot.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.TestSrcHelper');
/**
* A class for the source of tests related functions.
* @param {Function} loadTestsFromBackend The tests loading function.
* @constructor
* @export
*/
bite.server.TestSrcHelper = function(loadTestsFromBackend) {
/**
* Some value.
* @type {Function}
*/
this.loadTestsFromBackend = loadTestsFromBackend;
};
/**
* Shows the query fields UI.
* @export
*/
bite.server.TestSrcHelper.prototype.showQueryFields = function() {
};
/**
* Saves the inputs from fields.
* @export
*/
bite.server.TestSrcHelper.prototype.saveFields = function() {
};
/**
* Loads the inputs in fields.
* @export
*/
bite.server.TestSrcHelper.prototype.loadFields = function() {
};
/**
* Sets the fields.
* @param {Object} paramsMap A params map.
* @export
*/
bite.server.TestSrcHelper.prototype.setFields = function(paramsMap) {
};
/**
* Adds the properties to the given params map.
* @param {Object} paramsMap A params map.
* @export
*/
bite.server.TestSrcHelper.prototype.addProperties = function(paramsMap) {
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview BITE server constants.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.Constants');
/**
* The everything tab UI data in explore page.
* @type {Object}
* @export
*/
bite.server.Constants.EVERYTHING_DEFAULT_UI_DATA = {
'name': 'all',
'href': '/event/show_all',
'title': 'Everything',
'artifactTitle': 'Recent Activities',
'icon': '/images/artifacts/testing.png',
'description': 'This page shows recent activities',
'data': [],
'filters': [
{'name': 'all',
'title': 'All items',
'href': '/event/show_all',
'selected': true}]
};
/**
* The Set tab UI data in explore page.
* @type {Object}
* @export
*/
bite.server.Constants.SUITES_DEFAULT_UI_DATA = {
'name': 'suites',
'href': '/suite/show_all',
'title': 'Sets',
'icon': '/images/artifacts/testsuite.png',
'description': 'Sets are a collection of tests intended to ' +
'be run under a specific configuration(s).',
'data': [],
'filters': [
{'name': 'all',
'title': 'All items',
'href': '/suite/show_all',
'selected': true}]
};
/**
* The Runs tab UI data in explore page.
* @type {Object}
* @export
*/
bite.server.Constants.RUNS_DEFAULT_UI_DATA = {
'name': 'runs',
'title': 'Runs',
'href': '/run/show_all',
'icon': '/images/artifacts/testrun.png',
'description': 'Runs are an execution of a set of tests. ' +
'Results are stored in the test case manager.',
'filters': [
{'name': 'all',
'title': 'All items',
'href': '/run/show_all?filter=all'},
{'name': 'completed',
'title': 'Completed',
'href': '/run/show_all?filter=completed'},
{'name': 'running',
'title': 'Running',
'href': '/run/show_all?filter=running'},
{'name': 'scheduled',
'title': 'Scheduled',
'href': '/run/show_all?filter=scheduled'}]
};
/**
* The top navigation data in all pages.
* @type {Array}
* @export
*/
bite.server.Constants.TOP_NAV_DEFAULT_DATA = [
];
/**
* The tab id and tab data's map in explore page.
* @type {Object}
* @export
*/
bite.server.Constants.NAV_DETAILS_MAP = {
'all': bite.server.Constants.EVERYTHING_DEFAULT_UI_DATA,
'suites': bite.server.Constants.SUITES_DEFAULT_UI_DATA,
'runs': bite.server.Constants.RUNS_DEFAULT_UI_DATA
};
/**
* The main navigations UI data in explore page.
* @type {Array}
* @export
*/
bite.server.Constants.DEFAULT_MAINNAVS_EXPLORE_PAGE = [
{'name': 'all',
'title': 'Everything',
'path': '/event/show_all'},
{'name': 'suites',
'title': 'Sets',
'path': '/suite/show_all'},
{'name': 'runs',
'title': 'Runs',
'path': '/run/show_all'}
];
/**
* The main navigations UI data in project explore page.
* @type {Array}
* @export
*/
bite.server.Constants.MAINNAVS_PROJECT_EXPLORE_PAGE = [
{'name': 'projects',
'title': 'Projects'}
];
/**
* The main navigations UI data in Set's details page.
* @type {Array}
* @export
*/
bite.server.Constants.DEFAULT_MAINNAVS_DETAILS_PAGE = [
{'name': 'runs',
'title': 'Runs',
'href': ''}
];
/**
* The main navigations UI data in Run's details page.
* @type {Array}
* @export
*/
bite.server.Constants.DEFAULT_MAINNAVS_RUN_DETAILS_PAGE = [
{'name': 'results',
'title': 'Results',
'href': ''}
];
/**
* The main navigations UI data in Project's details page.
* @type {Array}
* @export
*/
bite.server.Constants.DEFAULT_MAINNAVS_PROJECT_DETAILS_PAGE = [
{'name': 'general',
'title': 'General',
'href': ''},
{'name': 'members',
'title': 'Members',
'href': ''},
{'name': 'settings',
'title': 'Settings',
'href': ''}
];
/**
* The left navigations UI data in runs tab of Set's details page.
* @type {Array}
* @export
*/
bite.server.Constants.DETAILS_RUNS_LEFT_NAVIGATION = [
{'name': 'all',
'title': 'All'},
{'name': 'day1',
'title': 'Past 24 hours'},
{'name': 'day2',
'title': 'Past 2 days'},
{'name': 'day7',
'title': 'Past week'},
{'name': 'running',
'title': 'Running'},
{'name': 'queued',
'title': 'Queued'},
{'name': 'completed',
'title': 'Completed'}
];
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the helper functions.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.Helper');
goog.require('goog.Timer');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.string');
goog.require('goog.ui.ComboBox');
/**
* A class for helper functions.
* @constructor
* @export
*/
bite.server.Helper = function() {
};
/**
* Updates the selected item's css.
* @param {Element} elem The element was clicked.
* @param {string} normalCss The css for unselected choice.
* @param {string} selectedCss The css for selected choice.
* @export
*/
bite.server.Helper.updateSelectedCss = function(
elem, normalCss, selectedCss) {
var mainNavs = goog.dom.getElementsByClass(normalCss);
for (var i = 0, len = mainNavs.length; i < len; i++) {
goog.dom.setProperties(mainNavs[i], {'class': normalCss});
}
goog.dom.setProperties(elem, {'class': selectedCss});
};
/**
* Gets the url string with the given parameters.
* @param {string} serverUrl The server url.
* @param {string} requestPath The request path of the server.
* @param {!Object} paramMap The param map object.
* @return {string} the request url.
* @export
*/
bite.server.Helper.getUrl = function(
serverUrl, requestPath, paramMap) {
var request = goog.Uri.parse(serverUrl);
request.setPath(requestPath);
var data = goog.Uri.QueryData.createFromMap(paramMap);
request.setQueryData(data);
return request.toString();
};
/**
* Gets the url with hash data by the given parameters.
* @param {string} serverUrl The server url.
* @param {string} requestPath The request path of the server.
* @param {!Object} paramMap The param map object.
* @return {string} the request url.
* @export
*/
bite.server.Helper.getUrlHash = function(
serverUrl, requestPath, paramMap) {
var request = goog.Uri.parse(serverUrl);
request.setPath(requestPath);
var data = goog.Uri.QueryData.createFromMap(paramMap).toString();
request.setFragment(data, true);
return request.toString();
};
/**
* Adds listeners to a group of elements.
* @param {Array} elems The elements to be added listeners.
* @param {Function} callback The callback function.
* @export
*/
bite.server.Helper.addListenersToElems = function(
elems, callback) {
for (var i = 0, len = elems.length; i < len; i++) {
goog.events.listen(
elems[i], 'click', callback);
}
};
/**
* Adds listeners to a group of elements.
* @param {Array} array The data array.
* @param {string} name The sample name.
* @param {string} value The sample value.
* @param {string} requestedName The requested name.
* @return {*} The requested name's value.
* @export
*/
bite.server.Helper.getValueInArray = function(
array, name, value, requestedName) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i][name] == value) {
return array[i][requestedName];
}
}
return null;
};
/**
* Draws the chart.
* @param {number} passed The passed number.
* @param {number} failed The failed number.
* @param {number} uncompleted The uncompleted number.
* @suppress {missingProperties} google.visualization.DataTable and
* google.visualization.ImageBarChart
* @export
*/
bite.server.Helper.drawBarChart = function(passed, failed, uncompleted) {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'tests');
data.addColumn('number', 'passed');
data.addColumn('number', 'failed');
data.addColumn('number', 'uncompleted');
data.addRows(1);
data.setCell(0, 0, '');
data.setCell(0, 1, passed);
data.setCell(0, 2, failed);
data.setCell(0, 3, uncompleted);
// Create and draw the visualization.
new google.visualization.ImageBarChart(goog.dom.getElement('visualization')).
draw(data, {'isStacked': true, 'width': 400, 'height': 100,
'colors': ['00FF00', 'FF0000', 'C0C0C0']
});
};
/**
* Draws the pie chart.
* @param {number} passed The passed number.
* @param {number} failed The failed number.
* @param {number} uncompleted The uncompleted number.
* @suppress {missingProperties} google.visualization.DataTable and
* google.visualization.PieChart
* @export
*/
bite.server.Helper.drawPieChart = function(passed, failed, uncompleted) {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Status');
data.addColumn('number', 'Number');
data.addRows(3);
data.setValue(0, 0, 'Passed');
data.setValue(0, 1, passed);
data.setValue(1, 0, 'Failed');
data.setValue(1, 1, failed);
data.setValue(2, 0, 'Uncompleted');
data.setValue(2, 1, uncompleted);
// Create and draw the visualization.
new google.visualization.PieChart(goog.dom.getElement('visualization')).
draw(data, {'width': 200, 'height': 200,
'colors': ['00FF00', 'FF0000', 'C0C0C0'],
'legend': 'none'
});
};
/**
* Splits a string and trim each elements.
* @param {string} str The string to be splited.
* @param {string} delimiter Used to split the string.
* @return {Array} The result array.
*/
bite.server.Helper.splitAndTrim = function(str, delimiter) {
var result = [];
var arr = str.split(delimiter);
for (var i = 0, len = arr.length; i < len; i++) {
result.push(goog.string.trim(arr[i]));
}
return result;
};
/**
* Creates the project selector for choosing options.
* @param {Array} options The options to be showed in selector.
* @param {string} id The id of the div where the selector will be rendered.
* @param {string} text The default text.
* @return {goog.ui.ComboBox} The combobox instance.
* @export
*/
bite.server.Helper.createSelector = function(options, id, text) {
var projectSelector_ = new goog.ui.ComboBox();
projectSelector_.setUseDropdownArrow(true);
projectSelector_.setDefaultText(text);
for (var i = 0, len = options.length; i < len; ++i) {
var pName = '';
var pId = '';
if (goog.isString(options[i])) {
pName = options[i];
pId = options[i];
} else {
pName = options[i]['name'];
pId = options[i]['id'];
}
var option = new goog.ui.ComboBoxItem(pName);
goog.dom.setProperties(/** @type {Element} */ (option), {'id': pId});
projectSelector_.addItem(option);
}
projectSelector_.render(goog.dom.getElement(id));
return projectSelector_;
};
/**
* Joins the list or returns the string directly.
* @param {string|Array} strOrArr The given array or string.
* @param {string} delimiter The delimiter string.
* @return {string} The result string.
*/
bite.server.Helper.joinToStr = function(strOrArr, delimiter) {
return typeof strOrArr == 'string' ? strOrArr : strOrArr.join(delimiter);
};
/**
* Displays a status message in Google bar, and optionally dismiss it.
* @param {string} message The message to be displayed.
* @param {number=} opt_timeout The optional time out to hide the message.
* @param {boolean=} opt_error Whether this is an error message.
*/
bite.server.Helper.displayMessage = function(message, opt_timeout, opt_error) {
goog.dom.getElement('statusMessage').innerHTML = message;
var elem = goog.dom.getElement('statusMessageDiv');
if (opt_error) {
goog.dom.setProperties(elem, {'class': 'kd-butterbar error shown'});
} else {
goog.dom.setProperties(elem, {'class': 'kd-butterbar shown'});
}
if (opt_timeout) {
goog.Timer.callOnce(bite.server.Helper.dismissMessage, opt_timeout);
}
};
/**
* Dismisses the message.
*/
bite.server.Helper.dismissMessage = function() {
var elem = goog.dom.getElement('statusMessageDiv');
goog.dom.setProperties(elem, {'class': 'kd-butterbar'});
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the details page's all tab.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.set.Overview');
goog.require('bite.server.Helper');
goog.require('bite.server.set.Tab');
goog.require('bite.server.templates.details');
goog.require('goog.dom');
goog.require('goog.json');
/**
* A class for the set, which is a group of tests.
* @param {function():Object} getInfoFunc The function to get the set's info.
* @extends {bite.server.set.Tab}
* @constructor
* @export
*/
bite.server.set.Overview = function(getInfoFunc) {
/**
* The function to get the info of selected item.
* @type {function():Object}
* @private
*/
this.getInfoFunc_ = getInfoFunc;
/**
* The set's description.
* @type {string}
*/
this.description = '';
/**
* The set's labels.
* @type {Array.<string>}
*/
this.labels = [];
/**
* The set's project name.
* @type {string}
*/
this.biteProject = 'BITE';
};
goog.inherits(bite.server.set.Overview, bite.server.set.Tab);
/**
* Inits the setting's overview page.
* @param {Element} tabDetailsDiv The tab details div.
* @export
*/
bite.server.set.Overview.prototype.init = function(tabDetailsDiv) {
tabDetailsDiv.innerHTML = bite.server.templates.details.showTabOverview({});
this.loadSetting();
};
/**
* Saves the previous page settings. This is called when another tab is
* selected.
* @export
*/
bite.server.set.Overview.prototype.saveSetting = function() {
this.biteProject = goog.dom.getElement('setProject').value;
this.description = goog.dom.getElement('setDesc').value;
this.labels = bite.server.Helper.splitAndTrim(
goog.dom.getElement('setLabels').value, ',');
};
/**
* Loads the page's settings. This is called when the overview tab is selected.
* @export
*/
bite.server.set.Overview.prototype.loadSetting = function() {
goog.dom.getElement('setProject').value = this.biteProject;
goog.dom.getElement('setDesc').value = this.description;
goog.dom.getElement('setLabels').value = bite.server.Helper.joinToStr(
this.labels, ',');
};
/**
* Sets the default properties. This is called when a set is loaded, and
* a map of params will be passed in.
* @param {Object} params The parameter map.
* @export
*/
bite.server.set.Overview.prototype.setProperties = function(params) {
this.description = params['description'];
this.labels = goog.json.parse(params['labels'])['labels'];
this.biteProject = params['projectName'];
};
/**
* Adds the properties to the given map. This is called when a set is saved,
* and this function adds parameters to the map to be sent to the server.
* @param {Object} params The parameter map.
* @export
*/
bite.server.set.Overview.prototype.addProperties = function(params) {
params['projectName'] = this.biteProject;
params['description'] = this.description;
params['labels'] = goog.json.serialize({'labels': this.labels});
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the details page's runs tab.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.set.Runs');
goog.require('bite.server.Constants');
goog.require('bite.server.Helper');
goog.require('bite.server.explore.RunTab');
goog.require('bite.server.set.Tab');
goog.require('bite.server.templates.details.SetRuns');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.net.XhrIo');
/**
* A class for the runs tab in the set page.
* @param {function():Object} getInfoFunc The getter for set's info.
* @extends {bite.server.set.Tab}
* @constructor
* @export
*/
bite.server.set.Runs = function(getInfoFunc) {
/**
* A function to get the selected item's info.
* @type {function():Object}
* @private
*/
this.getInfoFunc_ = getInfoFunc;
/**
* The instance of bite.server.explore.RunTab.
* @type {bite.server.explore.RunTab}
* @private
*/
this.testsExploreRunHelper_ = new bite.server.explore.RunTab(
goog.bind(this.getProjectName_, this));
};
goog.inherits(bite.server.set.Runs, bite.server.set.Tab);
/**
* Inits the setting's overview page.
* @param {Element} tabDetailsDiv The tab details div.
* @export
*/
bite.server.set.Runs.prototype.init = function(tabDetailsDiv) {
tabDetailsDiv.innerHTML = bite.server.templates.details.SetRuns.showTabRuns(
{'data': bite.server.Constants.DETAILS_RUNS_LEFT_NAVIGATION});
var leftNavs = /** @type {Array} */
(goog.dom.getElementsByClass('kd-sidebarlistitem'));
bite.server.Helper.addListenersToElems(
leftNavs,
goog.bind(this.listenFilterRuns, this));
this.filterRuns('all', goog.dom.getElement('all'));
};
/**
* Gets the project name.
* @return {string} The project name.
* @private
*/
bite.server.set.Runs.prototype.getProjectName_ = function() {
return this.getInfoFunc_()['projectName'];
};
/**
* Listens to select a choice to filter the runs.
* @param {Object} event The event object.
* @export
*/
bite.server.set.Runs.prototype.listenFilterRuns = function(event) {
this.filterRuns(event.currentTarget.id, event.currentTarget);
};
/**
* Selects a choice to filter the runs.
* @param {string} filter The filter choice.
* @param {Element} elem The filter element was clicked.
* @export
*/
bite.server.set.Runs.prototype.filterRuns = function(filter, elem) {
goog.dom.getElement('main_preview').innerHTML = '';
bite.server.Helper.updateSelectedCss(
elem, 'kd-sidebarlistitem',
'kd-sidebarlistitem selected');
var requestUrl = bite.server.Helper.getUrl(
'',
'/run/same_suite',
{});
var parameters = goog.Uri.QueryData.createFromMap(
{'suiteKey': this.getInfoFunc_()['suiteKey'],
'suiteName': this.getInfoFunc_()['suiteName'],
'projectName': this.getInfoFunc_()['projectName'],
'filter': filter}).toString();
goog.net.XhrIo.send(
requestUrl,
goog.bind(this.filterRunsCallback_, this),
'POST',
parameters);
bite.server.Helper.displayMessage('Loading runs...', 30 * 1000);
};
/**
* Callback after selecting a choice to filter the runs.
* @param {Event} event The event object.
* @private
*/
bite.server.set.Runs.prototype.filterRunsCallback_ = function(event) {
var xhr = /** @type {goog.net.XhrIo} */ (event.target);
if (xhr.isSuccess()) {
var runs_obj = xhr.getResponseJson();
if (runs_obj) {
goog.dom.getElement('filteredRuns').innerHTML =
bite.server.templates.details.SetRuns.showFilteredRuns(runs_obj);
var dataRows = /** @type {Array} */
(goog.dom.getElementsByClass('data-row'));
var layoutHelper = bite.server.LayoutHelper.getInstance();
bite.server.Helper.addListenersToElems(
dataRows,
goog.bind(layoutHelper.selectArtifact,
layoutHelper,
goog.bind(this.testsExploreRunHelper_.onArtifactSelected,
this.testsExploreRunHelper_)));
var dataActions = /** @type {Array} */
(goog.dom.getElementsByClass('data-action'));
bite.server.Helper.addListenersToElems(
dataActions,
goog.bind(
this.testsExploreRunHelper_.handleUserOperation,
this.testsExploreRunHelper_));
}
bite.server.Helper.dismissMessage();
} else {
throw new Error('Failed to get the runs. Error status: ' +
xhr.getStatus());
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the run details page's settings tab.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.run.Settings');
goog.require('bite.server.Helper');
goog.require('bite.server.set.Tab');
goog.require('bite.server.templates.details.RunSettings');
goog.require('goog.dom');
goog.require('goog.json');
goog.require('goog.string');
/**
* A class for the settings tab in the Run's page.
* @param {function():string} getKeyFunc The getter for set's key.
* @extends {bite.server.set.Tab}
* @constructor
* @export
*/
bite.server.run.Settings = function(getKeyFunc) {
/**
* A function used to get the selected item's key string.
* @type {function():string}
* @private
*/
this.getKeyFunc_ = getKeyFunc;
/**
* The run's token string.
* @type {string}
* @private
*/
this.token_ = '';
/**
* The run's start url string.
* @type {string}
* @private
*/
this.startUrl_ = '';
/**
* The run's line timeout limit.
* @type {number}
* @private
*/
this.lineTimeout_ = 0;
/**
* The run's test timeout limit.
* @type {number}
* @private
*/
this.testTimeout_ = 0;
/**
* The run's filtered results labels.
* @type {Array}
* @private
*/
this.filteredResultLabels_ = [];
/**
* The run's test dimension labels.
* @type {Array}
* @private
*/
this.dimensionLabels_ = [];
/**
* Whether to save the screenshots.
* @type {boolean}
* @private
*/
this.saveScnShots_ = true;
};
goog.inherits(bite.server.run.Settings, bite.server.set.Tab);
/**
* Inits the Run page's settings page.
* @param {Element} tabDetailsDiv The tab details div.
* @export
*/
bite.server.run.Settings.prototype.init = function(tabDetailsDiv) {
tabDetailsDiv.innerHTML =
bite.server.templates.details.RunSettings.showTabSettings({});
this.loadSetting();
};
/**
* Saves the previous page settings. This is called when another tab is
* selected.
* @export
*/
bite.server.run.Settings.prototype.saveSetting = function() {
this.filteredResultLabels_ = bite.server.Helper.splitAndTrim(
goog.dom.getElement('runFilteredLabels').value, ',');
this.dimensionLabels_ = bite.server.Helper.splitAndTrim(
goog.dom.getElement('runDimensionLabels').value, ',');
this.token_ = goog.dom.getElement('runWorkerToken').value;
this.startUrl_ = goog.dom.getElement('runStartUrl').value;
this.lineTimeout_ = goog.dom.getElement('runLineTimeout').value;
this.testTimeout_ = goog.dom.getElement('runTestTimeout').value;
this.saveScnShots_ = goog.dom.getElement('runSaveScnShots').checked;
};
/**
* Loads the page's settings. This is called when the settings tab is selected.
* @export
*/
bite.server.run.Settings.prototype.loadSetting = function() {
goog.dom.getElement('runFilteredLabels').value =
bite.server.Helper.joinToStr(this.filteredResultLabels_, ',');
goog.dom.getElement('runDimensionLabels').value =
bite.server.Helper.joinToStr(this.dimensionLabels_, ',');
goog.dom.getElement('runWorkerToken').value = this.token_;
goog.dom.getElement('runStartUrl').value = this.startUrl_;
goog.dom.getElement('runLineTimeout').value = this.lineTimeout_;
goog.dom.getElement('runTestTimeout').value = this.testTimeout_;
goog.dom.getElement('runSaveScnShots').checked = this.saveScnShots_;
};
/**
* Sets the default properties. This is called when loading a set from server.
* @param {Object} params The parameter map.
* @export
*/
bite.server.run.Settings.prototype.setProperties = function(params) {
this.filteredResultLabels_ = params['filteredLabels'];
this.dimensionLabels_ = params['dimensionLabels'];
this.token_ = params['runTokens'];
this.startUrl_ = params['runStartUrl'];
this.lineTimeout_ = 0;
this.testTimeout_ = 0;
this.saveScnShots_ = true;
};
/**
* Adds the properties to the given map. This is called when it creates
* a map of properties to be saved to server.
* @param {Object} params The parameter map.
* @export
*/
bite.server.run.Settings.prototype.addProperties = function(params) {
params['runTokens'] = this.token_;
params['runStartUrl'] = this.startUrl_;
params['filteredLabels'] = goog.json.serialize(this.filteredResultLabels_);
params['dimensionLabels'] = goog.json.serialize(this.dimensionLabels_);
params['lineTimeout'] = this.lineTimeout_;
params['testTimeout'] = this.testTimeout_;
params['saveScnShots'] = this.saveScnShots_;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for the layout class.
*
* @author phu@google.com (Po Hu)
*/
goog.require('bite.server.LayoutHelper');
goog.require('goog.dom');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.mockmatchers');
goog.require('goog.testing.net.XhrIo');
var stubs_ = new goog.testing.PropertyReplacer();
var mockControl_ = null;
function setUp() {
mockControl_ = new goog.testing.MockControl();
stubs_.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send);
}
function tearDown() {
mockControl_.$tearDown();
mockControl_ = null;
goog.testing.net.XhrIo.sendInstances_ = [];
stubs_.reset();
}
function testHandleLeftNavChanges() {
var id = 'leftnav-abc';
var mockCallbackOnSelectFunc = mockControl_.createFunctionMock();
mockCallbackOnSelectFunc().$returns();
var mockCallbackOnActionFunc = mockControl_.createFunctionMock();
mockCallbackOnActionFunc().$returns();
var elem = goog.dom.createDom('div', {'id': id,
'class': 'leftnav-item'});
goog.dom.appendChild(goog.dom.getDocument().body, elem);
var layoutHelper = new bite.server.LayoutHelper();
layoutHelper.handleLeftNavChanges(
id,
[],
mockCallbackOnSelectFunc,
mockCallbackOnActionFunc);
var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0];
var sentUri = sendInstance.getLastUri();
assertEquals('', sentUri);
}
function testSelectArtifact() {
var target = goog.dom.createDom('input', {'id': 'abc_def',
'name': '123'});
var target2 = goog.dom.createDom('div', {'id': 'abc_defmore',
'name': '123'});
goog.dom.appendChild(goog.dom.getDocument().body, target2);
var event = {'currentTarget': target};
var callback = mockControl_.createFunctionMock();
callback('123', 'def', '').$returns();
mockControl_.$replayAll();
var helper = new bite.server.LayoutHelper();
helper.selectArtifact(callback, event);
assertObjectEquals(helper.selectedArtifact_, target);
mockControl_.$verifyAll();
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the Result page class.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.server.Result');
goog.require('bite.server.Constants');
goog.require('bite.server.LayoutHelper');
goog.require('bite.server.Page');
goog.require('bite.server.Helper');
goog.require('bite.server.run.Overview');
goog.require('bite.server.run.Settings');
goog.require('bite.server.run.Results');
goog.require('bite.server.set.Tab');
goog.require('bite.server.templates.details.ResultPage');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.net.XhrIo');
goog.require('goog.ui.CustomButton');
/**
* A class for result's details page.
* @extends {bite.server.Page}
* @constructor
* @export
*/
bite.server.Result = function() {
};
goog.inherits(bite.server.Result, bite.server.Page);
/**
* Inits the result page.
* @param {Object} paramsMap The params map of the url hash.
*/
bite.server.Result.prototype.init = function(paramsMap) {
var baseHeader = goog.dom.getElement('baseHeader');
baseHeader.innerHTML =
bite.server.templates.details.ResultPage.showHeader();
var baseView = goog.dom.getElement('baseView');
baseView.innerHTML = bite.server.templates.details.ResultPage.showBodyArea();
this.parseParams_(paramsMap);
};
/**
* Parses the given params and perform accordingly.
* @param {Object} paramsMap The params map.
* @private
*/
bite.server.Result.prototype.parseParams_ = function(paramsMap) {
var resultKey = paramsMap.get('resultKey') || '';
if (resultKey) {
this.loadResultFromServer_(resultKey);
}
};
/**
* Loads the result info from server.
* @param {string} resultKey The result's key string.
* @private
*/
bite.server.Result.prototype.loadResultFromServer_ = function(resultKey) {
var requestUrl = bite.server.Helper.getUrl(
'',
'/result/view',
{});
var parameters = goog.Uri.QueryData.createFromMap(
{'resultKey': resultKey}).toString();
goog.net.XhrIo.send(requestUrl, goog.bind(function(e) {
var xhr = e.target;
if (xhr.isSuccess()) {
var result = xhr.getResponseJson();
goog.dom.getElement('resultScreenshot').src = result['screenshot'];
} else {
throw new Error('Failed to get the Run template: ' +
xhr.getStatus());
}
}, this), 'POST', parameters);
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview User visible messages for bite.
* @author michaelwill@google.com (Michael Williamson)
*/
goog.provide('bite.client.messages');
/** @desc Tests option title. */
var MSG_POPUP_OPTION_TEST_NAME = goog.getMsg('Tests');
/** @desc Tests option info. */
var MSG_POPUP_OPTION_TEST_DESC = goog.getMsg('Find and run manual tests.');
/** @desc Bugs option title. */
var MSG_POPUP_OPTION_BUGS_NAME = goog.getMsg('Bugs');
/** @desc Bugs option info. */
var MSG_POPUP_OPTION_BUGS_DESC = goog.getMsg(
'Visualize existing bugs or file new ones.');
/** @desc Report Bug option title. */
var MSG_POPUP_OPTION_REPORT_BUG_NAME = goog.getMsg('Report Bug');
/** @desc Report Bug option info. */
var MSG_POPUP_OPTION_REPORT_BUG_DESC = goog.getMsg(
'File a bug against this page (Ctrl+Alt+B)');
/** @desc Close option title. */
var MSG_POPUP_OPTION_CLOSE_NAME = goog.getMsg('Close Consoles');
/** @desc Close option info. */
var MSG_POPUP_OPTION_CLOSE_DESC = goog.getMsg(
'Close all BITE consoles in all windows.');
/** @desc Record and playback option title. */
var MSG_POPUP_OPTION_FLUX_NAME = goog.getMsg('Record/Playback');
/** @desc Record and playback option info. */
var MSG_POPUP_OPTION_FLUX_DESC = goog.getMsg(
'Record and playback UI automation.');
/** @desc Layers option title. */
var MSG_POPUP_OPTION_LAYERS_NAME = goog.getMsg('Layers');
/** @desc Layers option info. */
var MSG_POPUP_OPTION_LAYERS_DESC = goog.getMsg(
'Create or use custom tools and scripts.');
/** @desc Sets option title. */
var MSG_POPUP_OPTION_SETS_NAME = goog.getMsg('Sets');
/** @desc Sets option info. */
var MSG_POPUP_OPTION_SETS_DESC = goog.getMsg(
'Manage and analyze collections of tests.');
/** @desc Risk option title. */
var MSG_POPUP_OPTION_RISK_NAME = goog.getMsg('Risk');
/** @desc Risk option info. */
var MSG_POPUP_OPTION_RISK_DESC = goog.getMsg(
'Track risk and test analytics.');
/** @desc Admin option title. */
var MSG_POPUP_OPTION_ADMIN_NAME = goog.getMsg('Admin');
/** @desc Admin option info. */
var MSG_POPUP_OPTION_ADMIN_DESC = goog.getMsg(
'Manage projects, layers and security.');
/** @desc Help option title. */
var MSG_POPUP_OPTION_HELP_NAME = goog.getMsg('Help');
/** @desc Help option info. */
var MSG_POPUP_OPTION_HELP_DESC = goog.getMsg('Learn how to use BITE.');
/** @desc Settings option title. */
var MSG_POPUP_OPTION_SETTINGS_NAME = goog.getMsg('Settings');
/** @desc Settings option info. */
var MSG_POPUP_OPTION_SETTINGS_DESC = goog.getMsg('Configure BITE.');
/**
* @param {string} uri The url that will help the user in
* the event of an error.
* @return {string} The message.
*/
function CALL_MSG_POPUP_LOGIN_ERROR(uri) {
/** @desc A login error string. */
var MSG_POPUP_LOGIN_ERROR = goog.getMsg(
'There was a problem logging in.<br>' +
'<a href="{$uri}" target="_blank">Try logging in here</a>.',
{uri: uri});
return MSG_POPUP_LOGIN_ERROR;
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A method for mapping mouse position to DOM Element. The
* approach used is to store a list of DOM Elements and associated information.
* When a request for elements at a given (x,y) position is given the list
* will be linearly traversed and the coordinate will be checked to see if
* falls within the element.
*
* This approach was chosen for reduced space requirements. An alternative
* memory intensive, but quick lookup, is to keep a two-dimensional array of
* ids that map to the element and its information. The other issue with this
* approach is that the data would need to be recalculated upon screen resize.
* The current approach does not have this requirement as long as the position
* and dimensions are explicitly recorded along with the element.
*
* Revisit this approach and bug overlays in general to scale to much larger
* numbers of bugs. Current estimates is in the hundreds per page (small).
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.client.ElementMapper');
goog.require('goog.style');
/**
* A class that allows a mapping of window position to DOM Element.
* @constructor
*/
bite.client.ElementMapper = function() {
/**
* The list of overlay elements.
* @type {Array.<{element: !Element, info: !Object}>}
* @private
*/
this.elements_ = [];
};
/**
* Adds an element to the list. For speed, duplicates are not checked for.
* @param {!Element} element The element to record.
* @param {!Object} info The information to be recorded with the element.
*/
bite.client.ElementMapper.prototype.add = function(element, info) {
this.elements_.push({element: element, info: info});
};
/**
* Returns all Element Info objects stored in the mapper.
* @return {Array.<!Object>} The data.
*/
bite.client.ElementMapper.prototype.all = function() {
var data = [];
for (var i = 0; i < this.elements_.length; ++i) {
data.push(this.elements_[i].info);
}
return data;
};
/**
* Clears the list of elements.
*/
bite.client.ElementMapper.prototype.clear = function() {
this.elements_ = [];
};
/**
* Retrieves the information associated with the DOM Elements at the given
* coordinate.
* @param {number} x The x coordinate.
* @param {number} y The y coordinate.
* @return {Array.<!Object>} An array of information objects.
*/
bite.client.ElementMapper.prototype.find = function(x, y) {
var data = [];
for (var i = 0; i < this.elements_.length; ++i) {
var elementObj = this.elements_[i];
var element = elementObj.element;
var position = goog.style.getPageOffset(element);
var dimension = goog.style.getSize(element);
if (x >= position.x && x < position.x + dimension.width &&
y >= position.y && y < position.y + dimension.height) {
data.push(elementObj.info);
}
}
return data;
};
/**
* Remove an element from the list.
* @param {!Element} element The element to remove.
*/
bite.client.ElementMapper.prototype.remove = function(element) {
for (var i = 0; i < this.elements_.length; ++i) {
if (this.elements_[i].element == element) {
this.elements_.splice(i, 1);
return;
}
}
};
/**
* Remove duplicate element references from the list in case one did not ensure
* this to be the case.
*/
bite.client.ElementMapper.prototype.removeDuplicates = function() {
var oldElements = this.elements_;
this.elements_ = [];
for (var i = 0; i < oldElements.length; ++i) {
var element = oldElements[i].element;
var found = false;
for (var j = 0; j < this.elements_.length; ++j) {
if (this.elements_[j].element == element) {
found = true;
break;
}
}
if (!found) {
this.elements_.push(oldElements[i]);
}
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This function provides functions for manipulating the BITE
* configuration. The functions allow get/set of individual configuration
* options or as a group. It also allows users to access default option
* values and validate individual option values.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.options.data');
goog.require('bite.options.constants');
goog.require('bite.options.private_constants');
goog.require('goog.date.DateTime');
goog.require('goog.object');
/**
* Returns an object containing the default configuration where each setting's
* key is from bite.options.constants.Id.
* @return {!Object} The default configuration.
*/
bite.options.data.getAllDefaults = function() {
// Returns the entire Default enum as the Object.
return bite.options.private_constants.Default;
};
/**
* Returns the default value for the requested option.
* @param {bite.options.constants.Id} id The option to lookup.
* @return {string} The default value.
*/
bite.options.data.getDefault = function(id) {
// Retrieve the id value used as a key in the Default enum.
return bite.options.private_constants.Default[id];
};
/**
* Returns an object containing the current configuration where each setting's
* key is from bite.options.constants.Id.
* @return {!Object} The current configuration.
*/
bite.options.data.getCurrentConfiguration = function() {
// Retrieves all option values (or default value if not set) and adds them
// to the data Object, which is then returned.
var data = {};
for (var key in bite.options.constants.Id) {
var id = bite.options.constants.Id[key];
// Get current value or its default if not set.
data[id] = bite.options.data.get(id);
}
return data;
};
/**
* Returns the current setting for the specified option.
* @param {bite.options.constants.Id} id The option to lookup.
* @return {string} The current value.
*/
bite.options.data.get = function(id) {
// Determine the cache's key for the given id.
var cacheKey = bite.options.private_constants.Key[id];
// Return the cached value or the default if there is no cache value.
return /** @type {string} */ (goog.global.localStorage.getItem(cacheKey)) ||
bite.options.data.getDefault(id);
};
/**
* Uses the given data to override the configuration with the given values.
* Invalid keys are ignored, but invalid data will result in an exception
* being thrown (in string form).
* @param {!Object} data The data used to override the current configuration.
* @param {string=} opt_username The name of the user making the change. If
* not supplied then it is set to the default username.
*/
bite.options.data.updateConfiguration = function(data, opt_username) {
// Loop over all possible configuration options.
for (var key in bite.options.constants.Id) {
var id = bite.options.constants.Id[key];
// If the current option is not present in the data then move to the next
// option.
if (!(id in data)) {
continue;
}
// Update the given option with the given value. Update can throw an
// exception if the data value being passed in is not valid.
bite.options.data.update(id, data[id], opt_username);
}
};
/**
* Updates the given option with the given value. An invalid value will
* result in an exception being thrown (in string form).
* @param {bite.options.constants.Id} id The option to update.
* @param {string} value The option's new value if valid.
* @param {string=} opt_username The name of the user making the change. If
* not supplied then it is set to the default username.
*/
bite.options.data.update = function(id, value, opt_username) {
// Before setting the current option's value, validate the given value.
// If validation fails an exception will be thrown (in string form).
// Otherwise, the function returns a processed version of the value
// suitable for caching.
var processedValue = bite.options.data.validate(id, value);
// Determine the username to use to mark the most recent update of the
// configuration.
var username = opt_username ||
bite.options.private_constants.DEFAULT_USERNAME;
// Determine the time stamp to use to make the most recent update of the
// configuration.
var date = new goog.date.DateTime();
var timestamp = date.getTime();
// Shortcut to the Key enum that contains the each setting's cache key.
var keys = bite.options.private_constants.Key;
// Cache the new option's value and a signature to mark who and when the
// configuration was updated.
goog.global.localStorage.setItem(keys[id], processedValue);
goog.global.localStorage.setItem(keys.ADMIN_LAST_SAVE_TIME, timestamp);
goog.global.localStorage.setItem(keys.ADMIN_LAST_SAVE_USER, username);
};
/**
* Validates the given value for the given option. If the value is invalid
* then an exception will be thrown (in string form).
* @param {bite.options.constants.Id} id The option to lookup.
* @param {string} value The value to validate.
* @return {string} The processed version of the value.
*/
bite.options.data.validate = function(id, value) {
// By defaulting to empty, any that make it throw will automatically return
// false for the containsValue test.
var enumToTest = {};
// Process each of the options to verify the value is valid. Each option
// will either return the processed value or throw an exception.
switch (id) {
case bite.options.constants.Id.BUG_RECORDING:
case bite.options.constants.Id.BUG_SCREENSHOT:
case bite.options.constants.Id.BUG_UI_BINDING:
bite.options.data.validateEnum_(
bite.options.constants.ThreeWayOption, value, id);
break;
case bite.options.constants.Id.BUG_STATE:
bite.options.data.validateEnum_(
bite.options.constants.StateOption, value, id);
break;
case bite.options.constants.Id.BUG_PROJECT:
bite.options.data.validateEnum_(
bite.options.constants.ProjectOption, value, id);
break;
case bite.options.constants.Id.SERVER_CHANNEL:
bite.options.data.validateEnum_(
bite.options.constants.ServerChannelOption, value, id);
break;
case bite.options.constants.Id.AUTO_RECORD:
case bite.options.constants.Id.FEATURES_BUGS:
case bite.options.constants.Id.FEATURES_RPF:
case bite.options.constants.Id.FEATURES_REPORT:
case bite.options.constants.Id.FEATURES_CLOSE:
case bite.options.constants.Id.FEATURES_TESTS:
bite.options.data.validateCheckbox_(value, id);
break;
default:
// If the id is invalid throw an exception.
throw 'ERROR: Validation failed - invalid option ' +
bite.options.constants.Id[id] + '.';
}
return value;
};
/**
* Validates an enum.
* @param {Object} enumToTest The enum that the value should be in.
* @param {string} value The value to validate.
* @param {bite.options.constants.Id} id The option.
* @private
*/
bite.options.data.validateEnum_ = function(enumToTest, value, id) {
// If the enum under test does not contain the value then throw an exception.
if (!goog.object.containsValue(enumToTest, value)) {
throw 'ERROR: Invalid value (' + value + ') for option ' + id + '.';
}
};
/**
* Validates a checkbox.
* @param {string} value The value to validate.
* @param {bite.options.constants.Id} id The option.
* @private
*/
bite.options.data.validateCheckbox_ = function(value, id) {
if (value != 'true' && value != 'false') {
throw 'ERROR: Invalid value (' + value + ') for option ' + id + '.';
}
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* BITE options/settings page controller. The BITE Options Page provides an
* interface for BITE users to change different configuration details about the
* BITE tool.
*
* @author alexto@google.com (Alexis O. Torres)
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.options.Page');
goog.require('bite.LoginManager');
goog.require('bite.options.constants');
goog.require('bite.options.data');
goog.require('bite.options.private_constants');
goog.require('bite.options.private_data');
goog.require('goog.Timer');
goog.require('goog.date.relative');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.object');
/**
* Provides the class to maintain state for the page.
* @constructor
* @export
*/
bite.options.Page = function() {
/**
* Records which configuration settings have changed.
* @type {!Object}
* @private
*/
this.changed_ = {};
/**
* The handler reference used to handle chrome extension request messages.
* A reference is required for cleanup.
* @type {Function}
* @private
*/
this.handleOnRequest_ = goog.bind(this.onRequestHandler_, this);
/**
* A flag representing whether or not this object has been destroyed.
* @type {boolean}
* @private
*/
this.isDestroyed_ = false;
/**
* A flag used to denote whether or not this object is ready for use.
* @type {boolean}
* @private
*/
this.isReady_ = false;
/**
* Manages event listeners created by this page.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
/**
* A timer used to refresh dynamic elements such as last saved time. When
* the Page object is destroyed, the timer will be disposed.
* @type {goog.Timer}
* @private
*/
this.refreshTimer_ = new goog.Timer(bite.options.Page.REFRESH_RATE_);
};
/**
* The options page DOM Element names.
*
* Some of the keys are values from bite.options.constants.Id instead of
* directly accessing the enum due to the fact that Closure can not handle
* keys in an enum being set from values in a different enum. They also can't
* handle non-capitalized, quoted strings as keys for enums. Thus this type
* is Object out of necessity.
* @type {!Object}
* @private
*/
bite.options.Page.ElementName_ = {
'project': 'bug-project',
'recording': 'bug-recording',
'screenshot': 'bug-screenshot',
'state': 'bug-state',
'uiBinding': 'bug-ui-binding',
'serverChannel': 'server-channel',
'autoRecord': 'auto-record',
'featuresBugs': 'features-bugs',
'featuresRpf' : 'features-rpf',
'featuresTests' : 'features-tests',
'featuresClose': 'features-close',
'featuresReport': 'features-report',
SAVE_BUTTON: 'save-button',
SAVE_TIME: 'save-time',
USERNAME: 'user'
};
/**
* Map option value to configuration value.
* @type {Object}
* @private
*/
bite.options.Page.MapValues_ = {
'dev': bite.options.constants.ServerChannelOption.DEV,
'rel': bite.options.constants.ServerChannelOption.RELEASE
};
/**
* The refresh rate used with a timer to determine when dynamic elements
* should be updated (refreshed). The rate is in milliseconds.
* @type {number}
* @private
*/
bite.options.Page.REFRESH_RATE_ = 5000;
/**
* Enables/disables the Save button and updates it's text.
* @param {boolean} enable Whether or not to enable the button.
* @private
*/
bite.options.Page.prototype.enableSave_ = function(enable) {
var saveButtonId = bite.options.Page.ElementName_.SAVE_BUTTON;
var saveButton = goog.dom.getElement(saveButtonId);
if (!saveButton) {
// Do nothing if the DOM Element is not found, the error should have been
// recorded in the initialization.
return;
}
saveButton.disabled = !enable;
saveButton.innerText = enable ? 'Save Now' : 'Saved';
};
/**
* Handle saving of a new configuration.
* @private
*/
bite.options.Page.prototype.handleSave_ = function() {
this.enableSave_(false);
// Assumes that the changed_ Object will only ever have iterable items for
// those option values that are stored/removed.
// If the changed_ object is empty, do nothing.
if (goog.object.isEmpty(this.changed_)) {
return;
}
var usernameId = bite.options.Page.ElementName_.USERNAME;
var usernameElement = goog.dom.getElement(usernameId);
var username = usernameElement ? usernameElement.innerText : undefined;
// Set the cached values for the configuration to the local instance managed
// by this object/UI.
bite.options.data.updateConfiguration(this.changed_, username);
// Let everyone know that the entire configuration has changed.
this.notifyChange_();
this.refreshInterface_();
this.changed_ = {};
};
/**
* Handles the onselect event for option elements and updates the configuration
* with the appropriate value.
* @param {string} key A key used to identify the option.
* @param {Event} event The event caused when the select element changes.
* @private
*/
bite.options.Page.prototype.handleSelect_ = function(key, event) {
var value = event.target.value;
value = this.processOption_(key, value);
this.updateOption_(key, value);
};
/**
* Handles a change in the value of a checkbox.
* @param {string} key A key used to identify the option.
* @param {Element} checkbox The checkbox element.
* @param {Event} event The event.
* @private
*/
bite.options.Page.prototype.handleCheckbox_ = function(key, checkbox, event) {
var value = 'false';
if (checkbox.checked) {
value = 'true';
}
this.updateOption_(key, value);
};
/**
* Initializes the page by validating DOM Elements, initializing the page's
* events and handlers. It also retrieves the current configuration and
* updates the interface to reflect it.
* @param {function(boolean)=} opt_callback An optional callback that will
* be fired when initialization is complete.
* @export
*/
bite.options.Page.prototype.init = function(opt_callback) {
if (this.isReady() || this.isDestroyed()) {
// Do not allow initialization if the object is already initialized or
// has been destroyed.
return;
}
this.initDOMElements_();
this.initData_();
this.refreshInterface_();
// Start the refresh timer so that the interface will update as things change
// such as last saved time.
this.refreshTimer_.start();
// Once everything is ready, hookup the extension onRequest handler that
// listens to configuration updates from other parts of the application.
// handleOnRequest is a goog.bind function reference.
chrome.extension.onRequest.addListener(this.handleOnRequest_);
this.isReady_ = true;
};
/**
* Sets up handling for the object, the refresh timer, and DOM Elements. It
* also verifies DOM Elements are present and does any other setup related
* functions.
* @private
*/
bite.options.Page.prototype.initDOMElements_ = function() {
var type, handler, listenId;
// Retrieve the data elements from the HTML and setup their event handlers.
for (var key in bite.options.constants.Id) {
var id = bite.options.constants.Id[key];
var elementName = bite.options.Page.ElementName_[id];
var element = goog.dom.getElement(elementName);
if (!element) {
// Continue processing the handler setup if a element is missing.
console.log('ERROR: Failed to find data element (' + elementName + ').');
continue;
}
// Figure out if it's a select or a checkbox input.
if (element.tagName == 'SELECT') {
this.eventHandler_.listen(element, goog.events.EventType.CHANGE,
goog.bind(this.handleSelect_, this, id));
} else if (element.tagName == 'INPUT' && element.type == 'checkbox') {
this.eventHandler_.listen(
element, goog.events.EventType.CLICK,
goog.bind(this.handleCheckbox_, this, id, element));
} else {
console.log('ERROR: Element of unknown input type (' +
elementName + ').');
continue;
}
}
// Setup the Save Button
var saveButtonId = bite.options.Page.ElementName_.SAVE_BUTTON;
var saveButton = goog.dom.getElement(saveButtonId);
if (saveButton) {
type = goog.events.EventType.CLICK;
handler = goog.bind(this.handleSave_, this);
this.eventHandler_.listen(saveButton, type, handler);
this.enableSave_(false);
} else {
// Continue processing the handler setup if a element is missing.
console.log('ERROR: Failed to find save button element (' + saveButtonId +
').');
}
// Validate the presence of the last save time Element.
var saveTimeId = bite.options.Page.ElementName_.SAVE_TIME;
var saveTimeElement = goog.dom.getElement(saveTimeId);
if (!saveTimeElement) {
// Continue processing the handler setup if a element is missing.
console.log('ERROR: Failed to find last saved time element (' +
saveTimeId + ').');
}
// Validate the presence of the user name Element.
var usernameId = bite.options.Page.ElementName_.USERNAME;
var usernameElement = goog.dom.getElement(usernameId);
if (!usernameElement) {
// Continue processing the handler setup if a element is missing.
console.log('ERROR: Failed to find username element (' +
usernameId + ').');
}
// Setup the refresh timer to update the last saved time.
type = goog.Timer.TICK;
handler = goog.bind(this.refreshInterface_, this);
this.eventHandler_.listen(this.refreshTimer_, type, handler);
};
/**
* Retrieves the current configuration and sets the data values to its
* current value.
* @private
*/
bite.options.Page.prototype.initData_ = function() {
var configuration = bite.options.data.getCurrentConfiguration();
// Retrieve the data elements from the HTML and setup their event handlers.
for (var key in bite.options.constants.Id) {
// Retrieve id used to lookup the DOM Element's name.
var id = bite.options.constants.Id[key];
if (!(id in configuration)) {
continue;
}
this.refreshData_(id, configuration[id]);
}
};
/**
* Returns whether or not this object is destroyed.
* @return {boolean} Destroyed or not.
*/
bite.options.Page.prototype.isDestroyed = function() {
return this.isDestroyed_;
};
/**
* Returns whether or not this object is ready for use.
* @return {boolean} Ready or not.
*/
bite.options.Page.prototype.isReady = function() {
return this.isReady_;
};
/**
* Send broadcast message letting others know what part of the configuration
* has changed.
* @private
*/
bite.options.Page.prototype.notifyChange_ = function() {
// Construct message data.
var data = {};
data['action'] = bite.options.constants.Message.UPDATE;
data[bite.options.constants.MessageData.DATA] = this.changed_;
// Broadcast message to the extension. No response is desired.
chrome.extension.sendRequest(data, goog.nullFunction);
};
/**
* Handles messages sent from others related to the configuration data.
* @param {!Object} request The data sent.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} response Optional function to call when the
* request completes; only call when appropriate.
* @private
*/
bite.options.Page.prototype.onRequestHandler_ =
function(request, sender, response) {
// TODO (jasonstredwick): Figure out how to generate a common set of
// message passing values to cross all of BITE and potentially others.
// (possibly in testing/chronos/common?)
var owner = request['owner'];
var action = request['action'];
if (owner != bite.options.constants.OWNER || !action) {
return;
}
switch (action) {
case bite.options.constants.Message.UPDATE:
var data = request[bite.options.constants.MessageData.DATA];
// Look through all the valid options and update the ones that were
// supplied with the data.
for (var key in bite.options.constants.Id) {
var id = bite.options.constants.Id[key];
if (id in data) {
this.refreshData_(id, data[id]);
this.updateOption_(id, data[id]);
}
}
break;
}
};
/**
* Process the option that was selected from the UI in case it does not map
* directly to the configuration value.
* @param {string} id The option id.
* @param {string} value The value that was chosen.
* @return {string} The processed version of the value.
* @private
*/
bite.options.Page.prototype.processOption_ = function(id, value) {
if (!goog.object.containsValue(bite.options.constants.Id, id)) {
console.log('ERROR: Update option failed due to a bad key: ' + id + '.');
return value;
}
id = /** @type {bite.options.constants.Id} */ (id);
switch (id) {
case bite.options.constants.Id.SERVER_CHANNEL:
// Map the option interface id to the configuration value. Assumes that
// the map is managed and all mapped values are present and correct.
return bite.options.Page.MapValues_[value];
}
return value;
};
/**
* Process the option that was selected from the UI in case it does not map
* directly to the configuration value.
* @param {bite.options.constants.Id} id The option id.
* @param {string} value The value that was chosen.
* @return {string} The processed version of the value.
* @private
*/
bite.options.Page.prototype.processOptionReverse_ = function(id, value) {
switch (id) {
case bite.options.constants.Id.SERVER_CHANNEL:
// Map the configuration value to the UI option value. Assumes that
// the mapped values are present and correct.
switch (value) {
case bite.options.constants.ServerChannelOption.DEV:
return 'dev';
case bite.options.constants.ServerChannelOption.RELEASE:
return 'rel';
}
break;
}
return value;
};
/**
* Refresh DOM Element selections with values from the given data.
* @param {string} id The option to update.
* @param {string} value The new value.
* @private
*/
bite.options.Page.prototype.refreshData_ = function(id, value) {
if (!goog.object.containsValue(bite.options.constants.Id, id)) {
console.log('ERROR: Refresh data failed due to a bad key ' + id + '.');
return;
}
id = /** @type {bite.options.constants.Id} */ (id);
var elementName = bite.options.Page.ElementName_[id];
var element = goog.dom.getElement(elementName);
if (!element) {
// Continue processing the handler setup if a element is missing.
// An error is not recorded here because it would have been recorded
// first in this.setup_.
return;
}
if (element.tagName == 'SELECT') {
element.value = this.processOptionReverse_(id, value);
} else if (element.tagName == 'INPUT' && element.type == 'checkbox') {
if (value == 'true') {
element.checked = true;
} else {
element.checked = false;
}
}
};
/**
* Refreshes the non-data portion of the interface; updates the last saved
* information and the username.
* @private
*/
bite.options.Page.prototype.refreshInterface_ = function() {
var saveTimeId = bite.options.Page.ElementName_.SAVE_TIME;
var saveTimeElement = goog.dom.getElement(saveTimeId);
if (saveTimeElement) {
// Shortcut to the Key enum.
var keys = bite.options.private_constants.Key;
// Retrieve the cached last saved data.
var timestamp = bite.options.private_data.get(keys.ADMIN_LAST_SAVE_TIME);
var lastuser = bite.options.private_data.get(keys.ADMIN_LAST_SAVE_USER);
// Prepare the last saved data information string.
var lastSaveInfo = '';
if (timestamp && lastuser) {
// Prepare timestamp by converting it to a delta time relative to now.
var millisec = /** @type {number} */ (timestamp);
// Converts the millisecond time to a formatted time relative to now.
// If the diff is too old it will return an empty string.
var timeDiff = goog.date.relative.format(millisec);
if (!timeDiff) {
// If the date is old enough, format relative to days.
timeDiff = goog.date.relative.formatDay(millisec);
}
lastSaveInfo = 'Updated ' + timeDiff + ' by ' + lastuser;
}
saveTimeElement.innerText = lastSaveInfo;
}
// Begin the refresh of the current user.
var usernameId = bite.options.Page.ElementName_.USERNAME;
var usernameElement = goog.dom.getElement(usernameId);
if (usernameElement) {
// Retrieve the current user asynchronously.
var callback = goog.bind(this.refreshUsername_, this, usernameElement);
var server = bite.options.data.get(
bite.options.constants.Id.SERVER_CHANNEL);
bite.LoginManager.getInstance().getCurrentUser(callback, server);
}
};
/**
* Refreshes the username based on the current value stored by the
* LoginManager.
* @param {!Element} element The username DOM Element.
* @param {Object} data The user related data with the following information:
* {success: boolean, url: string, username: string}.
* @private
*/
bite.options.Page.prototype.refreshUsername_ = function(element, data) {
var success = data['success'];
var username = data['username'];
username = username.replace(/[@]google[.]com$/, '');
// Make sure that we have valid values before updating the configuration.
if (success && username && element.innerText != username) {
element.innerText = username;
// Shortcut to the Key enum.
var keys = bite.options.private_constants.Key;
bite.options.private_data.update(keys.ADMIN_LAST_SAVE_USER, username);
}
};
/**
* Destroys and cleans up the object when it is no longer needed. It will
* unhook all listeners and perform other related cleanup functions.
* Essentially, this object will no longer be functional after a call to this
* function.
*/
bite.options.Page.prototype.stop = function() {
if (this.isDestroyed()) {
return;
}
// Stop refresh timer and destroy it by removing its only reference
// maintained by this object, which created it.
this.refreshTimer_.stop();
this.refreshTimer_.dispose();
// Cleanup all the Listeners.
this.eventHandler_.removeAll();
// Remove chrome extension's request listener.
if (chrome.extension.onRequest.hasListener(this.handleOnRequest_)) {
chrome.extension.onRequest.removeListener(this.handleOnRequest_);
}
// Clean storage objects.
this.changed_ = {};
// Set a flag so the object can't be destroyed multiple times.
this.isDestroyed_ = true;
};
/**
* Updates a single option with the given value.
* @param {string} key A key used to identify the option.
* @param {string} value The new value for the option.
* @private
*/
bite.options.Page.prototype.updateOption_ = function(key, value) {
if (!goog.object.containsValue(bite.options.constants.Id, key)) {
console.log('ERROR: Update option failed due to a bad key ' + key + '.');
return;
}
key = /** @type {bite.options.constants.Id} */ (key);
var cachedValue = bite.options.data.get(key);
// If the user selected the same value as what is cached then we don't want
// to mark this option as changed. Otherwise, remember the newly selected
// value.
if (value == cachedValue) {
delete this.changed_[key];
} else {
this.changed_[key] = value;
}
// After potentially removing/adding a change, the save button needs to be
// updated to reflect this information. The button should be disabled if
// there are no changes.
if (goog.object.isEmpty(this.changed_)) {
this.enableSave_(false);
} else {
this.enableSave_(true);
}
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the code on the Options script file.
*
* @author alexto@google.com (Alexis O. Torres)
*/
goog.require('bite.options.Page');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
var stubs_ = new goog.testing.PropertyReplacer();
var mockControl_ = null;
var configuration = {
'project': bite.options.constants.ProjectOption.NOT_TRASH,
'recording': bite.options.constants.ThreeWayOption.ALL,
'screenshot': bite.options.constants.ThreeWayOption.ALL,
'state': bite.options.constants.StateOption.ALL,
'uiBinding': bite.options.constants.ThreeWayOption.ALL,
'serverChannel': bite.options.constants.ServerChannelOption.DEVELOPMENT,
'autoRecord': 'false',
'featuresBugs': 'false',
'featuresRpf': 'false',
'featuresTests': 'false'
};
function setUp() {
initChrome();
mockOnRequest = {addListener: goog.nullFunction,
hasListener: function() {return false}};
stubs_.set(chrome.extension, 'onRequest', mockOnRequest);
}
function tearDown() {
if (mockControl_) {
mockControl_.$tearDown();
mockControl_ = null;
}
stubs_.reset();
}
function testSaveOptions() {
mockControl_ = new goog.testing.MockControl();
optionsPage = new bite.options.Page();
var mockGet = mockControl_.createFunctionMock('get');
stubs_.set(bite.options.data, 'get', mockGet);
var mockConfiguration = mockControl_.createFunctionMock(
'getCurrentConfiguration');
stubs_.set(bite.options.data, 'getCurrentConfiguration', mockConfiguration);
var mockPrivateGet = mockControl_.createFunctionMock('get');
stubs_.set(bite.options.private_data, 'get', mockPrivateGet);
var mockUpdateConfiguration = mockControl_.createFunctionMock(
'updateConfiguration');
stubs_.set(bite.options.data, 'updateConfiguration', mockUpdateConfiguration);
mockConfiguration().$returns(configuration);
// The LoginManager calls bite.options.data.get for the server channel.
mockGet('serverChannel').$anyTimes();
mockGet('featuresBugs').$times(1);
mockGet('serverChannel').$anyTimes();
mockPrivateGet(goog.testing.mockmatchers.isString).$anyTimes().$returns(
'false');
var expectedChanges = {'featuresBugs': 'true'};
mockUpdateConfiguration(expectedChanges, undefined).$times(1);
mockControl_.$replayAll();
optionsPage.init();
assertTrue(optionsPage.isReady());
var bugsCheckbox = goog.dom.getElement('features-bugs');
bugsCheckbox.checked = true;
goog.testing.events.fireClickEvent(bugsCheckbox);
var saveButton = goog.dom.getElement('save-button');
goog.testing.events.fireClickEvent(saveButton);
optionsPage.stop();
assertTrue(optionsPage.isDestroyed());
mockControl_.$verifyAll();
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines BITE options/settings constants including ids,
* messaging, and option settings.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.options.constants');
/**
* Options key values.
* @enum {string}
*/
bite.options.constants.Id = {
BUG_PROJECT: 'project',
BUG_RECORDING: 'recording',
BUG_SCREENSHOT: 'screenshot',
BUG_STATE: 'state',
BUG_UI_BINDING: 'uiBinding',
SERVER_CHANNEL: 'serverChannel',
AUTO_RECORD: 'autoRecord',
FEATURES_BUGS: 'featuresBugs',
FEATURES_RPF: 'featuresRpf',
FEATURES_TESTS: 'featuresTests',
FEATURES_CLOSE: 'featuresClose',
FEATURES_REPORT: 'featuresReport'
};
/**
* The owner string to specifiy that messages come from the configuration data.
* @type {string}
*/
bite.options.constants.OWNER = 'bite.options';
/**
* Messages to notify configuration data users.
* @enum {string}
*/
bite.options.constants.Message = {
UPDATE: 'update'
};
/**
* Possible data sent with the various messages.
* @enum {string}
*/
bite.options.constants.MessageData = {
DATA: 'data' // The data will be an Object.<bite.option.constants.Id, string>
};
/**
* Bug project option pulldown values.
* @enum {string}
*/
bite.options.constants.ProjectOption = {
ALL: 'all',
GEO: 'geo',
WEBSTORE: 'chromewebstore',
NOT_TRASH: 'nottrash',
TRASH: 'trash'
};
/**
* Bug state option pulldown values.
* @enum {string}
*/
bite.options.constants.StateOption = {
ACTIVE: 'active',
ALL: 'all',
CLOSED: 'closed',
RESOLVED: 'resolved'
};
/**
* Three-way option pulldown values.
* @enum {string}
*/
bite.options.constants.ThreeWayOption = {
ALL: 'all',
NO: 'no',
YES: 'yes'
};
/**
* BITE's server list.
* @enum {string}
*/
bite.options.constants.ServerChannelOption = {
DEV: 'https://bite-playground-dev.appspot.com',
RELEASE: 'https://bite-playground.appspot.com'
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This function provides functions for manipulating private BITE
* configuration data.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.options.private_data');
goog.require('bite.options.private_constants');
goog.require('goog.date.DateTime');
goog.require('goog.object');
/**
* Returns the current setting for the specified option.
* @param {string} key The option's cache key.
* @return {?string} The current value.
*/
bite.options.private_data.get = function(key) {
if (!goog.object.contains(bite.options.private_constants.Key, key)) {
console.log('ERROR: Trying to get a configuration option with invalid ' +
'key ' + key + '.');
return null;
}
// Return the cached value or the default if there is no cache value.
return /** @type {string} */ (goog.global.localStorage.getItem(key)) || null;
};
/**
* Updates the given option with the given value. This is a private function
* and expects the user to validate their own inputs.
* @param {string} key The option's cache key.
* @param {string} value The option's new value if valid.
*/
bite.options.private_data.update = function(key, value) {
if (!goog.object.contains(bite.options.private_constants.Key, key)) {
console.log('ERROR: Trying to get a configuration option with invalid ' +
'key ' + key + '.');
return;
}
// Cache the specified option's new value.
goog.global.localStorage.setItem(key, value);
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines BITE options/settings constants that are intended to
* be private to the options package.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.options.private_constants');
goog.require('bite.options.constants');
/**
* Options key values used for caching values in the localStorage.
*
* Some of the keys are values from bite.options.constants.Id instead of
* directly accessing the enum due to the fact that Closure can not handle
* keys in an enum being set from values in a different enum. They also can't
* handle non-capitalized, quoted strings as keys for enums. Thus this type
* is Object out of necessity.
* @type {!Object}
*/
bite.options.private_constants.Key = {
ADMIN_LAST_SAVE_TIME: 'bite.options.admin.lastSaveTime',
ADMIN_LAST_SAVE_USER: 'bite.options.admin.lastSaveUser',
'project': 'bite.options.bug.project',
'recording': 'bite.options.bug.recording',
'screenshot': 'bite.options.bug.screenshot',
'state': 'bite.options.bug.state',
'uiBinding': 'bite.options.bug.uiBinding',
'serverChannel': 'bite.options.server.channel',
'autoRecord': 'bite.options.rpf.autoRecord',
'featuresBugs': 'bite.options.popup.Bugs',
'featuresRpf': 'bite.options.popup.Rpf',
'featuresTests': 'bite.options.popup.Tests',
'featuresClose': 'bite.options.popup.Close',
'featuresReport': 'bite.options.popup.Report'
};
/**
* Defines the default username constant when there is no username given.
* @type {string}
*/
bite.options.private_constants.DEFAULT_USERNAME = 'unknown';
/**
* Default values for the Option settings.
*
* Some of the keys are values from bite.options.constants.Id instead of
* directly accessing the enum due to the fact that Closure can not handle
* keys in an enum being set from values in a different enum. They also can't
* handle non-capitalized, quoted strings as keys for enums. Thus this type
* is Object out of necessity.
* @type {!Object}
*/
bite.options.private_constants.Default = {
'project': bite.options.constants.ProjectOption.ALL,
'recording': bite.options.constants.ThreeWayOption.ALL,
'screenshot': bite.options.constants.ThreeWayOption.ALL,
'state': bite.options.constants.StateOption.ALL,
'uiBinding': bite.options.constants.ThreeWayOption.ALL,
'serverChannel': bite.options.constants.ServerChannelOption.DEV,
'autoRecord': 'false',
'featuresBugs': 'true',
'featuresRpf': 'true',
'featuresTests': 'false',
'featuresClose': 'false',
'featuresReport': 'true'
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Helper for filing bugs specific to maps.google.com.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.provide('bite.client.MapsHelper');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.string');
/**
* The maps domain.
* @const
* @type {string}
* @private
*/
bite.client.MapsHelper.MAPS_DOMAIN_ = 'maps.google.com';
/**
* Maps related data.
* @enum {string}
*/
bite.client.MapsHelper.MapsData = {
DEBUG_URL_ID: 'ledebugurl',
LINK_ID: 'link'
};
/**
* Determines whether an URL is a Google Maps URL.
* @param {string} url URL to test.
* @return {boolean} Whether the given URL is a Google Maps URL.
*/
bite.client.MapsHelper.isMapsUrl = function(url) {
var uri = new goog.Uri(url);
return goog.string.caseInsensitiveCompare(
uri.getDomain(), bite.client.MapsHelper.MAPS_DOMAIN_) == 0;
};
/**
* Updates the URL of a maps page, and does not edit other URLs.
* @param {string} url The page's url.
* @param {function(string)} setUrlCallback A callback to set the new url.
*/
bite.client.MapsHelper.updateUrl = function(url, setUrlCallback) {
if (bite.client.MapsHelper.isMapsUrl(url)) {
var link = goog.dom.getElement(bite.client.MapsHelper.MapsData.LINK_ID);
// We'd like to use the debug url instead of the normal URL if it exists.
// We have to click on the link element to show the dialog which
// potentially contains the debug url.
// Calls the wrapper function for the actions.
BiteRpfAction.click(link);
// Gets the debug URL only when the field is shown. Will retry if
// not immediaetly available.
bite.client.MapsHelper.updateDebugUrl_(0, setUrlCallback);
}
};
/**
* Updates the bugs's url with the debug url, retries up to 5 times.
* @param {number} timesAttempted The number of retries that have been attempted.
* @param {function(string)} setUrlCallback A callback to set the new url.
* @private
*/
bite.client.MapsHelper.updateDebugUrl_ =
function(timesAttempted, setUrlCallback) {
var debugInput = goog.dom.getElement(
bite.client.MapsHelper.MapsData.DEBUG_URL_ID);
if (debugInput && debugInput.value &&
debugInput.parentNode.style.display != 'none') {
setUrlCallback(debugInput.value);
} else {
// Retry up to 5 times.
if (timesAttempted < 5) {
goog.Timer.callOnce(
goog.partial(
bite.client.MapsHelper.updateDebugUrl_,
timesAttempted + 1,
setUrlCallback),
200);
} else {
// TODO(bustamante): Capture failures like this and report them to the
// BITE server or Google Analytics.
}
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define the controller for bite.project.Explore
* window. The object defines the functionality specifically for this
* controller and does not affect the outside world. However, it does define
* a set of signals that can be used by external sources to perform actions
* when the controller performs certain tasks.
*
* The Explore window is inteneded to have only a single instance.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.Explore');
goog.require('bite.common.mvc.helper');
goog.require('bite.project.soy.Explore');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
/**
* Constructs an instance of a Explore controller. The constructor
* creates the object in a default state that has not been mapped to a view.
* @constructor
* @export
*/
bite.project.Explore = function() {
/**
* Drill down button for browse results.
* @type {Element}
* @private
*/
this.drillBrowse_ = null;
/**
* Drill down button for search results.
* @type {Element}
* @private
*/
this.drillSearch_ = null;
/**
* Drill down button for subscription results.
* @type {Element}
* @private
*/
this.drillSubscription_ = null;
/**
* Whether or not the window's model is initialized.
* @type {boolean}
* @private
*/
this.isModelInitialized_ = false;
/**
* Window element managed by this controller. Defaults to null meaning the
* controller is not attached to a model.
* @type {Element}
* @private
*/
this.window_ = null;
};
goog.addSingletonGetter(bite.project.Explore);
/**
* The window's id.
* @type {string}
* @private
*/
bite.project.Explore.CONSOLE_ID_ = 'project-explore';
/**
* Buttons.
* @enum {string}
* @private
*/
bite.project.Explore.Button_ = {
BROWSE: 'project-general-browse-results',
SEARCH: 'project-general-search-drilldown',
SUBSCRIPTION: 'project-general-subscription-drilldown'
};
/**
* Given an object, fill in values respective to this view.
* @param {Object} inout_data An object to be filled with values.
* @export
*/
bite.project.Explore.prototype.getData = function(inout_data) {
};
/**
* Returns the div element for the explore view.
* @return {Element} It will return the element or null if not created.
* @export
*/
bite.project.Explore.prototype.getView = function() {
return this.window_;
};
/**
* Initialize the Explore Window by creating the model and hooking
* functions to the model. If a baseUrl is given and the view is not yet
* initialized then this function will try to initialize it. Nothing happens
* if the window is already initialized.
* @param {string=} opt_baseUrl The baseUrl required for relative references.
* @return {boolean} Whether or not the model is initialized. It will also
* return true if the model is already initialized.
* @export
*/
bite.project.Explore.prototype.init = function(opt_baseUrl) {
if (this.isModelInitialized_) {
return true;
}
var helper = bite.common.mvc.helper;
this.window_ = helper.renderModel(bite.project.soy.Explore.getModel,
{'baseUrl': opt_baseUrl});
if (this.window_ && this.setupButtons_(this.window_)) {
this.isModelInitialized_ = true;
} else {
this.undoSetup_();
}
return this.isModelInitialized_;
};
/**
* Determines if the window is constructed or not.
* @return {boolean} Whether or not the view is initialized.
* @export
*/
bite.project.Explore.prototype.isInitialized = function() {
return this.isModelInitialized_;
};
/**
* Retrieve and store button elements.
* @param {!Element} srcElement The element to search within.
* @return {boolean} Successfully setup buttons.
* @private
*/
bite.project.Explore.prototype.setupButtons_ = function(srcElement) {
var helper = bite.common.mvc.helper;
var button = bite.project.Explore.Button_;
this.drillBrowse_ = helper.getElement(button.BROWSE, srcElement);
this.drillSearch_ = helper.getElement(button.SEARCH, srcElement);
this.drillSubscription_ = helper.getElement(button.SUBSCRIPTION, srcElement);
return true;
};
/**
* Takes an object that contains data for the various inputs and sets the
* input elements to the appropriate values.
* TODO (jasonstredwick): Cleanup function by either moving code to soy or
* rethink what needs to happen here.
* @param {Object} data The data used to fill out the form.
* @return {boolean} Whether or not the window was updated.
* @export
*/
bite.project.Explore.prototype.update = function(data) {
if (!this.isInitialized()) {
return false;
}
var i = 0;
var len = 0;
var element = null;
var srcElement = /** @type {!Element} */ (this.window_);
var helper = bite.common.mvc.helper;
var elementName = '';
if ('subscriptions' in data) {
// Clear element
elementName = 'project-general-subscriptions';
var subscriptionsElement = helper.getElement(elementName, srcElement);
subscriptionsElement.innerHTML = '';
// Add in up to the first five values.
var subscriptions = data['subscriptions'];
for (i = 0, len = subscriptions.length; i < len && i < 5; ++i) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = subscriptions[i];
goog.dom.appendChild(subscriptionsElement, element);
}
if (subscriptions.length >= 5) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = 'See more...';
element.className = 'see-more';
goog.dom.appendChild(subscriptionsElement, element);
}
}
if ('search' in data) {
// Reset element
elementName = 'project-general-search-results';
var searchElement = helper.getElement(elementName, srcElement);
var searchBar = searchElement.childNodes[0];
goog.dom.removeChildren(searchElement);
goog.dom.appendChild(searchElement, searchBar);
var results = data['search'];
// Add in the number of results.
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = 'Found ' + results.length + 'results.';
element.className = 'results';
goog.dom.appendChild(searchElement, element);
// Add in up to the first five values.
for (i = 0, len = results.length; i < len && i < 5; ++i) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = results[i];
goog.dom.appendChild(searchElement, element);
}
if (results.length >= 5) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = 'See more...';
element.className = 'see-more';
goog.dom.appendChild(searchElement, element);
}
}
if ('browse' in data) {
// Reset element
elementName = 'project-general-search-results';
var browseElement = helper.getElement(elementName, srcElement);
browseElement.innerHTML = '';
var browseResults = data['browse'];
// Add in up to the first five values.
for (i = 0, len = browseResults.length; i < len && i < 5; ++i) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = browseResults[i];
goog.dom.appendChild(browseElement, element);
}
if (browseResults.length >= 5) {
element = goog.dom.createElement(goog.dom.TagName.DIV);
element.innerHTML = 'See more...';
element.className = 'see-more';
goog.dom.appendChild(browseElement, element);
}
}
return true;
};
/**
* Reset the model portion of the controller back to an uninitialized state.
* @private
*/
bite.project.Explore.prototype.undoSetup_ = function() {
// Make sure and remove the DOM Element from the document upon failure.
if (this.window_) {
bite.common.mvc.helper.removeElementById(bite.project.Explore.CONSOLE_ID_);
}
this.drillBrowse_ = null;
this.drillSearch_ = null;
this.drillSubscription_ = null;
this.window_ = null;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define the controller for bite.project.General
* window. The object defines the functionality specifically for this
* controller and does not affect the outside world. However, it does define
* a set of signals that can be used by external sources to perform actions
* when the controller performs certain tasks.
*
* The General window is inteneded to have only a single instance.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.General');
goog.require('bite.common.mvc.helper');
goog.require('bite.project.soy.General');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
/**
* Constructs an instance of a General controller. The constructor
* creates the object in a default state that has not been mapped to a view.
* @constructor
* @export
*/
bite.project.General = function() {
/**
* The description input element.
* @type {Element}
* @private
*/
this.description_ = null;
/**
* Whether or not the window's model is initialized.
* @type {boolean}
* @private
*/
this.isModelInitialized_ = false;
/**
* The name input element.
* @type {Element}
* @private
*/
this.name_ = null;
/**
* The provider input element.
* @type {Element}
* @private
*/
this.provider_ = null;
/**
* The provider info input element.
* @type {Element}
* @private
*/
this.providerInfo_ = null;
/**
* The provider input element.
* @type {Element}
* @private
*/
this.tcm_ = null;
/**
* The provider info input element.
* @type {Element}
* @private
*/
this.tcmInfo_ = null;
/**
* Window element managed by this controller. Defaults to null meaning the
* controller is not attached to a model.
* @type {Element}
* @private
*/
this.window_ = null;
};
goog.addSingletonGetter(bite.project.General);
/**
* The window's id.
* @type {string}
* @private
*/
bite.project.General.CONSOLE_ID_ = 'project-general';
/**
* The string identifiers for this view's data.
* @enum {string}
* @private
*/
bite.project.General.Data_ = {
DESCRIPTION: 'description',
NAME: 'name',
PROVIDER: 'provider',
PROVIDER_INFO: 'provider_info',
TCM: 'tcm',
TCM_INFO: 'tcm_info'
};
/**
* Given an object, fill in values respective to this view.
* @param {Object} inout_data An object to be filled with values.
* @export
*/
bite.project.General.prototype.getData = function(inout_data) {
if (!this.isInitialized()) {
return;
}
inout_data[bite.project.General.Data_.DESCRIPTION] = this.description_.value;
inout_data[bite.project.General.Data_.NAME] = this.name_.value;
inout_data[bite.project.General.Data_.PROVIDER] = this.provider_.value;
inout_data[bite.project.General.Data_.PROVIDER_INFO] =
this.providerInfo_.value;
inout_data[bite.project.General.Data_.TCM] = this.tcm_.value;
inout_data[bite.project.General.Data_.TCM_INFO] = this.tcmInfo_.value;
};
/**
* Returns the div element representing this details view.
* @return {Element} It will return the element or null if not created.
* @export
*/
bite.project.General.prototype.getView = function() {
return this.window_;
};
/**
* Initialize the General Window by creating the model and hooking
* functions to the model. If a baseUrl is given and the view is not yet
* initialized then this function will try to initialize it. Nothing happens
* if the window is already initialized.
* @param {string=} opt_baseUrl The baseUrl required for relative references.
* @return {boolean} Whether or not the model is initialized. It will also
* return true if the model is already initialized.
* @export
*/
bite.project.General.prototype.init = function(opt_baseUrl) {
if (this.isModelInitialized_) {
return true;
}
var helper = bite.common.mvc.helper;
this.window_ = helper.initModel(bite.project.soy.General.getModel,
{'baseUrl': opt_baseUrl});
if (this.window_ && this.setupInputs_(this.window_)) {
this.isModelInitialized_ = true;
} else {
this.undoSetup_();
}
return this.isModelInitialized_;
};
/**
* Determines if the window is constructed or not.
* @return {boolean} Whether or not the view is initialized.
* @export
*/
bite.project.General.prototype.isInitialized = function() {
return this.isModelInitialized_;
};
/**
* Retrieve elements from the model to be used later.
* @param {!Element} srcElement The element from which to find the ones
* desired.
* @return {boolean} Whether or not they were all found.
* @private
*/
bite.project.General.prototype.setupInputs_ = function(srcElement) {
var helper = bite.common.mvc.helper;
this.description_ = helper.getElement('project-description', srcElement);
this.name_ = helper.getElement('project-name', srcElement);
this.provider_ = helper.getElement('project-bug-provider',
srcElement);
this.providerInfo_ = helper.getElement('project-bug-provider-info',
srcElement);
this.tcm_ = helper.getElement('project-tcm', srcElement);
this.tcmInfo_ = helper.getElement('project-tcm-info', srcElement);
return true;
};
/**
* Takes an object that contains data for the various inputs and sets the
* input elements to the appropriate values.
* @param {Object} data The data used to fill out the form.
* @return {boolean} Whether or not the window was updated.
* @export
*/
bite.project.General.prototype.update = function(data) {
if (!this.isInitialized()) {
return false;
}
if (bite.project.General.Data_.DESCRIPTION in data) {
this.description_.value = data[bite.project.General.Data_.DESCRIPTION];
}
if (bite.project.General.Data_.NAME in data) {
this.name_.value = data[bite.project.General.Data_.NAME];
}
if (bite.project.General.Data_.PROVIDER in data) {
this.provider_.value = data[bite.project.General.Data_.PROVIDER];
}
if (bite.project.General.Data_.PROVIDER_INFO in data) {
this.providerInfo_.value = data[bite.project.General.Data_.PROVIDER_INFO];
}
if (bite.project.General.Data_.TCM in data) {
this.tcm_.value = data[bite.project.General.Data_.TCM];
}
if (bite.project.General.Data_.TCM_INFO in data) {
this.tcmInfo_.value = data[bite.project.General.Data_.TCM_INFO];
}
return true;
};
/**
* Reset the model portion of the controller back to an uninitialized state.
* @private
*/
bite.project.General.prototype.undoSetup_ = function() {
// Make sure and remove the DOM Element from the document upon failure.
if (this.window_) {
bite.common.mvc.helper.removeElementById(bite.project.General.CONSOLE_ID_);
}
this.description_ = null;
this.name_ = null;
this.provider_ = null;
this.providerInfo_ = null;
this.tcm_ = null;
this.tcmInfo_ = null;
this.window_ = null;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define the controller for bite.project.Settings
* window. The object defines the functionality specifically for this
* controller and does not affect the outside world. However, it does define
* a set of signals that can be used by external sources to perform actions
* when the controller performs certain tasks.
*
* The Settings window is inteneded to have only a single instance.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.Settings');
goog.require('bite.common.mvc.helper');
goog.require('bite.project.soy.Settings');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
/**
* Constructs an instance of a Settings controller. The constructor
* creates the object in a default state that has not been mapped to a view.
* @constructor
* @export
*/
bite.project.Settings = function() {
/**
* Whether or not the window's model is initialized.
* @type {boolean}
* @private
*/
this.isModelInitialized_ = false;
/**
* Holds the line length element.
* @type {Element}
* @private
*/
this.lineLength_ = null;
/**
* Holds the run time element.
* @type {Element}
* @private
*/
this.runtime_ = null;
/**
* Holds the screenshot checkbox element.
* @type {Element}
* @private
*/
this.screenshot_ = null;
/**
* Holds the timeout limit element.
* @type {Element}
* @private
*/
this.timeout_ = null;
/**
* Holds the worker mode token element.
* @type {Element}
* @private
*/
this.token_ = null;
/**
* Holds the start url element.
* @type {Element}
* @private
*/
this.url_ = null;
/**
* Window element managed by this controller. Defaults to null meaning the
* controller is not attached to a model.
* @type {Element}
* @private
*/
this.window_ = null;
};
goog.addSingletonGetter(bite.project.Settings);
/**
* The window's id.
* @type {string}
* @private
*/
bite.project.Settings.CONSOLE_ID_ = 'project-settings';
/**
* The string identifiers for this view's data.
* @enum {string}
* @private
*/
bite.project.Settings.Data_ = {
LINE_LENGTH: 'test_case_line_length',
RUNTIME: 'max_runs_per_test',
SCREENSHOT: 'save_screen_shot',
TIMEOUT: 'line_timeout_limit',
TOKEN: 'worker_mode_token',
URL: 'start_url_replacement'
};
/**
* Given an object, fill in values respective to this view.
* @param {Object} inout_data An object to be filled with values.
* @export
*/
bite.project.Settings.prototype.getData = function(inout_data) {
if (!this.isInitialized()) {
return;
}
inout_data[bite.project.Settings.Data_.LINE_LENGTH] = this.lineLength_.value;
inout_data[bite.project.Settings.Data_.RUNTIME] = this.runtime_.value;
inout_data[bite.project.Settings.Data_.SCREENSHOT] =
(this.screenshot_.value) ? 'true' : 'false';
inout_data[bite.project.Settings.Data_.TIMEOUT] = this.timeout_.value;
inout_data[bite.project.Settings.Data_.TOKEN] = this.token_.value;
inout_data[bite.project.Settings.Data_.URL] = this.url_.value;
};
/**
* Returns the div element of this details view.
* @return {Element} It will return the element or null if not created.
* @export
*/
bite.project.Settings.prototype.getView = function() {
return this.window_;
};
/**
* Initialize the Settings Window by creating the model and hooking
* functions to the model. If a baseUrl is given and the view is not yet
* initialized then this function will try to initialize it. Nothing happens
* if the window is already initialized.
* @param {string=} opt_baseUrl The baseUrl required for relative references.
* @return {boolean} Whether or not the model is initialized. It will also
* return true if the model is already initialized.
* @export
*/
bite.project.Settings.prototype.init = function(opt_baseUrl) {
if (this.isModelInitialized_) {
return true;
}
var helper = bite.common.mvc.helper;
this.window_ = helper.initModel(bite.project.soy.Settings.getModel,
{'baseUrl': opt_baseUrl});
if (this.window_ && this.setupInputs_(this.window_)) {
this.isModelInitialized_ = true;
} else {
this.undoSetup_();
}
return this.isModelInitialized_;
};
/**
* Determines if the window is constructed or not.
* @return {boolean} Whether or not the view is initialized.
* @export
*/
bite.project.Settings.prototype.isInitialized = function() {
return this.isModelInitialized_;
};
/**
* Retrieve and store references to the input elements.
* @param {!Element} srcElement The element from which to find the needed
* elements.
* @return {boolean} Whether or not all elements were found.
* @private
*/
bite.project.Settings.prototype.setupInputs_ = function(srcElement) {
var helper = bite.common.mvc.helper;
this.lineLength_ = helper.getElement('project-line-length', srcElement);
this.runtime_ = helper.getElement('project-max-time', srcElement);
this.screenshot_ = helper.getElement('project-screenshot', srcElement);
this.timeout_ = helper.getElement('project-timeout', srcElement);
this.token_ = helper.getElement('project-worker-mode-token', srcElement);
this.url_ = helper.getElement('project-start-url', srcElement);
return true;
};
/**
* Takes an object that contains data for the various inputs and sets the
* input elements to the appropriate values.
* @param {Object} data The data used to fill out the form.
* @return {boolean} Whether or not the window was updated.
* @export
*/
bite.project.Settings.prototype.update = function(data) {
if (!this.isInitialized()) {
return false;
}
if (bite.project.Settings.Data_.LINE_LENGTH in data) {
this.lineLength_.value = data[bite.project.Settings.Data_.LINE_LENGTH];
}
if (bite.project.Settings.Data_.RUNTIME in data) {
this.runtime_.value = data[bite.project.Settings.Data_.RUNTIME];
}
if (bite.project.Settings.Data_.SCREENSHOT in data) {
this.screenshot_.checked =
(data[bite.project.Settings.Data_.SCREENSHOT]) ? 'true' : 'false';
}
if (bite.project.Settings.Data_.TIMEOUT in data) {
this.timeout_.value = data[bite.project.Settings.Data_.TIMEOUT];
}
if (bite.project.Settings.Data_.TOKEN in data) {
this.token_.value = data[bite.project.Settings.Data_.TOKEN];
}
if (bite.project.Settings.Data_.URL in data) {
this.url_.value = data[bite.project.Settings.Data_.URL];
}
return true;
};
/**
* Reset the model portion of the controller back to an uninitialized state.
* @private
*/
bite.project.Settings.prototype.undoSetup_ = function() {
// Make sure and remove the DOM Element from the document upon failure.
if (this.window_) {
var helper = bite.common.mvc.helper;
helper.removeElementById(bite.project.Settings.CONSOLE_ID_);
}
this.lineLength_ = null;
this.runtime_ = null;
this.screenshot_ = null;
this.timeout_ = null;
this.token_ = null;
this.url_ = null;
this.window_ = null;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unifies the bite.project subsystem within the context of
* content scripts. The constructor as a the initializer for the subsystem
* causes the rest of the system to initialize.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.Content');
goog.require('bite.project.Explore');
goog.require('bite.project.General');
goog.require('bite.project.Member');
goog.require('bite.project.Settings');
/**
* Constructs an object that manages the project UX.
* @constructor
* @export
*/
bite.project.Content = function() {
/**
* Whether or not consoles are initialized.
* @type {boolean}
* @private
*/
this.areConsolesInitialized_ = false;
/**
* A string representing the base url for relative references.
* @type {string}
* @private
*/
this.baseUrl_ = '';
/**
* The controller for the detail's page general view.
* @type {bite.project.General}
* @private
*/
this.detailsGeneralView_ = null;
/**
* The controller for the detail's page member view.
* @type {bite.project.Member}
* @private
*/
this.detailsMemberView_ = null;
/**
* The controller for the detail's page settings view.
* @type {bite.project.Settings}
* @private
*/
this.detailsSettingsView_ = null;
/**
* The controller for the explore page.
* @type {bite.project.Explore}
* @private
*/
this.exploreView_ = null;
/**
* Whether or not the common view is initialized.
* @type {boolean}
* @private
*/
this.isViewInitialized_ = false;
};
goog.addSingletonGetter(bite.project.Content);
/**
* A list of actions defined for projects.
* @enum {string}
* @export
*/
bite.project.Content.action = {
GET_VIEW: 'get-view'
};
/**
* Names used to identify the various project views in terms of visual
* elements.
* @enum {string}
* @export
*/
bite.project.Content.viewId = {
EXPLORE: 'explore',
GENERAL: 'general',
MEMBER: 'member',
SETTINGS: 'settings'
};
/**
* Names used to identify the various project views in terms of data retrieval.
* @enum {string}
* @export
*/
bite.project.Content.dataId = {
DETAILS: 'details',
EXPLORE: 'explore'
};
/**
* Returns the div element containing a project view.
* @param {bite.project.Content.viewId} id Which view.
* @return {Element} The div element for the requested view or null if not
* created.
* @export
*/
bite.project.Content.prototype.getView = function(id) {
switch (id) {
case bite.project.Content.viewId.EXPLORE:
return this.exploreView_.getView();
case bite.project.Content.viewId.GENERAL:
return this.detailsGeneralView_.getView();
case bite.project.Content.viewId.MEMBER:
return this.detailsMemberView_.getView();
case bite.project.Content.viewId.SETTINGS:
return this.detailsSettingsView_.getView();
default:
console.log('WARNING (bite.project.Content.getView): Bad id - ' + id);
}
return null;
};
/**
* Returns the div element containing a project view.
* @param {bite.project.Content.dataId} id Which view.
* @param {Object} inout_data An object to be filled.
* @export
*/
bite.project.Content.prototype.getData = function(id, inout_data) {
switch (id) {
case bite.project.Content.dataId.EXPLORE:
this.exploreView_.getData(inout_data);
case bite.project.Content.dataId.DETAILS:
this.detailsGeneralView_.getData(inout_data);
this.detailsMemberView_.getData(inout_data);
this.detailsSettingsView_.getData(inout_data);
default:
console.log('WARNING (bite.project.Content.getData): Bad id - ' + id);
}
return;
};
/**
* Initializes the Project UX for content scripts.
* @param {string=} baseUrl The base url to use for relative references.
* @export
*/
bite.project.Content.prototype.init = function(baseUrl) {
this.baseUrl_ = baseUrl || '';
// Initialize controllers
this.exploreView_ = bite.project.Explore.getInstance();
this.exploreView_.init(this.baseUrl_);
this.detailsGeneralView_ = bite.project.General.getInstance();
this.detailsGeneralView_.init(this.baseUrl_);
this.detailsMemberView_ = bite.project.Member.getInstance();
this.detailsMemberView_.init(this.baseUrl_);
this.detailsSettingsView_ = bite.project.Settings.getInstance();
this.detailsSettingsView_.init(this.baseUrl_);
};
/**
* Create the content instance to initialize the project subsystem in the
* context of a content script.
*/
bite.project.Content.getInstance();
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define the controller for bite.project.Member
* window. The object defines the functionality specifically for this
* controller and does not affect the outside world. However, it does define
* a set of signals that can be used by external sources to perform actions
* when the controller performs certain tasks.
*
* The Member window is inteneded to have only a single instance.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.Member');
goog.require('bite.common.mvc.helper');
goog.require('bite.project.soy.Member');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.string');
/**
* Constructs an instance of a Member controller. The constructor
* creates the object in a default state that has not been mapped to a view.
* @constructor
* @export
*/
bite.project.Member = function() {
/**
* The cancel button element.
* @type {Element}
* @private
*/
this.buttonCancel_ = null;
/**
* The invite button element.
* @type {Element}
* @private
*/
this.buttonInvite_ = null;
/**
* The remove button element.
* @type {Element}
* @private
*/
this.buttonRemove_ = null;
/**
* The invite textarea.
* @type {Element}
* @private
*/
this.invite_ = null;
/**
* Whether or not the window's model is initialized.
* @type {boolean}
* @private
*/
this.isModelInitialized_ = false;
/**
* The Element that contains a list of group members.
* @type {Element}
* @private
*/
this.members_ = null;
/**
* Window element managed by this controller. Defaults to null meaning the
* controller is not attached to a model.
* @type {Element}
* @private
*/
this.window_ = null;
};
goog.addSingletonGetter(bite.project.Member);
/**
* The window's id.
* @type {string}
* @private
*/
bite.project.Member.CONSOLE_ID_ = 'project-member';
/**
* The string identifiers for this view's data.
* TODO (jasonstredwick): Need to incorporate the rest of the elements into
* this and other enums.
* @enum {string}
* @private
*/
bite.project.Member.Data_ = {
MEMBERS: 'emails'
};
/**
* Given an object, fill in values respective to this view.
* @param {Object} inout_data An object to be filled with values.
* @export
*/
bite.project.Member.prototype.getData = function(inout_data) {
if (!this.isInitialized()) {
return;
}
var members = [];
for (var i = 0, len = this.members_.rows.length; i < len; ++i) {
members.push(this.members_.rows[i].cells[0]);
}
inout_data[bite.project.Member.Data_.MEMBERS] = members;
};
/**
* Returns the div element for this details view.
* @return {Element} It will return the element or null if not created.
* @export
*/
bite.project.Member.prototype.getView = function() {
return this.window_;
};
/**
* Initialize the Member Window by creating the model and hooking
* functions to the model. If a baseUrl is given and the view is not yet
* initialized then this function will try to initialize it. Nothing happens
* if the window is already initialized.
* @param {string=} opt_baseUrl The baseUrl required for relative references.
* @return {boolean} Whether or not the model is initialized. It will also
* return true if the model is already initialized.
* @export
*/
bite.project.Member.prototype.init = function(opt_baseUrl) {
if (this.isModelInitialized_) {
return true;
}
var helper = bite.common.mvc.helper;
this.window_ = helper.initModel(bite.project.soy.Member.getModel,
{'baseUrl': opt_baseUrl});
if (this.window_ && this.setupInputs_(this.window_)) {
this.isModelInitialized_ = true;
} else {
this.undoSetup_();
}
return this.isModelInitialized_;
};
/**
* Determines if the window is constructed or not.
* @return {boolean} Whether or not the view is initialized.
* @export
*/
bite.project.Member.prototype.isInitialized = function() {
return this.isModelInitialized_;
};
/**
* Retrieve and store references to the input elements.
* @param {!Element} srcElement The element from which to find the needed
* elements.
* @return {boolean} Whether or not all elements were found.
* @private
*/
bite.project.Member.prototype.setupInputs_ = function(srcElement) {
var helper = bite.common.mvc.helper;
this.buttonCancel_ = helper.getElement('project-invite-cancel', srcElement);
this.buttonInvite_ = helper.getElement('project-invite', srcElement);
this.buttonRemove_ = helper.getElement('project-member-remove', srcElement);
this.invite_ = helper.getElement('project-invite-users', srcElement);
this.members_ = helper.getElement('project-members', srcElement);
return true;
};
/**
* Takes an object that contains data for the various inputs and sets the
* input elements to the appropriate values.
* @param {Object} data The data used to fill out the form.
* @return {boolean} Whether or not the window was updated.
* @export
*/
bite.project.Member.prototype.update = function(data) {
if (!this.isInitialized()) {
return false;
}
this.members_.innerHTML = bite.project.soy.Member.addMembers(
{members: data[bite.project.Member.Data_.MEMBERS]});
return true;
};
/**
* Reset the model portion of the controller back to an uninitialized state.
* @private
*/
bite.project.Member.prototype.undoSetup_ = function() {
// Make sure and remove the DOM Element from the document upon failure.
if (this.window_) {
bite.common.mvc.helper.removeElementById(bite.project.Member.CONSOLE_ID_);
}
this.buttonCancel_ = null;
this.buttonInvite_ = null;
this.buttonRemove_ = null;
this.invite_ = null;
this.members_ = null;
this.window_ = null;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a background script stub used for testing the project
* subsystem in a standalone fashion.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.BackgroundTest');
goog.require('bite.project.Background');
/**
* Handler is called when the extension icon is pressed. The function will
* send a message to the injected content script notifying it of the action.
* @param {Tab} tab The currently selected tab when the extension icon is
* pressed.
*/
bite.project.BackgroundTest.onBrowserAction = function(tab) {
if (!tab || !tab.id) {
return;
}
var msg = {
'owner': 'bite.project',
'action': 'turn-on'
};
chrome.tabs.sendRequest(tab.id, msg);
};
chrome.browserAction.onClicked.addListener(
bite.project.BackgroundTest.onBrowserAction);
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a content script stub used for testing the project
* subsystem in a standalone fashion.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.ContentTest');
goog.require('bite.project.Content');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
/**
* @constructor
* @export
*/
bite.project.ContentTest = function() {};
/**
* @export
*/
bite.project.ContentTest.init = function() {
var content = bite.project.Content.getInstance();
content.init('/');
var explore = content.getView(bite.project.Content.viewId.EXPLORE);
var general = content.getView(bite.project.Content.viewId.GENERAL);
var member = content.getView(bite.project.Content.viewId.MEMBER);
var settings = content.getView(bite.project.Content.viewId.SETTINGS);
if (!explore || !general || !member || !settings) {
return;
}
goog.dom.appendChild(goog.dom.getDocument().body, explore);
goog.dom.appendChild(goog.dom.getDocument().body, general);
goog.dom.appendChild(goog.dom.getDocument().body, member);
goog.dom.appendChild(goog.dom.getDocument().body, settings);
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unifies the bite.project subsystem within the context of a
* background script. The constructor as a the initializer for the subsystem
* causes the rest of the system to initialize.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.project.Background');
/**
* Constructs an object that manages the project UX within the background.
* @constructor
* @export
*/
bite.project.Background = function() {
};
goog.addSingletonGetter(bite.project.Background);
/**
* Handles messages for the project subsystem and redirects as appropriate.
* @param {!Object} request The data sent.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} response Optional function to call when the
* request completes; only call when appropriate.
* @private
*/
bite.project.Background.prototype.onRequest_ =
function(request, sender, response) {
};
/**
* Create the content instance to initialize the project subsystem in the
* context of a content script.
*/
bite.project.Background.getInstance();
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the code on the background script file.
*
* @author alexto@google.com (Alexis O. Torres)
*/
goog.require('Bite.Constants');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.structs.Queue');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.MockUserAgent');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.net.XhrIo');
goog.require('bite.client.Background');
var mocks_ = null;
var stubs_ = null;
var mockUserAgent_ = null;
var background = null;
function setUp() {
initChrome();
mocks_ = new goog.testing.MockControl();
stubs_ = new goog.testing.PropertyReplacer();
var mockLocalStorage = {getItem: function() {return 'http://hud.test'},
setItem: function() {},
removeItem: function() {}};
stubs_.set(goog.global, 'localStorage', mockLocalStorage);
var mockRpf = mocks_.createStrictMock(rpf.Rpf);
stubs_.set(rpf.Rpf, 'getInstance', function() { return mockRpf; });
stubs_.set(bite.client.Background, 'logEvent', function() {});
background = new bite.client.Background();
stubs_.set(goog.net, 'XhrIo', goog.testing.net.XhrIo);
}
function tearDown() {
stubs_.reset();
if (mockUserAgent_) {
mockUserAgent_.uninstall();
}
}
function getLastXhrIo() {
var sendInstances = goog.testing.net.XhrIo.getSendInstances();
var xhr = sendInstances[sendInstances.length - 1];
return xhr;
}
function testBadgeBegin() {
background.updateBadge_(
new ChromeTab(),
{action: bite.client.Background.FetchEventType.FETCH_BEGIN});
assertEquals('...', chrome.browserAction.details.text);
}
function testBadgeEndZero() {
background.updateBadge_(
new ChromeTab(),
{action: bite.client.Background.FetchEventType.FETCH_END,
count: 0});
assertEquals('0', chrome.browserAction.details.text);
}
function testBadgeEndNotZero() {
background.updateBadge_(
new ChromeTab(),
{action: bite.client.Background.FetchEventType.FETCH_END,
count: 25});
assertEquals('25', chrome.browserAction.details.text);
}
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Background script containing code to handle tasks
* invoked elsewhere in the extension code.
*
* @author alexto@google.com (Alexis O. Torres)
* @author phu@google.com (Po Hu)
*/
goog.provide('bite.client.Background');
goog.require('Bite.Constants');
goog.require('bite.LoginManager');
goog.require('bite.client.BugTemplate');
goog.require('bite.client.TemplateManager');
goog.require('bite.common.net.xhr.async');
goog.require('bite.options.constants');
goog.require('bite.options.data');
goog.require('bugs.api');
goog.require('goog.Timer');
goog.require('goog.Uri');
goog.require('goog.json');
goog.require('goog.userAgent');
goog.require('rpf.MiscHelper');
goog.require('rpf.Rpf');
/**
* The Background Class is a singleton that manages all of BITE's background
* operations and data.
* @constructor
* @export
*/
bite.client.Background = function() {
/**
* @type {string}
* @private
*/
this.currentUser_ = '';
/**
* @type {bite.LoginManager}
* @private
*/
this.loginManager_ = bite.LoginManager.getInstance();
/**
* The template manager controls loading Bug Templates from the server.
* It will load templates directly from the server upon the first request,
* then cache those values.
* @type {bite.client.TemplateManager}
* @private
*/
this.templateManager_ = bite.client.TemplateManager.getInstance();
/**
* @type {rpf.Rpf}
* @private
*/
this.rpf_ = rpf.Rpf.getInstance();
// If this is the first time a user opens BITE, log an event.
var firstRun = (
goog.global.localStorage.getItem(bite.client.Background.PREVIOUS_USE_KEY)
!= 'true');
if (firstRun) {
// Analytics may not be loaded, so delay the logging until after the
// next batch of browser event processing.
goog.Timer.callOnce(goog.partial(bite.client.Background.logEvent,
'Background', 'FirstUse', ''), 0);
goog.global.localStorage.setItem(bite.client.Background.PREVIOUS_USE_KEY,
'true');
}
};
goog.addSingletonGetter(bite.client.Background);
/**
* Key used to keep track of first time use of BITE. The value of this key in
* localStorage will be set to 'true' once the application is loaded for the
* first time.
* @type {string}
*/
bite.client.Background.PREVIOUS_USE_KEY = 'bite-client-background-previous-use';
/**
* URL path for the "get test assigned to me" API.
* @type {string}
* @private
*/
bite.client.Background.prototype.fetchTestsApiPath_ =
'/get_my_compat_test';
/**
* The API path for submitting a test result.
* @type {string}
* @private
*/
bite.client.Background.prototype.submitTestResultApiPath_ =
'/compat/test';
/**
* Enum of events handled by the Background script.
* @enum {string}
* @export
*/
bite.client.Background.FetchEventType = {
FETCH_BEGIN: 'fetchbegin',
FETCH_END: 'fetchend'
};
/**
* Returns the new script url.
* @param {string} project The project name.
* @param {string} script The script name.
* @private
*/
bite.client.Background.prototype.getNewScriptUrl_ = function(project, script) {
var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL);
var url = new goog.Uri(server);
url.setPath('automateRpf');
url.setParameterValue('projectName', project);
url.setParameterValue('scriptName', script);
url.setParameterValue('location', 'web');
return url.toString();
};
/**
* Gets tests for a given web page.
* @param {Tab} tab Tab requesting the tests list.
* @param {function(!*): void} callback Function to call with the list of tests.
* @private
*/
bite.client.Background.prototype.fetchTestData_ =
function(tab, callback) {
var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL);
var testUrl = goog.Uri.parse(server).setPath(
this.fetchTestsApiPath_).toString();
bite.common.net.xhr.async.get(testUrl,
goog.bind(this.fetchTestsDataCallback_, this, callback));
};
/**
* Handle the callback to fetch the tests request.
* @param {function({test: ?Object, user: ?string})} callback
* Callback function.
* @param {boolean} success Whether or not the request was successful.
* @param {string} data The data received from the request or an error string.
* @param {number} status The status of the request.
* @private
*/
bite.client.Background.prototype.fetchTestsDataCallback_ =
function(callback, success, data, status) {
var test = null;
var user = null;
if (success) {
var compatTesting = goog.json.parse(data);
test = compatTesting['test'];
user = compatTesting['user'];
this.currentUser_ = user;
} else {
console.log('Failed to fetch tests: ' + data);
}
callback({'test': test,
'user': user});
};
/**
* Gets bugs for a given webpage.
* @param {Tab} tab Tab requesting the bugs list.
* @param {function({bugs: Object, filters: Object})} callback
* The callback fired with the set of bugs retrieved by url and bug
* filters.
* @private
*/
bite.client.Background.prototype.fetchBugsData_ = function(tab, callback) {
this.updateBadge_(
tab, {'action': bite.client.Background.FetchEventType.FETCH_BEGIN});
bugs.api.urls([tab.url],
goog.bind(this.fetchBugsDataCallback_, this, tab, callback));
};
/**
* Handles the response from the server to fetch bugs data.
* @param {Tab} tab Tab requesting the bugs list.
* @param {function({bugs: Object, filters: Object})} callback
* The callback fired with the set of bugs retrieved by url and bug
* filters.
* @param {!{success: boolean, error: string,
* bugMap: bugs.kind.UrlBugMap}} result The results of the request.
* @private
*/
bite.client.Background.prototype.fetchBugsDataCallback_ = function(tab,
callback,
result) {
if (!result.success) {
console.error('Failed to retrieve bugs for url; ' + result.error);
return;
}
/**
* Bugs is an array of arrays in the format:
* [[urlPart, [bugs]], [urlPart, [bugs]]]
* Where URL part is either the full URL, Hostname + Path, or Hostname,
* of the target URL, and bugs is a list of bugs associated with the
* given urlPart. For example:
* [["www.google.com",
* [{"status": "duplicate", "project": "chromium",..}, ...]]]
*/
var bugs = [];
var urlBugMap = result.bugMap['mappings'];
var totalBugs = 0;
// Translate the urlBugMap into the bugs structure expected by the rest of
// the extension.
// TODO (jason.stredwick): Remvoe translation and update client to use new
// url to bug mapping.
for (var i = 0; i < urlBugMap.length; ++i) {
var url = urlBugMap[i]['url'];
var bugData = urlBugMap[i]['bugs'];
// In order to count the number of bugs returned; for each result in the
// format [urlPart, [bugs]] we need to agregate the bugs count.
totalBugs += bugData.length;
// Create entry in translate bug structure.
bugs.push([url, bugData]);
}
this.updateBadge_(
tab, {'action': bite.client.Background.FetchEventType.FETCH_END,
'count': totalBugs});
callback({'filters': bite.options.data.getCurrentConfiguration(),
'bugs': bugs});
};
/**
* Updates the extension's badge.
* @param {Tab} tab Tab requesting the bugs list.
* @param {Object} request Object data sent in the request.
* @private
*/
bite.client.Background.prototype.updateBadge_ = function(tab, request) {
var text = null;
switch (request['action']) {
case bite.client.Background.FetchEventType.FETCH_BEGIN:
text = '...';
break;
case bite.client.Background.FetchEventType.FETCH_END:
var count = request['count'];
text = count.toString();
break;
default:
throw new Error('The specified action is not valid: ' +
request['action']);
}
chrome.browserAction.setBadgeText({'text': text,
'tabId': tab.id});
};
/**
* @return {rpf.Rpf} The RPF object.
* @export
*/
bite.client.Background.prototype.getRpfObj = function() {
return this.rpf_;
};
/**
* Sets a new RPF object.
* @param {rpf.Rpf} rpfObj The new RPF obj.
* @export
*/
bite.client.Background.prototype.setRpfObj = function(rpfObj) {
this.rpf_ = rpfObj;
};
/**
* Gets a value from localStorage, or 'null' if no value is stored.
* @param {string} key The localStorage key of the item.
* @param {function(?string)} callback The function to call with the value
* from localStorage.
* @private
*/
bite.client.Background.prototype.getLocalStorage_ = function(key, callback) {
var data = /** @type {?string} */ (goog.global.localStorage.getItem(key));
callback(data);
};
/**
* Sets a value in localStorage.
* @param {string} key The localStorage key to set.
* @param {string} value The value to set into localStorage.
* @param {function()} callback A function to callback.
* @private
*/
bite.client.Background.prototype.setLocalStorage_ =
function(key, value, callback) {
goog.global.localStorage.setItem(key, value);
callback();
};
/**
* Removes a value in localStorage.
* @param {string} key The localStorage key to remove.
* @param {function()} callback A function to callback.
* @private
*/
bite.client.Background.prototype.removeLocalStorage_ = function(key, callback) {
goog.global.localStorage.removeItem(key);
callback();
};
/**
* Updates the data in the selected tab of Chrome.
* @param {Tab} tab The created tab object.
* @private
*/
bite.client.Background.prototype.updateData_ = function(tab) {
this.sendRequestToTab_(Bite.Constants.HUD_ACTION.UPDATE_DATA, tab, 0);
};
/**
* Hides the BITE consoles opened in all tabs/windows of Chrome.
* @private
*/
bite.client.Background.prototype.hideAllConsoles_ = function() {
chrome.windows.getAll({'populate': true},
goog.bind(this.hideAllConsolesInWindows_, this));
};
/**
* Hides the BITE consoles found in the list windows provided.
* @param {Array} windows An array of chrome.window objects.
* @private
*/
bite.client.Background.prototype.hideAllConsolesInWindows_ = function(
windows) {
for (var i = 0; i < windows.length; i++) {
for (var k = 0; k < windows[i].tabs.length; k++) {
this.sendRequestToTab_(Bite.Constants.HUD_ACTION.HIDE_CONSOLE,
windows[i].tabs[k], 0);
}
}
};
/**
* Sends the specified request to the content script running
* on the given tab.
* @param {Bite.Constants.HUD_ACTION} action Action the content script
* needs to execute.
* @param {Tab} tab Tab to toggle the visibility on.
* @param {number} delay The number of milliseconds to wait before executing.
* @private
*/
bite.client.Background.prototype.sendRequestToTab_ =
function(action, tab, delay) {
goog.Timer.callOnce(
goog.bind(chrome.tabs.sendRequest, this, tab.id, {'action': action}),
delay);
};
/**
* Gets a list of templates from the server. If the request contains a
* url, gets the templates for that url. If no url is given, returns all
* templates.
* @param {Object} request Dictionary containing request details.
* @param {function(Object.<string, bite.client.BugTemplate>)} callback
* A callback to call with the list of templates.
* @private
*/
bite.client.Background.prototype.getTemplates_ = function(request, callback) {
if (request.url) {
this.templateManager_.getTemplatesForUrl(callback, request.url);
} else {
this.templateManager_.getAllTemplates(callback);
}
};
/**
* Sends the test result back to the server.
* @param {Object} resultData Ojbect containg the result details.
* @param {function(): void} callback Function to call after the result is
* sent.
* @private
*/
bite.client.Background.prototype.logTestResult_ =
function(resultData, callback) {
var result = resultData['result'];
var testId = resultData['testId'];
var comments = resultData['comment'];
var bugs = resultData['bugs'];
var name = '';
switch (result) {
case Bite.Constants.TestResult.PASS:
name = 'passResult';
break;
case Bite.Constants.TestResult.FAIL:
name = 'failResult';
break;
case Bite.Constants.TestResult.SKIP:
name = 'skip';
break;
default:
console.error('Unrecognized test result: ' + result);
break;
}
var queryParams = {'name': testId};
if (bugs) {
queryParams['bugs_' + testId] = bugs;
}
if (comments) {
queryParams['comment_' + testId] = comments;
}
var queryData = goog.Uri.QueryData.createFromMap(queryParams);
var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL);
var url = goog.Uri.parse(server);
url.setPath(this.submitTestResultApiPath_);
bite.common.net.xhr.async.post(url.toString(), queryData.toString(),
goog.bind(this.logTestResultComplete_, this, callback));
};
/**
* Fires when the log request completes. Ignores request response.
* @param {function(): void} callback Function to call after the result is
* sent.
* @private
*/
bite.client.Background.prototype.logTestResultComplete_ = function(callback) {
callback();
};
/**
* Loads the content script into the specified tab.
* @param {Tab} tab The tab to load the content_script into.
* @private
*/
bite.client.Background.prototype.loadContentScript_ = function(tab) {
// The content is dependent on the puppet script for element selection
// in bug filing, so load it first. Then load the content script.
chrome.tabs.executeScript(tab.id, {file: 'content_script.js'});
};
/**
* Ensure the BITE console content script has been loaded.
* @param {Tab} tab The tab to ensure the content script is loaded in.
* @private
*/
bite.client.Background.prototype.startEnsureContentScriptLoaded_ = function(
tab) {
// Create a script that checks for the BITE lock and sends a
// loadContentScript command if it isn't there. This intentionally
// doesn't use closure due to not having the closure libraries available
// when executing.
var contentScriptChecker = '//Checking the content script\n' +
'var biteLock=document.getElementById("' +
Bite.Constants.BITE_CONSOLE_LOCK + '");' +
'if(!biteLock){chrome.extension.sendRequest({action: "' +
Bite.Constants.HUD_ACTION.LOAD_CONTENT_SCRIPT +
'"});}';
chrome.tabs.executeScript(tab.id, {code: contentScriptChecker});
};
/**
* Logs an instrumentation event. NOTE(alexto): This method assumes that
* Google Analytics code is already loaded.
* @param {string} category Main of the main feture serving the event.
* @param {string} action Action that trigger the event.
* @param {string} label Additional information to log about the action.
* @export
*/
bite.client.Background.logEvent = function(category, action, label) {
var gaq = goog.global['_gaq'];
if (gaq) {
gaq.push(['_trackEvent', category, action, label]);
} else {
console.warn('Google Analytics is not ready.');
}
};
/**
* Captures the current page's screenshot.
* @param {function(string)} callback The callback function.
* @private
*/
bite.client.Background.prototype.captureVisibleTab_ = function(callback) {
chrome.tabs.captureVisibleTab(
null, null,
goog.partial(rpf.MiscHelper.resizeImage, callback, 800, null));
};
/**
* Callback function that begins the new bug filing process.
* @param {Tab} tab The created tab object.
* @private
*/
bite.client.Background.prototype.startNewBug_ = function(tab) {
this.startEnsureContentScriptLoaded_(tab);
// Wait 100 ms for the BITE content script to get kicked off.
this.sendRequestToTab_(Bite.Constants.HUD_ACTION.START_NEW_BUG, tab, 100);
};
/**
* Callback function that toggles the bugs console.
* @param {Tab} tab The created tab object.
* @private
*/
bite.client.Background.prototype.toggleBugsConsole_ = function(tab) {
this.startEnsureContentScriptLoaded_(tab);
// Wait 100 ms for the BITE content script to get kicked off.
this.sendRequestToTab_(Bite.Constants.HUD_ACTION.TOGGLE_BUGS, tab, 100);
};
/**
* Callback function that toggles the tests console.
* @param {Tab} tab The created tab object.
* @private
*/
bite.client.Background.prototype.toggleTestsConsole_ = function(tab) {
this.startEnsureContentScriptLoaded_(tab);
// Wait 100 ms for the BITE content script to get kicked off.
this.sendRequestToTab_(Bite.Constants.HUD_ACTION.TOGGLE_TESTS, tab, 100);
};
/**
* Return the url of the current server channel.
* @return {string} The url of the current server channel.
* @private
*/
bite.client.Background.prototype.getServerChannel_ = function() {
return bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL);
};
/**
* Returns the current configuration of the BITE settings/options.
* @return {!Object} The current configuration.
* @private
*/
bite.client.Background.prototype.getSettingsConfiguration_ = function() {
return bite.options.data.getCurrentConfiguration();
};
/**
* Handles request sent via chrome.extension.sendRequest().
* @param {!Object} request Object data sent in the request.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} callback Function to call when the request
* completes.
* @export
*/
bite.client.Background.prototype.onRequest =
function(request, sender, callback) {
// If the request contains a command or the request does not handle requests
// from the specified request's owner then do nothing (i.e. don't process
// this request).
if (request['command']) {
return;
}
switch (request['action']) {
case Bite.Constants.Action.XHR_REQUEST:
{
var command = request['cmd'];
var url = request['url'];
var data = request['data'];
var headers = request['headers'];
var callback_wrapper = function (success, resultText, status) {
if (!callback) {
return;
}
var resultObj = {'success': success,
'reply': resultText,
'status': status};
console.log('Result obj: ');
console.log(resultObj);
callback(resultObj);
};
if (command == 'GET') {
bite.common.net.xhr.async.get(url, callback_wrapper, headers);
} else if (command == 'DELETE') {
bite.common.net.xhr.async.del(url, callback_wrapper, headers);
} else if (command == 'POST') {
bite.common.net.xhr.async.post(url, data, callback_wrapper, headers);
} else if (command == 'PUT') {
bite.common.net.xhr.async.put(url, data, callback_wrapper, headers);
}
}
break;
case Bite.Constants.HUD_ACTION.FETCH_TEST_DATA:
this.fetchTestData_(sender.tab, callback);
break;
case Bite.Constants.HUD_ACTION.FETCH_BUGS_DATA:
this.fetchBugsData_(sender.tab, callback);
break;
case Bite.Constants.HUD_ACTION.LOG_TEST_RESULT:
this.logTestResult_(request, /** @type {function()} */ (callback));
break;
case Bite.Constants.HUD_ACTION.TOGGLE_BUGS:
chrome.tabs.getSelected(null, goog.bind(this.toggleBugsConsole_, this));
break;
case Bite.Constants.HUD_ACTION.TOGGLE_TESTS:
chrome.tabs.getSelected(null, goog.bind(this.toggleTestsConsole_, this));
break;
case Bite.Constants.HUD_ACTION.HIDE_ALL_CONSOLES:
this.hideAllConsoles_();
break;
// UPDATE_DATA updates the data (such as bugs and tests) on the current
// tab.
case Bite.Constants.HUD_ACTION.UPDATE_DATA:
chrome.tabs.getSelected(null, goog.bind(this.updateData_, this));
break;
// Bug templates
case Bite.Constants.HUD_ACTION.GET_TEMPLATES:
this.getTemplates_(request, callback);
break;
// Bug information handling.
case Bite.Constants.HUD_ACTION.START_NEW_BUG:
chrome.tabs.getSelected(null, goog.bind(this.startNewBug_, this));
break;
case Bite.Constants.HUD_ACTION.UPDATE_BUG:
bugs.api.update(request['details'], callback);
break;
case Bite.Constants.HUD_ACTION.CREATE_BUG:
if (request['details'] &&
request['details']['summary'] && request['details']['title']) {
request['details']['summary'] +=
this.getNewScriptUrl_('bugs', request['details']['title']);
}
bugs.api.create(request['details'], callback);
break;
case Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE:
this.getLocalStorage_(request['key'], callback);
break;
case Bite.Constants.HUD_ACTION.SET_LOCAL_STORAGE:
this.setLocalStorage_(request['key'], request['value'],
/** @type {function()} */ (callback));
break;
case Bite.Constants.HUD_ACTION.REMOVE_LOCAL_STORAGE:
this.removeLocalStorage_(request['key'],
/** @type {function()} */ (callback));
break;
case Bite.Constants.HUD_ACTION.ENSURE_CONTENT_SCRIPT_LOADED:
chrome.tabs.getSelected(
null, goog.bind(this.startEnsureContentScriptLoaded_, this));
break;
case Bite.Constants.HUD_ACTION.LOAD_CONTENT_SCRIPT:
chrome.tabs.getSelected(
null, goog.bind(this.loadContentScript_, this));
break;
case Bite.Constants.HUD_ACTION.LOG_EVENT:
bite.client.Background.logEvent(
request['category'], request['event_action'], request['label']);
break;
case Bite.Constants.HUD_ACTION.CREATE_RPF_WINDOW:
this.rpf_.setUserId(request['userId']);
this.rpf_.createWindow();
break;
case Bite.Constants.HUD_ACTION.CHANGE_RECORD_TAB:
this.rpf_.focusRpf();
break;
case Bite.Constants.HUD_ACTION.GET_CURRENT_USER:
var server = bite.options.data.get(
bite.options.constants.Id.SERVER_CHANNEL);
this.loginManager_.getCurrentUser(callback, server);
break;
case Bite.Constants.HUD_ACTION.GET_SERVER_CHANNEL:
callback(this.getServerChannel_());
break;
case Bite.Constants.HUD_ACTION.GET_SETTINGS:
callback(this.getSettingsConfiguration_());
break;
case Bite.Constants.HUD_ACTION.GET_SCREENSHOT:
this.captureVisibleTab_(callback);
break;
// UPDATE updates the data from BITE options.
case bite.options.constants.Message.UPDATE:
chrome.windows.getAll({'populate': true},
goog.bind(this.broadcastConfigurationChange_, this));
break;
default:
throw new Error('The specified action is not valid: ' +
request['action']);
}
};
/**
* Broadcast the current configuration to all content scripts.
* @param {Array.<Object>} windows An Array of Chrome windows.
* @private
*/
bite.client.Background.prototype.broadcastConfigurationChange_ =
function(windows) {
var configuration = bite.options.data.getCurrentConfiguration();
var msg = {};
msg['action'] = bite.options.constants.Message.UPDATE;
msg['data'] = goog.json.serialize(configuration);
// For each window, loop over its tabs and send a message with the current
// configuration.
for (var i = 0; i < windows.length; ++i) {
var window = windows[i];
var tabs = window.tabs;
if (!tabs) {
continue;
}
for (var j = 0; j < tabs.length; ++j) {
var tab = tabs[j];
chrome.tabs.sendRequest(tab.id, msg, goog.nullFunction);
}
}
};
// Wire up the listener.
chrome.extension.onRequest.addListener(
goog.bind(bite.client.Background.getInstance().onRequest,
bite.client.Background.getInstance()));
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Heads-up Display content script.
*
* @author alexto@google.com (Alexis O. Torres)
*/
goog.provide('bite.client.Content');
goog.require('Bite.Constants');
goog.require('bite.bugs.filter');
goog.require('bite.client.BugOverlay');
goog.require('bite.client.BugsConsole');
goog.require('bite.client.ElementMapper');
goog.require('bite.client.ElementSelector');
goog.require('bite.client.Templates');
goog.require('bite.client.TestsConsole');
goog.require('bite.client.console.NewBug');
goog.require('bite.client.console.NewBugTypeSelector');
goog.require('bite.console.Helper');
goog.require('bite.console.Screenshot');
goog.require('bite.options.constants');
goog.require('common.client.ElementDescriptor');
goog.require('goog.Timer');
goog.require('goog.Uri.QueryData');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.ViewportSizeMonitor');
goog.require('goog.dom.classes');
goog.require('goog.json');
goog.require('goog.math');
goog.require('goog.style');
goog.require('goog.userAgent');
goog.require('goog.userAgent.jscript');
goog.require('goog.userAgent.platform');
/**
* Content script class.
* @constructor
* @export
*/
bite.client.Content = function() {
/**
* Whether or not the current page is in the list of pages we should
* autorecord.
* @type {boolean}
* @private
*/
this.isAutoRecordPage_ = this.isAutoRecordUrl_(goog.global.location.href);
/**
* Whether or not RPF should automatically begin recording.
* @type {boolean}
* @private
*/
this.autoRecord_ = false;
/**
* The manager for the overlay.
* @type {bite.client.BugOverlay}
* @private
*/
this.bugOverlay_ = null;
/**
* Manager of the Bugs Console.
* @type {bite.client.BugsConsole}
* @private
*/
this.bugsConsole_ = null;
/**
* Manager of the Test Console.
* @type {bite.client.TestsConsole}
* @private
*/
this.testsConsole_ = null;
/**
* Monitors the viewport (window).
* @type {!goog.dom.ViewportSizeMonitor}
* @private
*/
this.biteViewportSizeMonitor_ = new goog.dom.ViewportSizeMonitor();
/**
* Manages selecting a new UI element when reporting a new bug from the page.
* @type {bite.client.ElementSelector}
* @private
*/
this.elementSelector_ = null;
/**
* Buffer for recorded script string.
* @type {string}
* @private
*/
this.recordingScript_ = '';
/**
* Buffer for the recorded script in human readable format.
* @type {string}
* @private
*/
this.recordingReadable_ = '';
/**
* Buffer for special recorded data (e.g. while while types).
* @type {string}
* @private
*/
this.recordingData_ = '';
/**
* The screenshot manager instance.
* @type {bite.console.Screenshot}
* @private
*/
this.screenshotMgr_ = new bite.console.Screenshot();
/**
* Buffer for recorded script's info map.
* @type {Object}
* @private
*/
this.recordingInfoMap_ = {};
/**
* Whether it's currently in the state of recording user actions.
* @type {boolean}
* @private
*/
this.isRecordingActions_ = false;
/**
* Whether a new bug is currently being filed.
* @type {boolean}
* @private
*/
this.isFilingNewBug_ = false;
/**
* The console for selecting the type of a new bug.
* @type {bite.client.console.NewBugTypeSelector}
* @private
*/
this.newBugTypeSelector_ = null;
/**
* The url of the current server channel.
* @type {string}
* @private
*/
this.serverChannel_ = '';
/**
* Retrieve the settings and current user info.
*/
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_SETTINGS},
goog.bind(this.handleSettings_, this, goog.nullFunction));
// Add a listener for window resizes.
goog.events.listen(this.biteViewportSizeMonitor_,
goog.events.EventType.RESIZE,
goog.bind(this.windowResizeHandler_, this));
// Add a listener for keyboard shortcuts.
goog.events.listen(goog.global.document.body,
goog.events.EventType.KEYDOWN,
goog.bind(this.shortcutHandler_, this));
};
/**
* Element seleted while logging a new bug or dragging an exising
* bug in to the right context.
* @type {Element}
* @private
*/
bite.client.Content.prototype.selectedElement_ = null;
/**
* @type {?bite.client.console.NewBug}
* @private
*/
bite.client.Content.prototype.newBugConsole_ = null;
/**
* Id of the bug template to show when the new bug console is shown.
* @type {string}
* @private
*/
bite.client.Content.prototype.newBugTemplateId_ = '';
/**
* Bugs data.
* @type {Object}
* @private
*/
bite.client.Content.prototype.bugs_ = null;
/**
* Bug data filters.
* @type {Object}
* @private
*/
bite.client.Content.prototype.bugFilters_ = null;
/**
* User email.
* @type {?string}
* @private
*/
bite.client.Content.prototype.user_ = null;
/**
* Buffer for the link to recorded script in json format.
* @type {?string}
* @private
*/
bite.client.Content.prototype.recordingLink_ = null;
/**
* Handles the response from the retrieving the settings.
* @param {?function(string)} callback A method to callback with retrieved url.
* @param {Object} settings The settings data. This is a mapping of option
* ids in bite.options.constants.Id to their values.
* @private
*/
bite.client.Content.prototype.handleSettings_ = function(callback, settings) {
this.serverChannel_ = settings[bite.options.constants.Id.SERVER_CHANNEL];
if (settings[bite.options.constants.Id.AUTO_RECORD] == 'true') {
this.autoRecord_ = true;
} else {
this.autoRecord_ = false;
}
if (callback) {
callback(this.serverChannel_);
}
// To enable stand-alone bug filing (without the Bugs console), and Maps
// specific features get the user's info and then finish initializing.
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_CURRENT_USER},
goog.bind(this.getCurrentUser_, this,
goog.bind(this.constructorCallback_, this)));
};
/**
* Callback function to finish initializing this class. Begins auto-recording
* if the page url matches those for automatic recording.
* @private
*/
bite.client.Content.prototype.constructorCallback_ = function() {
if (this.isAutoRecordPage_ && this.autoRecord_) {
this.overrideBiteInstallLink_();
this.startRecording_();
}
};
/**
* Handles the response from the backend for pages.
* @param {Object} e Key event object containing data on what was pressed.
* @private
*/
bite.client.Content.prototype.shortcutHandler_ = function(e) {
if (e.ctrlKey && e.altKey) {
if (e.keyCode == Bite.Constants.KeyCodes.B_KEY) {
this.startNewBugHandler_();
}
}
};
/**
* Sets the template id that the New Bug console will use as its default.
* @param {string} template The id of the new template.
*/
bite.client.Content.prototype.setNewBugTemplateId = function(template) {
this.newBugTemplateId_ = template;
};
/**
* Overrides the BITE Install button link if it is on the website.
* Clicking on the link when BITE is installed will open the New Bug
* console.
*
* @private
*/
bite.client.Content.prototype.overrideBiteInstallLink_ = function() {
var biteInstallButton = goog.dom.getElement('bite-install-link');
if (biteInstallButton) {
goog.dom.setProperties(biteInstallButton,
{'href': 'javascript: void(0)',
'id': 'bite-already-installed-link'});
goog.events.removeAll(biteInstallButton);
goog.events.listen(biteInstallButton, goog.events.EventType.CLICK,
goog.bind(this.startNewBugHandler_, this));
}
// The code below supports the version of maps without the bite install link.
var bugReport = goog.dom.getElement('bugreport');
if (!bugReport) {
return;
}
var link = goog.dom.getFirstElementChild(bugReport);
if (!link) {
return;
}
goog.dom.setProperties(link, {'href': 'javascript: void(0)'});
goog.events.removeAll(link);
goog.events.listen(link, goog.events.EventType.CLICK,
goog.bind(this.startNewBugHandler_, this));
};
/**
* Gets current user's email address.
* @param {function()} callback The callback to invoke.
* @param {{success: boolean, username: string, url: string}} responseObj
* An object that contains the login or logout url and optionally
* the username of the user.
* @private
*/
bite.client.Content.prototype.getCurrentUser_ =
function(callback, responseObj) {
if (!responseObj['success']) {
console.warn('Error checking login status.');
} else {
this.user_ = responseObj['username'];
}
callback();
};
/**
* Notify the user that they can't perform that action without logging in.
* @private
*/
bite.client.Content.prototype.createLoginErrorMessage_ = function() {
alert('You must be logged in to perform that action. \n' +
'Please log in at ' + this.serverChannel_ + ' and try again.');
};
/**
* Returns whether or not a given url is in the list of urls that should
* trigger automatic recording.
* @param {string} url The url to check.
* @return {boolean} True if the url should trigger automatic recording.
* @private
*/
bite.client.Content.prototype.isAutoRecordUrl_ = function(url) {
var uri = new goog.Uri(url);
var urls = Bite.Constants.AUTO_RECORD_URLS;
for (var i = 0; i < urls.length; ++i) {
if (goog.string.caseInsensitiveCompare(uri.getDomain(), urls[i]) == 0) {
return true;
}
}
return false;
};
/**
* Automatically starts recording user actions on a page
* (with no rpf Console UI constructed).
* @private
*/
bite.client.Content.prototype.startRecording_ = function() {
this.isRecordingActions_ = true;
chrome.extension.sendRequest(
{'command': Bite.Constants.CONSOLE_CMDS.SET_TAB_AND_START_RECORDING,
'params': {'url': ''}});
bite.client.Content.logEvent_('StartedRecording', '');
};
/**
* Stops recording user actions on a page and saves the test script on
* the web.
* @private
*/
bite.client.Content.prototype.stopRecording_ = function() {
if (!this.isRecordingActions_) {
return;
}
chrome.extension.sendRequest(
{'command': Bite.Constants.CONSOLE_CMDS.STOP_RECORDING});
bite.client.Content.logEvent_('StoppedRecording', '');
this.isRecordingActions_ = false;
};
/**
* Static method used to instrument the usage of BITE's content script.
* @param {string} action The action to log.
* @param {string} label Additional details related to the action to log.
* @private
*/
bite.client.Content.logEvent_ = function(action, label) {
chrome.extension.sendRequest({'action': Bite.Constants.HUD_ACTION.LOG_EVENT,
'category': Bite.Constants.TestConsole.NONE,
'event_action': action,
'label': label});
};
/**
* Called when the window resizes and updates BITE features that need it.
* @private
*/
bite.client.Content.prototype.windowResizeHandler_ = function() {
// Update bug overlay.
if (this.bugOverlay_ && this.bugOverlay_.bugOverlayOn()) {
this.bugOverlay_.render();
}
};
/**
* Removes the console element from the page.
* @private
*/
bite.client.Content.prototype.removeAllConsoles_ = function() {
if (this.bugsConsole_) {
this.bugsConsole_.removeConsole();
this.bugsConsole_ = null;
}
if (this.testsConsole_) {
this.testsConsole_.removeConsole();
this.testsConsole_ = null;
}
if (this.newBugConsole_) {
this.newBugConsole_.cancel();
this.newBugConsole_ = null;
}
};
// TODO(ralphj): Add a function to just hide the consoles.
/**
* Starts the process of filing a new bug. Begins by checking if the user is
* logged in.
* @private
*/
bite.client.Content.prototype.startNewBugHandler_ = function() {
if (!this.user_) {
// Try getting the current user one more time.
var callback = goog.bind(this.startNewBug_, this);
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_CURRENT_USER},
goog.bind(this.getCurrentUser_, this, callback));
return;
}
this.startNewBug_();
};
/**
* Begins filing a new bug. The first step is to show the New Bug Type
* Selector. If the current page does not have any Bug Template options,
* the type selector will automatically move to the next step.
* @private
*/
bite.client.Content.prototype.startNewBug_ = function() {
if (!this.user_) {
this.createLoginErrorMessage_();
return;
}
// Don't start filing a new bug if the process of filing a new bug has
// already begun.
if (this.isFilingNewBug_) {
return;
}
this.isFilingNewBug_ = true;
this.stopRecording_();
this.removeAllConsoles_();
if (!this.newBugTypeSelector_) {
this.newBugTypeSelector_ =
new bite.client.console.NewBugTypeSelector(
goog.bind(this.setNewBugTemplateId, this),
goog.bind(this.toggleReportBug_, this),
goog.bind(function() {this.isFilingNewBug_ = false;}, this));
}
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.GET_TEMPLATES,
url: goog.global.location.href},
goog.bind(this.newBugTypeSelector_.load, this.newBugTypeSelector_));
};
/**
* Toggles the visibility of the Bugs console.
* @private
*/
bite.client.Content.prototype.toggleBugs_ = function() {
if (this.bugsConsole_) {
if (this.bugsConsole_.isConsoleVisible()) {
this.bugsConsole_.hideConsole();
} else {
this.bugsConsole_.showConsole();
}
} else {
this.loadBugsConsole();
}
};
/**
* Toggles the visibility of the Tests console.
* @private
*/
bite.client.Content.prototype.toggleTests_ = function() {
if (this.testsConsole_) {
if (this.testsConsole_.isConsoleVisible()) {
this.testsConsole_.hideConsole();
} else {
this.testsConsole_.showConsole();
}
} else {
this.loadTestsConsole();
}
};
/**
* Handles when the New Bug console is done (it is cancelled or a new bug is
* logged using it).
* @private
*/
bite.client.Content.prototype.newBugConsoleDoneHandler_ = function() {
this.newBugConsole_ = null;
this.isFilingNewBug_ = false;
};
/**
* Handles loading/showing the New Bug console.
* @private
*/
bite.client.Content.prototype.loadNewBugConsole_ = function() {
if (!this.newBugConsole_) {
var callback = goog.bind(this.newBugConsoleDoneHandler_, this);
this.newBugConsole_ = new bite.client.console.NewBug(this.user_, callback);
}
// The console will not be displayed until the template list is retrieved.
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.GET_TEMPLATES},
goog.bind(this.finishLoadNewBugConsole_, this));
};
/**
* Finishes loading the New Bug Console by displaying it to the user.
* @param {!Object.<string, bite.client.BugTemplate>} templates The templates to
* show.
* @private
*/
bite.client.Content.prototype.finishLoadNewBugConsole_ = function(templates) {
this.newBugConsole_.show(this.selectedElement_,
this.serverChannel_,
templates,
this.newBugTemplateId_,
this.recordingLink_,
this.recordingScript_,
this.recordingReadable_,
this.recordingData_,
this.recordingInfoMap_);
};
/**
* Toggles Report a bug recording mode.
* @private
*/
bite.client.Content.prototype.toggleReportBug_ = function() {
if (!this.elementSelector_) {
this.elementSelector_ = new bite.client.ElementSelector(
goog.bind(function() {this.isFilingNewBug_ = false;}, this));
}
var label = 'IS_RECORDING: ' + this.elementSelector_.isActive();
bite.client.Content.logEvent_('ToggleReportBug', label);
if (this.elementSelector_.isActive()) {
this.elementSelector_.cancelSelection();
} else if (this.user_) {
// Only enter recording mode if the user is logged in.
this.removeAllConsoles_();
this.elementSelector_.startRecording(
goog.bind(this.endReportBugHandler_, this));
}
};
/**
* Refreshes the UI to reflect any changes in bug data.
* @private
*/
bite.client.Content.prototype.refreshBugConsoleUI_ = function() {
bite.bugs.filter(this.bugs_, this.bugFilters_);
if (this.bugsConsole_) {
this.bugsConsole_.updateData(this.bugs_, this.user_, this.serverChannel_);
}
};
/**
* Returns a bug with a specified id.
* @param {string} id The id of the bug to look up.
* @return {?Object} A dictionary of the Bug data elements, or
* null if a matching bug wasn't found.
* @private
*/
bite.client.Content.prototype.getBugData_ = function(id) {
for (var i = 0; i < this.bugs_.length; ++i) {
for (var j = 0, bugs = this.bugs_[i][1]; j < bugs.length; ++j) {
if (bugs[j]['id'] == id) {
return bugs[j];
}
}
}
return null;
};
/**
* Gets the link to recorded and saved test from saveloadmanager.js.
* @param {!Object.<string, string>} request Object Data sent in the request.
* @private
*/
bite.client.Content.prototype.getRecordingLink_ = function(request) {
this.recordingLink_ = request['recording_link'];
};
/**
* Handles the callback after an element is clicked while logging a new bug.
* @param {Element} selectedElement Element the user clicked on.
* @private
*/
bite.client.Content.prototype.endReportBugHandler_ = function(selectedElement) {
this.selectedElement_ = selectedElement;
this.loadNewBugConsole_();
};
/**
* Parses a string containing "###, ###" coordinates.
* @param {string} coordinates a string containing "###, ###" coordinates.
* @return {Array} An array of ints with [x, y] coordinates.
* @private
*/
bite.client.Content.prototype.parseCoordinates_ = function(coordinates) {
var coordComponents = coordinates.split(',');
return [parseInt(coordComponents[0], 10), parseInt(coordComponents[1], 10)];
};
/**
* Updates the bugs data.
* @param {Object} result Bug data known for the page.
*/
bite.client.Content.prototype.updateBugsData = function(result) {
if (!this.user_) {
// Try getting the current user one more time.
var callback = goog.bind(this.updateBugsData_, this, result);
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_CURRENT_USER},
goog.bind(this.getCurrentUser_, this, callback));
return;
}
this.updateBugsData_(result);
};
/**
* Updates the bugs data.
* @param {Object} result Bug data known for the page.
*/
bite.client.Content.prototype.updateBugsData_ = function(result) {
this.bugs_ = result['bugs'];
this.bugFilters_ = result['filters'];
bite.bugs.filter(this.bugs_, this.bugFilters_);
if (this.bugsConsole_) {
this.bugsConsole_.updateData(result['bugs'], this.user_,
this.serverChannel_);
}
if (this.bugOverlay_) {
this.bugOverlay_.updateData(result['bugs']);
}
};
/**
* Updates the tests data.
* @param {Object} result Test data known for the page.
*/
bite.client.Content.prototype.updateTestData =
function(result) {
this.user_ = result['user'];
if (this.testsConsole_) {
this.testsConsole_.updateData(result['test'], this.user_,
this.serverChannel_);
}
};
/**
* Loads the bugs console tab.
* @export
*/
bite.client.Content.prototype.loadBugsConsole = function() {
bite.client.Content.fetchBugsData();
if (!this.bugsConsole_) {
// Set up the overlay before passing it to the bugs console.
this.bugOverlay_ = new bite.client.BugOverlay();
this.bugsConsole_ = new bite.client.BugsConsole(this.user_,
this.serverChannel_,
this.bugOverlay_);
}
bite.client.Content.logEvent_('Load', 'SET_VISIBLE: ' +
this.bugsConsole_.isConsoleVisible());
};
/**
* Submits a bug recording to the server. This function is going to be used,
* when updating existing bugs with recording information.
* @param {Object} bugData a dictionary of the bug data for this binding.
* @param {string} recording_link The link to recorded steps.
* @private
*/
bite.client.Content.prototype.submitBugRecording_ = function(
bugData, recording_link) {
var requestData = {'action': Bite.Constants.HUD_ACTION.UPDATE_BUG,
'project': bugData['project'],
'details': {'id': bugData['kind'],
'kind': bugData['id'],
'recording_link': recording_link}};
chrome.extension.sendRequest(requestData);
};
/**
* Loads the test console tab.
* @export
*/
bite.client.Content.prototype.loadTestsConsole = function() {
bite.client.Content.fetchTestData();
if (!this.testsConsole_) {
this.testsConsole_ = new bite.client.TestsConsole(this.user_,
this.serverChannel_);
}
bite.client.Content.logEvent_('Load', 'SET_VISIBLE: ' +
this.testsConsole_.isConsoleVisible());
};
/**
* Handles request sent via chrome.extension.sendRequest().
* @param {!Object.<string, string|Object>} request Object Data sent in
* the request.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} callback Function to call when the request
* completes.
* @export
*/
bite.client.Content.prototype.onRequest = function(request, sender, callback) {
if (request['command']) {
this.handleScriptCommand_(request, sender, callback);
} else if (request['action']) {
this.handleBugCommand_(request, sender, callback);
}
};
/**
* Handles the script related commands.
* @param {!Object.<string, string|Object>} request Object Data sent in
* the request.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} callback Function to call when the request
* completes.
* @private
*/
bite.client.Content.prototype.handleScriptCommand_ = function(
request, sender, callback) {
switch (request['command']) {
case Bite.Constants.UiCmds.ADD_SCREENSHOT:
this.screenshotMgr_.addScreenShot(
/** @type {string} */ (request['dataUrl']),
/** @type {string} */ (request['iconUrl']));
break;
case Bite.Constants.UiCmds.ADD_NEW_COMMAND:
var params = request['params'];
this.recordingScript_ += (params['pCmd'] + '\n\n');
this.recordingReadable_ += (params['readableCmd'] + '\n\n');
if (params['dCmd']) {
this.recordingData_ += (params['dCmd'] + '\n');
}
this.screenshotMgr_.addIndex(params['cmdMap']['id']);
bite.console.Helper.assignInfoMap(
this.recordingInfoMap_, params['cmdMap']);
break;
}
};
/**
* Handles the bug related commands.
* @param {!Object.<string, string, Object>} request Object Data sent in
* the request.
* @param {MessageSender} sender An object containing information about the
* script context that sent the request.
* @param {function(!*): void} callback Function to call when the request
* completes.
* @private
*/
bite.client.Content.prototype.handleBugCommand_ = function(
request, sender, callback) {
switch (request['action']) {
case Bite.Constants.HUD_ACTION.GET_RECORDING_LINK:
this.getRecordingLink_(request);
break;
case Bite.Constants.HUD_ACTION.HIDE_CONSOLE:
this.removeAllConsoles_();
break;
case Bite.Constants.HUD_ACTION.START_NEW_BUG:
this.startNewBugHandler_();
break;
case Bite.Constants.HUD_ACTION.TOGGLE_BUGS:
this.toggleBugs_();
break;
case Bite.Constants.HUD_ACTION.TOGGLE_TESTS:
this.toggleTests_();
break;
case Bite.Constants.HUD_ACTION.UPDATE_DATA:
bite.client.Content.fetchTestData();
bite.client.Content.fetchBugsData();
break;
case bite.options.constants.Message.UPDATE:
var requestObj = goog.json.parse(request['data'] || '{}');
this.serverChannel_ = requestObj['serverChannel'];
this.bugFilters_ = requestObj;
this.refreshBugConsoleUI_();
break;
default:
goog.global.console.error(
'Action not recognized: ' + request['action']);
break;
}
};
/**
* An instance of this class.
* @type {bite.client.Content}
* @export
*/
bite.client.Content.instance = new bite.client.Content();
/**
* Send request to background page to fetch tests
* relevant to the current page.
* @export
*/
bite.client.Content.fetchTestData = function() {
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.FETCH_TEST_DATA,
target_url: goog.global.location.href},
goog.bind(bite.client.Content.instance.updateTestData,
bite.client.Content.instance));
};
/**
* Send request to background page to fetch bugs relevant to the
* current page.
* @export
*/
bite.client.Content.fetchBugsData = function() {
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.FETCH_BUGS_DATA,
target_url: goog.global.location.href},
goog.bind(bite.client.Content.instance.updateBugsData,
bite.client.Content.instance));
};
/**
* Creates a lock so multiple instances of the content script won't run.
* @param {string} id the ID of the lock.
* @export
*/
function createLock(id) {
var biteLock = goog.dom.createDom(goog.dom.TagName.DIV, {'id': id});
// Insert the lock element in the document head, to prevent it from
// inteferring with xpaths in the body.
goog.dom.appendChild(goog.global.document.head, biteLock);
}
//Create a lock so other instances won't run on top of this one.
createLock(Bite.Constants.BITE_CONSOLE_LOCK);
goog.exportSymbol(
'bite.client.Content.instance', bite.client.Content.instance);
// Wire up the requests.
chrome.extension.onRequest.addListener(
goog.bind(bite.client.Content.instance.onRequest,
bite.client.Content.instance));
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The element selector asks the user to pick a UI element
* from the website, and highlights the element under their cursor in yellow
* until they choose one. It will then call a callback with the selected
* element.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.provide('bite.client.ElementSelector');
goog.require('bite.ux.Dragger');
goog.require('bite.client.console.NewBugTemplate');
goog.require('common.client.RecordModeManager');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('soy');
/**
* Element selector constructor.
* @param {function()=} opt_cancelCallback A function to call if the element
* selector is cancelled.
* @constructor
*/
bite.client.ElementSelector = function(opt_cancelCallback) {
/**
* Manages the selection of a UI element and highlighting the element.
* @type {common.client.RecordModeManager}
* @private
*/
this.recordModeManager_ = new common.client.RecordModeManager();
/**
* A function to call if the element selector is cancelled.
* @type {function()}
* @private
*/
this.cancelCallback_ = opt_cancelCallback || goog.nullFunction;
/**
* A popup telling the user to select an element on the page.
* @type {Element}
* @private
*/
this.popup_ = null;
/**
* A function to callback on the selected element.
* @type {?function(Element)}
* @private
*/
this.callback_ = null;
/**
* Whether or not the element selector is active.
* @type {boolean}
* @private
*/
this.isActive_ = false;
/**
* Manages events for the element selector popup.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
/**
* Manages dragging the popup.
* @type {bite.ux.Dragger}
* @private
*/
this.dragger_ = null;
};
/**
* Instructs the element selector to start recording.
* @param {function(Element)} callback A callback that is called
* when the user clicks on an element. If no element is selected,
* the element will be null.
* @return {boolean} Whether or not the element selector succesfully began
* recording.
*/
bite.client.ElementSelector.prototype.startRecording = function(callback) {
if (this.isActive_) {
return false;
}
this.callback_ = callback;
this.recordModeManager_.enterRecordingMode(
goog.bind(this.onSelection_, this));
this.isActive_ = true;
var rootFolder = chrome.extension.getURL('');
this.popup_ = soy.renderAsElement(
bite.client.console.NewBugTemplate.newBugPrompt,
{rootFolder: rootFolder});
goog.dom.appendChild(goog.dom.getDocument().body, this.popup_);
var headerElement = goog.dom.getElementByClass('bite-header', this.popup_);
// Center the element selector in the viewport.
var viewport = goog.dom.getViewportSize();
var popupSize = goog.style.getSize(this.popup_);
goog.style.setPosition(
this.popup_,
(viewport.width - popupSize.width) / 2,
(viewport.height - popupSize.height) / 2);
if (headerElement) {
this.dragger_ = new bite.ux.Dragger(this.popup_,
/** @type {!Element} */ (headerElement));
}
this.setHandlers_();
return true;
};
/**
* Cancels the element selector if currently recording.
*/
bite.client.ElementSelector.prototype.cancelSelection = function() {
this.cancelCallback_();
this.cleanUp_();
};
/**
* Returns whether or not the element selector is currently active.
* @return {boolean} Whether the selector is active.
*/
bite.client.ElementSelector.prototype.isActive = function() {
return this.isActive_;
};
/**
* Handler for when the user clicks on an element.
* @param {Element} element The element which was clicked.
* @private
*/
bite.client.ElementSelector.prototype.onSelection_ =
function(element) {
this.cleanUp_();
this.callback_(element);
};
/**
* Handles the case where the user indicates that there is no specific
* UI element related to the issue.
* @private
*/
bite.client.ElementSelector.prototype.noSelection_ = function() {
this.cleanUp_();
this.callback_(null);
};
/**
* Turns off the record mode manager when mouse is over the popup. This
* prevents the popup from being highlighted.
* @private
*/
bite.client.ElementSelector.prototype.mouseOverHandler_ = function() {
this.recordModeManager_.exitRecordingMode();
};
/**
* Turns the record mode manager back on when the mouse leaves the popup.
* @private
*/
bite.client.ElementSelector.prototype.mouseOutHandler_ = function() {
this.recordModeManager_.enterRecordingMode(
goog.bind(this.onSelection_, this));
};
/**
* Exits recording mode if applicable and removes the popup.
* @private
*/
bite.client.ElementSelector.prototype.cleanUp_ = function() {
if (this.recordModeManager_.isRecording()) {
this.recordModeManager_.exitRecordingMode();
}
goog.dom.getDocument().body.removeChild(this.popup_);
this.popup_ = null;
this.dragger_ = null;
this.isActive_ = false;
};
/**
* Sets up the event listeners for the event selector popup.
* @private
*/
bite.client.ElementSelector.prototype.setHandlers_ = function() {
var cancelButton = goog.dom.getElementByClass('bite-close-button',
this.popup_);
this.eventHandler_.listen(cancelButton,
goog.events.EventType.CLICK,
goog.bind(this.cancelSelection, this));
var noSelectionButton = goog.dom.getElementByClass(
'bite-newbug-prompt-no-ui', this.popup_);
this.eventHandler_.listen(noSelectionButton,
goog.events.EventType.CLICK,
goog.bind(this.noSelection_, this));
this.eventHandler_.listen(this.popup_,
goog.events.EventType.MOUSEOVER,
goog.bind(this.mouseOverHandler_, this));
this.eventHandler_.listen(this.popup_,
goog.events.EventType.MOUSEOUT,
goog.bind(this.mouseOutHandler_, this));
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Handles the Tests console, which shows testing suites
* that the user belongs to.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.provide('bite.client.TestsConsole');
goog.require('Bite.Constants');
goog.require('bite.ux.Container');
goog.require('bite.client.Templates');
goog.require('goog.dom');
goog.require('goog.events.EventHandler');
goog.require('soy');
/**
* Creates a tests console and displays it on the current page.
* @param {?string} user The email of the current user.
* @param {string} server The current server channel.
* @constructor
*/
bite.client.TestsConsole = function(user, server) {
/**
* The tests console container.
* @type {bite.ux.Container}
* @private
*/
this.container_ = null;
/**
* Manages events on the overlay.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
/**
* Test data.
*
* TODO(ralphj): Considering making this more specified than 'object'.
* @type {Object}
* @private
*/
this.test_ = null;
this.load_(user, server);
};
/**
* Returns whether or not the console is currently visible on screen.
* @return {boolean} True if the console is visible.
*/
bite.client.TestsConsole.prototype.isConsoleVisible = function() {
if (this.container_) {
return this.container_.isVisible();
}
return false;
};
/**
* Updates the data stored in the test console.
* @param {Object} test The new test data.
* @param {?string} user The email of the current user.
* @param {string} server The current server channel.
*/
bite.client.TestsConsole.prototype.updateData = function(test, user, server) {
this.test_ = test;
this.renderTestsInfo_(user, server);
};
/**
* Removes the console element from the page.
* @return {boolean} Whether the console was removed or not.
*/
bite.client.TestsConsole.prototype.removeConsole = function() {
if (this.container_) {
this.container_.remove();
this.container_ = null;
this.eventHandler_.removeAll();
return true;
}
return false;
};
/**
* Hides the console element from the page.
*/
bite.client.TestsConsole.prototype.hideConsole = function() {
if (this.container_) {
this.container_.hide();
}
};
/**
* Shows the console element.
*/
bite.client.TestsConsole.prototype.showConsole = function() {
if (this.container_) {
this.container_.show();
}
};
/**
* Loads the test console.
* @param {?string} user The user's e-mail.
* @param {string} server The server url.
* @private
*/
bite.client.TestsConsole.prototype.load_ = function(user, server) {
this.container_ = new bite.ux.Container(server, 'bite-tests-console',
'Tests', 'Lists Available Tests',
true);
var rootFolder = chrome.extension.getURL('');
this.container_.setContentFromHtml(bite.client.Templates.testsConsole(
{rootFolder: rootFolder,
serverUrl: server}));
this.renderTestsInfo_(user, server);
this.setConsoleHandlers_();
};
/**
* Renders information about the available tests.
* @param {?string} user The user's e-mail.
* @param {string} server The server url.
* @private
*/
bite.client.TestsConsole.prototype.renderTestsInfo_ = function(user, server) {
if (this.test_) {
var testId = this.test_['test_id'];
var redirectUrl = server + '/compat/redirect?test_id=' +
testId;
var targetUrl = goog.dom.getElementByClass('bite-console-target-url',
this.container_.getRoot());
targetUrl.innerHTML = goog.dom.createDom(
'a', {'href': redirectUrl}, this.test_['test_url']).outerHTML;
var reproSteps = goog.dom.getElement('bite-tests-console-repro-steps');
reproSteps.innerText = this.test_['verification_steps'];
} else {
var contentHtml = 'No tests are available. ';
if (user) {
contentHtml += 'You are logged in as ' + user +
'. Not you? <a href="' + server +
'">Please re-login.</a>';
} else {
contentHtml += '<b><a href="' + server +
'">Please login.</a></b>';
}
var contentCanvas = goog.dom.getElement('bite-tests-content-canvas');
contentCanvas.innerHTML = contentHtml;
}
};
/**
* Sets up the handlers for the tests console.
* @private
*/
bite.client.TestsConsole.prototype.setConsoleHandlers_ = function() {
var hideConsole = goog.dom.getElementByClass('bite-close-button',
this.container_.getRoot());
if (hideConsole) {
this.eventHandler_.listen(hideConsole, goog.events.EventType.CLICK,
goog.bind(this.hideConsole, this));
}
var passButton = goog.dom.getElement('bite-tests-toolbar-button-pass');
if (this.test_ && passButton) {
this.eventHandler_.listen(passButton, goog.events.EventType.CLICK,
goog.bind(this.confirmAction_, this,
Bite.Constants.TestResult.PASS));
} else if (passButton) {
goog.dom.classes.swap(passButton, 'bite-toolbar-button',
'bite-toolbar-button-disabled');
}
var failButton = goog.dom.getElement('bite-tests-toolbar-button-fail');
if (this.test_ && failButton) {
this.eventHandler_.listen(failButton, goog.events.EventType.CLICK,
goog.bind(this.confirmAction_, this,
Bite.Constants.TestResult.FAIL));
} else if (failButton) {
goog.dom.classes.swap(failButton, 'bite-toolbar-button',
'bite-toolbar-button-disabled');
}
var skipButton = goog.dom.getElement('bite-tests-toolbar-button-skip');
if (this.test_ && skipButton) {
this.eventHandler_.listen(skipButton, goog.events.EventType.CLICK,
goog.bind(this.confirmAction_, this,
Bite.Constants.TestResult.SKIP));
} else if (skipButton) {
goog.dom.classes.swap(skipButton, 'bite-toolbar-button',
'bite-toolbar-button-disabled');
}
var newBugButton = goog.dom.getElement('bite-tests-toolbar-button-new-bug');
if (newBugButton) {
this.eventHandler_.listen(newBugButton, goog.events.EventType.CLICK,
goog.bind(this.startNewBugHandler_, this));
}
};
/**
* Handles starting a new bug.
* @private
*/
bite.client.TestsConsole.prototype.startNewBugHandler_ = function() {
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.START_NEW_BUG});
};
/**
* Called to show the confirmation screen to the user.
* @param {Bite.Constants.TestResult} result Test result.
* @private
*/
bite.client.TestsConsole.prototype.confirmAction_ = function(result) {
var messageDiv = goog.dom.createDom('div');
if (result == Bite.Constants.TestResult.PASS ||
result == Bite.Constants.TestResult.FAIL) {
messageDiv.innerHTML = '<b>Confirm Test Results:' +
'</b><br><b>URL</b>: ' + this.test_['test_url'];
if (result == Bite.Constants.TestResult.PASS) {
messageDiv.innerHTML += '<br><b>Result:</b>' +
'<span style="color:green; margin: 4px"> PASS</span><br>';
} else {
messageDiv.innerHTML += '<br><b>Result:</b><span style="color:' +
'red; margin: 4px"> FAIL</span><br>';
var bugsArea = goog.dom.createDom(
goog.dom.TagName.DIV, {'style': 'display:block'});
goog.dom.appendChild(bugsArea, goog.dom.createDom(
goog.dom.TagName.LABEL, {'for': 'failure_bugs'},
goog.dom.createTextNode('Bug Ids (eg: 1245, 1223): ')));
goog.dom.appendChild(bugsArea, goog.dom.createDom(
goog.dom.TagName.INPUT,
{'type': 'text', 'id': 'failure_bugs', 'style': 'display:block'}));
var commentArea = goog.dom.createDom(
goog.dom.TagName.DIV, {'style': 'display:block'});
goog.dom.appendChild(commentArea, goog.dom.createDom(
goog.dom.TagName.LABEL, {'for': 'failure_comment'},
goog.dom.createTextNode(
'Comments (eg: fails on first load only): ')));
goog.dom.appendChild(commentArea, goog.dom.createDom(
goog.dom.TagName.TEXTAREA,
{'id': 'failure_comment', 'style': 'display:block'}));
goog.dom.appendChild(messageDiv, bugsArea);
goog.dom.appendChild(messageDiv, commentArea);
}
} else if (result == Bite.Constants.TestResult.SKIP) {
messageDiv.innerHTML = '<b>Confirm skip test.<b>';
} else {
console.error('Unrecognized result: ' + result);
return;
}
messageDiv.appendChild(goog.dom.createDom(
goog.dom.TagName.INPUT,
{'type': 'button',
'value': 'Submit',
'onclick': goog.bind(this.logTestResult_, this, result)}));
messageDiv.appendChild(goog.dom.createDom(
goog.dom.TagName.INPUT,
{'type': 'button',
'value': 'Cancel',
'onclick': goog.bind(this.cancelAction_, this)}));
var contentCanvas = goog.dom.getElement('bite-tests-content-canvas');
contentCanvas.innerHTML = '';
contentCanvas.appendChild(messageDiv);
};
/**
* Cancels the action confirmation screen.
* @private
*/
bite.client.TestsConsole.prototype.cancelAction_ = function() {
this.requestUpdate_();
};
/**
* Logs the test result back to the server.
* @param {Bite.Constants.TestResult} result Test result.
* @private
*/
bite.client.TestsConsole.prototype.logTestResult_ = function(result) {
var params = {action: Bite.Constants.HUD_ACTION.LOG_TEST_RESULT,
result: result,
testId: this.test_['test_id']};
if (result == Bite.Constants.TestResult.FAIL) {
var comment = goog.dom.getElement('failure_comment').value;
var bugs = goog.dom.getElement('failure_bugs').value;
params['comment'] = comment;
params['bugs'] = bugs;
}
var contentCanvas = goog.dom.getElement('bite-tests-content-canvas');
contentCanvas.innerText = 'Submitting result, please wait...';
chrome.extension.sendRequest(params, this.requestUpdate_);
};
/**
* Requests that the background script update the test data for this tab.
* @private
*/
bite.client.TestsConsole.prototype.requestUpdate_ = function() {
chrome.extension.sendRequest({action: Bite.Constants.HUD_ACTION.UPDATE_DATA});
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the popup JS which opens the console.
* @author michaelwill@google.com (Michael Williamson)
*/
goog.provide('bite.Popup');
goog.require('Bite.Constants');
goog.require('bite.client.Templates.popup');
goog.require('bite.client.messages');
goog.require('bite.common.net.xhr.async');
goog.require('bite.options.constants');
goog.require('bite.options.data');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.json');
goog.require('goog.string');
goog.require('goog.ui.ToggleButton');
/**
* Constructs a singleton popup instance.
* Note that init() must be called on the instance
* before it's usable.
* @constructor
* @export
*/
bite.Popup = function() {
/**
* Records the extension version.
* @type {string}
* @private
*/
this.browserVersion_ = 'NaN';
/**
* This value will be true when the asynchronous initialization has finished.
* @type {boolean}
* @private
*/
this.initComplete_ = false;
/**
* The user id.
* @type {string}
* @private
*/
this.userId_ = '';
/**
* The last error message recorded. This is only valid if initComplete_ is
* false.
* @type {string}
* @private
*/
this.lastError_ = 'Not initialized.';
};
goog.addSingletonGetter(bite.Popup);
/**
* Css class used by each menu item.
* @type {string}
* @private
*/
bite.Popup.POPUP_ITEM_ROW_CLASS_ = 'menuitem-row';
/**
* Each of these options is displayed in the
* bite popup, and each should have a corresponding
* entry in the onclick handler below.
* @type {Object}
* @private
*/
bite.Popup.CONSOLE_OPTIONS_ = {
FLUX: {
name: MSG_POPUP_OPTION_FLUX_NAME,
img: '/imgs/popup/rpf_32.png',
description: MSG_POPUP_OPTION_FLUX_DESC
},
REPORT_BUG: {
name: MSG_POPUP_OPTION_REPORT_BUG_NAME,
img: '/imgs/popup/new_bug_32.png',
description: MSG_POPUP_OPTION_REPORT_BUG_DESC
},
BUGS: {
name: MSG_POPUP_OPTION_BUGS_NAME,
img: '/imgs/popup/bugs_32.png',
description: MSG_POPUP_OPTION_BUGS_DESC
},
TESTS: {
name: MSG_POPUP_OPTION_TEST_NAME,
img: '/imgs/popup/tests_32.png',
description: MSG_POPUP_OPTION_TEST_DESC
},
// TODO(ralphj): Make a dedicated close image.
CLOSE: {
name: MSG_POPUP_OPTION_CLOSE_NAME,
img: '/imgs/bug-unknown-32.png',
description: MSG_POPUP_OPTION_CLOSE_DESC
},
SETTINGS: {
name: MSG_POPUP_OPTION_SETTINGS_NAME,
img: '/imgs/popup/help_32.png',
description: MSG_POPUP_OPTION_SETTINGS_DESC
}
};
/**
* Installs onclick event handlers on each menu item.
* @private
*/
bite.Popup.prototype.installEventHandlers_ = function() {
var menuElements = goog.dom.getElementsByTagNameAndClass(
'tr', bite.Popup.POPUP_ITEM_ROW_CLASS_);
for (var i = 0; i < menuElements.length; i++) {
var el = menuElements[i];
var optionName = el.title;
goog.events.listen(el, goog.events.EventType.CLICK,
goog.bind(this.onClickCallback_, this, optionName));
}
};
/**
* Returns the initialization status.
* @return {boolean} Whether or not initialization has finished.
* @export
*/
bite.Popup.prototype.getInitComplete = function() {
return this.initComplete_;
};
/**
* Return the last recorded error message for this object.
* @return {string} The last recorded error message or an empty string if there
* is no valid error.
* @export
*/
bite.Popup.prototype.getLastError = function() {
return this.lastError_;
};
/**
* Returns the version of the currently installed extension.
* @return {string} The version of the extension.
* @export
*/
bite.Popup.prototype.getVersion = function() {
return this.browserVersion_;
};
/**
* Initializes the popup instance by checking the login status
* of the user and rendering the appropriate soy template.
* @param {function()=} opt_initCallback An optional callback
* that is invoked when initialization is finished.
* @export
*/
bite.Popup.prototype.init = function(opt_initCallback) {
var callback = opt_initCallback || goog.nullFunction;
if (this.initComplete_) {
callback();
return;
}
var body = goog.dom.getDocument().body;
soy.renderElement(body, bite.client.Templates.popup.loading);
this.initData_(/** @type {function(boolean, string, number)} */ (callback));
};
/**
* Initializes data necessary for the functioning of this object.
* @param {function(boolean, string, number)} callback The callback to invoke
* when initialization is complete.
* @private
*/
bite.Popup.prototype.initData_ = function(callback) {
var url = chrome.extension.getURL('manifest.json');
console.log('initData_: url='+url);
bite.common.net.xhr.async.get(url,
goog.bind(this.initDataComplete_, this, callback));
};
/**
* Async callback that gathers data before the final rendering of the popup.
* @param {function()} callback The callback to invoke when initialization
* is complete.
* @param {boolean} success Whether or not the request was successful.
* @param {string} data The data retrieved from the request or an error string.
* @private
*/
bite.Popup.prototype.initDataComplete_ = function(callback, success, data) {
try {
if (!success) {
throw data;
}
var manifest = goog.json.parse(data);
this.browserVersion_ = manifest['version'];
} catch (error) {
this.browserVersion_ = '';
console.error('Popup [initDataComplete_]: Failed retrieval of version; ' +
'setting to "unknown" and continuing.');
}
this.initLogin_(callback);
};
/**
* Performs the login initialization process.
* @param {function()} callback The callback to invoke when initialization
* is complete.
* @private
*/
bite.Popup.prototype.initLogin_ = function(callback) {
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_CURRENT_USER},
goog.bind(this.initLoginComplete_, this, callback));
};
/**
* Async callback used when the user login status request has finished.
* @param {function()} callback The callback to invoke when initialization
* is complete.
* @param {{success: boolean, username: string, url: string}} responseObj
* An object that contains the login
* or logout url and optionally the username of the user.
* @private
*/
bite.Popup.prototype.initLoginComplete_ = function(callback, responseObj) {
// Should only occur if LoginManager fails.
if (!responseObj) {
console.error('Popup [initLoginComplete_]: LoginManager failed to ' +
'provide a valid response.');
responseObj = {'success': false, 'username': '', 'url': ''};
}
var consoleOptions = [];
// Only display console options if logged in.
if (responseObj['success']) {
// Flatten the object into an array.
// Alias for bite.options.data namespace
var data = bite.options.data;
for (var key in bite.Popup.CONSOLE_OPTIONS_) {
var display = false;
switch (key) {
case 'BUGS':
if (data.get(bite.options.constants.Id.FEATURES_BUGS) == 'true') {
display = true;
}
break;
case 'FLUX':
if (data.get(bite.options.constants.Id.FEATURES_RPF) == 'true') {
display = true;
}
break;
case 'TESTS':
if (data.get(bite.options.constants.Id.FEATURES_TESTS) == 'true') {
display = true;
}
break;
case 'REPORT_BUG':
if (data.get(bite.options.constants.Id.FEATURES_REPORT) == 'true') {
display = true;
}
break;
case 'CLOSE':
if (data.get(bite.options.constants.Id.FEATURES_CLOSE) == 'true') {
display = true;
}
break;
default:
display = true;
}
if (display) {
consoleOptions.push(bite.Popup.CONSOLE_OPTIONS_[key]);
}
}
}
var body = goog.dom.getDocument().body;
soy.renderElement(body, bite.client.Templates.popup.all, {
version: this.getVersion(),
username: responseObj['username'],
consoleOptions: consoleOptions,
url: responseObj['url']
});
this.installEventHandlers_();
this.initComplete_ = true;
// TODO (jaosn.stredwick): Remove cast to 'unknown user'. It is legacy
// for RPF code. Instead RPF should be converted to get the user itself
// directly rather than from the popup.
this.userId_ = responseObj['username'] || 'unknown user';
callback();
};
/**
* A callback used when the popup menu is clicked on.
* @param {string} optionName The name of the option that was clicked on.
* @private
*/
bite.Popup.prototype.onClickCallback_ = function(optionName) {
switch (optionName) {
case bite.Popup.CONSOLE_OPTIONS_.REPORT_BUG.name:
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.START_NEW_BUG});
break;
case bite.Popup.CONSOLE_OPTIONS_.BUGS.name:
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.TOGGLE_BUGS});
break;
case bite.Popup.CONSOLE_OPTIONS_.TESTS.name:
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.TOGGLE_TESTS});
break;
case bite.Popup.CONSOLE_OPTIONS_.CLOSE.name:
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.HIDE_ALL_CONSOLES});
break;
case bite.Popup.CONSOLE_OPTIONS_.FLUX.name:
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.CREATE_RPF_WINDOW,
'userId': this.userId_});
break;
case bite.Popup.CONSOLE_OPTIONS_.SETTINGS.name:
chrome.tabs.create({'url': Bite.Constants.getOptionsPageUrl()});
break;
default:
// TODO (jasonstredwick): Examine throw as I suspect that this callback
// is only invoked from DOM Element interaction which means that
// catching this exception is outside of BITE's ability as it should be
// in the global scope.
throw Error('Not a valid popup option: ' + optionName);
}
goog.global.close();
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the code on the Options script file.
*
* @author michaelwill@google.com (Michael Williamson)
*/
goog.require('Bite.Constants');
goog.require('bite.Popup');
goog.require('goog.json');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.net.XhrIo');
goog.require('goog.testing.recordFunction');
goog.require('rpf.Rpf');
var mocks = null;
var stubs = null;
var popup = null;
var mockBackground = null;
function setUp() {
initChrome();
mocks = new goog.testing.MockControl();
stubs = new goog.testing.PropertyReplacer();
var mockLocalStorage = {getItem: function() {return 'http://hud.test'}};
stubs.set(goog.global, 'localStorage', mockLocalStorage);
popup = new bite.Popup();
}
function tearDown() {
stubs.reset();
mocks.$tearDown();
}
function testOnClickCallback_bugs() {
var option = bite.Popup.CONSOLE_OPTIONS_.BUGS.name;
popup.onClickCallback_(option);
var lastRequestObj = chrome.extension.lastRequest;
assertEquals(Bite.Constants.HUD_ACTION.TOGGLE_BUGS,
lastRequestObj.action);
}
function testOnClickCallback_tests() {
var option = bite.Popup.CONSOLE_OPTIONS_.TESTS.name;
popup.onClickCallback_(option);
var lastRequestObj = chrome.extension.lastRequest;
assertEquals(Bite.Constants.HUD_ACTION.TOGGLE_TESTS,
lastRequestObj.action);
}
function testOnClickCallback_rpf() {
var option = bite.Popup.CONSOLE_OPTIONS_.FLUX.name;
var rpfInstance = mocks.createStrictMock(rpf.Rpf);
mocks.$replayAll();
popup.onClickCallback_(option);
mocks.$verifyAll();
var lastRequestObj = chrome.extension.lastRequest;
assertEquals(Bite.Constants.HUD_ACTION.CREATE_RPF_WINDOW,
lastRequestObj.action);
}
function testOnClickCallback_options() {
var option = bite.Popup.CONSOLE_OPTIONS_.SETTINGS.name;
popup.onClickCallback_(option);
assertContains('options', chrome.tabs.createdTabUrl);
}
function testOnClickCallback_exception() {
try {
popup.onClickCallback_('blalsdjf');
} catch (e) {
return;
}
fail('Should have thrown an error!');
}
function testInitLoginComplete() {
var callbackRecord = goog.testing.recordFunction();
var success = true;
var url = 'loginOrOut';
var username = 'michaelwill';
var responseObj = {
'success': success,
'url': url,
'username': username
};
var soyRecord = goog.testing.recordFunction();
stubs.set(soy, 'renderElement', soyRecord);
var myVersion = 'myversion';
stubs.set(popup, 'getVersion', function() { return myVersion; });
// Going to ignore case where parse throws and exception. Testing onFailure_
// as a separate test.
popup.initLoginComplete_(callbackRecord, responseObj);
assertEquals(1, soyRecord.getCallCount());
var soyData = soyRecord.getLastCall().getArguments()[2];
assertEquals(myVersion, soyData.version);
assertEquals(username, soyData.username);
assertEquals(url, soyData.url);
assertEquals(1, callbackRecord.getCallCount());
assertTrue(popup.getInitComplete());
}
function testOnFailure_Error() {
var callbackRecord = goog.testing.recordFunction();
var error = 'error';
var soyRecord = goog.testing.recordFunction();
stubs.set(soy, 'renderElement', soyRecord);
popup.onFailure_(error, callbackRecord);
assertFalse(popup.getInitComplete());
assertEquals(error, popup.getLastError());
assertEquals(1, soyRecord.getCallCount());
var soyData = soyRecord.getLastCall().getArguments()[2];
assertNotNull(soyData['message']);
assertEquals(1, callbackRecord.getCallCount());
}
function testInitDataComplete() {
var mockCallback = mocks.createFunctionMock();
var mockParse = mocks.createFunctionMock();
mockParse('data').$returns({'version': 'a'});
stubs.set(goog.json, 'parse', mockParse);
var mockInitLogin = mocks.createFunctionMock();
mockInitLogin(mockCallback).$returns();
stubs.set(bite.Popup.prototype, 'initLogin_', mockInitLogin);
mocks.$replayAll();
// Going to ignore case where parse throws and exception. Testing onFailure_
// as a separate test.
popup.initDataComplete_(mockCallback, true, 'data');
mocks.$verifyAll();
assertEquals('a', popup.getVersion());
}
function testInit() {
var callbackRecord = goog.testing.recordFunction();
var soyRecorder = goog.testing.recordFunction();
stubs.set(soy, 'renderElement', soyRecorder);
var mockInitData = mocks.createFunctionMock();
mockInitData(callbackRecord).$returns();
stubs.set(bite.Popup.prototype, 'initData_', mockInitData);
mocks.$replayAll();
popup.init(callbackRecord);
popup.initComplete_ = true;
popup.init(callbackRecord);
mocks.$verifyAll();
assertEquals(1, soyRecorder.getCallCount());
assertEquals(1, callbackRecord.getCallCount());
}
function testInstallEventHandlers() {
var clickCallbackRecorder = goog.testing.recordFunction();
stubs.set(popup, 'onClickCallback_', clickCallbackRecorder);
popup.installEventHandlers_();
var clickEvent = new goog.events.Event(goog.events.EventType.CLICK);
// Try with the first element.
var rowElement = goog.dom.getElementsByTagNameAndClass(
'tr', bite.Popup.POPUP_ITEM_ROW_CLASS_)[0];
goog.events.fireListeners(rowElement, goog.events.EventType.CLICK,
false, clickEvent);
assertEquals(1, clickCallbackRecorder.getCallCount());
var args = clickCallbackRecorder.getLastCall().getArguments();
assertEquals('item1', args[0]);
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the Maps Helper.
*
* @author ralphj@google.com (Julie Ralph)
*/
/**
* Testing bite.client.MapsHelper.isMapsUrl.
* @this The context of the unit test.
*/
function testIsMapsUrl() {
assertEquals(true,
bite.client.MapsHelper.isMapsUrl('http://maps.google.com'));
assertEquals(true,
bite.client.MapsHelper.isMapsUrl(
'http://maps.google.com/?ie=UTF8&spn=34.808514,74.443359&z=4'));
assertEquals(false,
bite.client.MapsHelper.isMapsUrl('http://google.com'));
assertEquals(false,
bite.client.MapsHelper.isMapsUrl('http://maps.mail.com'));
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the NewBug element selector.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.require('bite.client.ElementSelector');
goog.require('common.client.RecordModeManager');
var element = null;
var mockCaller = null;
var elementSelector = null;
/**
* Stores the element returned by the element selector.
* @constructor
* @export
*/
mockCallBack = function() {
/**
* The element that was returned.
* @type {Element}
*/
this.element = null;
};
/**
* Sets the element of the mockCallBack.
* @param {Element} element The element to store.
*/
mockCallBack.prototype.callback = function(element) {
this.element = element;
};
function setUp() {
initChrome();
element = goog.dom.createDom(
goog.dom.TagName.DIV,
{'id': 'test-element',
'style': 'position:fixed;top:0;left:0;width:50px;height:50px'});
goog.dom.appendChild(goog.dom.getDocument().body, element);
mockCaller = new mockCallBack();
elementSelector = new bite.client.ElementSelector();
}
function tearDown() {
goog.dom.removeNode(element);
element = null;
mockCaller = null;
elementSelector = null;
goog.events.removeAll();
}
function testClickElement() {
elementSelector.startRecording(
goog.bind(mockCaller.callback, mockCaller));
assertTrue(elementSelector.isActive());
elementSelector.recordModeManager_.currElement_ = element;
elementSelector.recordModeManager_.clickOverride_();
assertEquals(element.id, mockCaller.element.id);
}
function testCancel() {
elementSelector.startRecording(
goog.bind(mockCaller.callback, mockCaller));
elementSelector.cancelSelection();
assertFalse(elementSelector.isActive());
assertNull(mockCaller.element);
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.mvc.helper.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.mvc.helper');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.query');
function setUp() {}
function tearDown() {}
/**
* Test bite.common.mvc.helper.bulkGetElementById
*/
function testBulkGetElementById() {
var body = goog.dom.getDocument().body;
var x = goog.dom.createElement(goog.dom.TagName.DIV);
var y = goog.dom.createElement(goog.dom.TagName.DIV);
var z = goog.dom.createElement(goog.dom.TagName.DIV);
x.id = 'x';
y.id = 'y';
z.id = 'z';
goog.dom.appendChild(body, x);
goog.dom.appendChild(body, y);
goog.dom.appendChild(body, z);
var obj = {
'x': undefined,
'y': undefined,
'z': undefined
};
// Test find with src element.
assertTrue(bite.common.mvc.helper.bulkGetElementById(obj, body));
assertFalse(goog.isNull(obj.x) || goog.isNull(obj.y) || goog.isNull(obj.z));
obj.x = undefined;
obj.y = undefined;
obj.z = undefined;
// Test find without src element.
assertTrue(bite.common.mvc.helper.bulkGetElementById(obj));
assertFalse(goog.isNull(obj.x) || goog.isNull(obj.y) || goog.isNull(obj.z));
obj.x = undefined;
obj.y = undefined;
obj.z = undefined;
// Test find with missing id.
obj['a'] = undefined;
assertFalse(bite.common.mvc.helper.bulkGetElementById(obj));
assertTrue(goog.isNull(obj.a));
// Clean up
goog.dom.removeNode(x);
goog.dom.removeNode(y);
goog.dom.removeNode(z);
}
/**
* Test bite.common.mvc.helper.getElement.
*/
function testGetElement() {
var body = goog.dom.getDocument().body;
var x = goog.dom.createElement(goog.dom.TagName.DIV);
x.id = 'x';
x.innerHTML = '<div id="y"><div id="z"></div></div>';
goog.dom.appendChild(body, x);
var element = bite.common.mvc.helper.getElement('y', goog.dom.getDocument());
assertNotNull(element);
assertEquals('y', element.id);
element = bite.common.mvc.helper.getElement('z', x);
assertNotNull(element);
assertEquals('z', element.id);
// Clean up
goog.dom.removeNode(x);
}
/**
* Test bite.common.mvc.helper.initModel
*/
function testInitModel() {
var body = goog.dom.getDocument().body;
var modelFunc = function(data) {
return '<div id="' + data['name'] + '"></div>';
}
var data = [{'name': 'e1'}, {'name': 'e2'}, {'name': 'e3'}];
for (i = 0, len = data.length; i < len; ++i) {
bite.common.mvc.helper.initModel(modelFunc, data[i]);
}
var elements = [];
for (i = 0, j = data.length - 1, len = body.childNodes.length;
i < len && j >= 0; ++i, --j) {
assertEquals(data[j]['name'], body.childNodes[i].id);
elements.push(body.childNodes[i]);
}
// Clean up
for (i = 0, len = elements.length; i < len; ++i) {
goog.dom.removeNode(elements[i]);
}
}
/**
* Test bite.common.mvc.helper.initView.
*/
function testInitView() {
var func = function(data) {
return '<div id="init-view-test">' + (data['baseUrl'] || 'empty') +
'</div>';
};
// Test with url
var query = goog.dom.query('[id="init-view-test"]');
assertEquals(0, query.length);
assertTrue(bite.common.mvc.helper.initView(func, 'testurl'));
query = goog.dom.query('[id="init-view-test"]');
assertEquals(1, query.length);
assertEquals('testurl', query[0].innerHTML);
goog.dom.removeNode(query[0]);
query = goog.dom.query('[id="init-view-test"]');
assertEquals(0, query.length);
// Test with no url
assertTrue(bite.common.mvc.helper.initView(func));
query = goog.dom.query('[id="init-view-test"]');
assertEquals(1, query.length);
assertEquals('empty', query[0].innerHTML);
goog.dom.removeNode(query[0]);
query = goog.dom.query('[id="init-view-test"]');
assertEquals(0, query.length);
}
/**
* Test bite.common.mvc.helper.removeElementById
*/
function testRemoveElementById() {
var body = goog.dom.getDocument().body;
// Remove with no matching id.
try {
bite.common.mvc.helper.removeElementById('fail');
} catch (error) {
fail(error);
}
var x = goog.dom.createElement(goog.dom.TagName.DIV);
var y = goog.dom.createElement(goog.dom.TagName.DIV);
var z = goog.dom.createElement(goog.dom.TagName.DIV);
x.id = 'x';
y.id = 'x';
z.id = 'x';
// Remove single instance of an element with the given id.
goog.dom.appendChild(body, x);
var query = goog.dom.query('[id="x"]');
assertEquals(1, query.length);
bite.common.mvc.helper.removeElementById('x');
query = goog.dom.query('[id="x"]');
assertEquals(0, query.length);
// Remove multiple instances of an element with the given id.
goog.dom.appendChild(body, x);
goog.dom.appendChild(body, y);
goog.dom.appendChild(body, z);
var query = goog.dom.query('[id="x"]');
assertEquals(3, query.length);
bite.common.mvc.helper.removeElementById('x');
query = goog.dom.query('[id="x"]');
assertEquals(0, query.length);
}
/**
* Test bite.common.mvc.helper.validateName
*/
function testValidateName() {
var name = '';
// Test empty string
assertFalse(bite.common.mvc.helper.validateName(name));
// Test bad values
name = '_';
assertFalse(bite.common.mvc.helper.validateName(name));
name = '_a';
assertFalse(bite.common.mvc.helper.validateName(name));
name = '1';
assertFalse(bite.common.mvc.helper.validateName(name));
name = '1a';
assertFalse(bite.common.mvc.helper.validateName(name));
name = 'a b';
assertFalse(bite.common.mvc.helper.validateName(name));
name = 'a.txt';
assertFalse(bite.common.mvc.helper.validateName(name));
// Test valid values
name = 'a';
assertTrue(bite.common.mvc.helper.validateName(name));
name = 'a1_';
assertTrue(bite.common.mvc.helper.validateName(name));
name = 'a_1';
assertTrue(bite.common.mvc.helper.validateName(name));
name = 'very_long_name';
assertTrue(bite.common.mvc.helper.validateName(name));
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define the helper functions for MVCs (Model/View/Controls).
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.mvc.helper');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.query');
goog.require('soy');
/**
* Takes an object whose keys are element ids, looks up each element, and
* sets the key's value in the object to that element or null if the element
* was not found or there was more than one. Returns false if an element was
* assigned null. It also assumes that each id is unique in the opt_srcElement
* (defaults to the document if not given).
*
* Note that goog.dom.query is used instead of goog.dom.getElement because
* getElement assumes the elements are already part of the document. Query
* can search relative to an element even if it is not in the document. Plus
* it is a targeted search rather than over the whole document.
* @param {Object.<string, Element>} inout_idToElementMap An object containing
* an element id. This function will look up the element by id and
* set the object's value to that element. If the element is not found
* or there is more than one then null is assigned as the value.
* @param {!Element=} opt_srcElement The opt_srcElement to use when looking up
* the id. If an element is not given then the document will be used.
* @return {boolean} Whether or not all the ids were found.
*/
bite.common.mvc.helper.bulkGetElementById = function(inout_idToElementMap,
opt_srcElement) {
var src = opt_srcElement || goog.dom.getDocument();
// srcId will only be assigned if src is an Element thus guaranteeing that
// only elements are returned by this function.
var srcId = 'id' in src && opt_srcElement ? src['id'] : '';
var success = true;
for (var elementId in inout_idToElementMap) {
if (srcId && elementId == srcId) {
inout_idToElementMap[elementId] = /** @type {Element} */ (src);
continue;
}
var id = '[id="' + elementId + '"]';
var query = goog.dom.query(id, src);
if (query.length != 1) {
inout_idToElementMap[elementId] = null;
success = false;
continue;
}
inout_idToElementMap[elementId] = query[0];
}
return success;
};
/**
* Takes an id and a source element and retrieves the element with that id.
* The intent is to provide the same general functionality as
* goog.dom.getElement(), but to allow a targeted search rather than searching
* the entire document for an element.
* @param {string} id The element id to search for.
* @param {!Element} srcElement The element from which to start the search.
* @return {Element} Return either the element or null. Null will also be
* returned in multiple elements with the same id are found.
*/
bite.common.mvc.helper.getElement = function(id, srcElement) {
var query = goog.dom.query('[id="' + id + '"]', srcElement);
if (query.length != 1) {
return null;
}
return query[0];
};
/**
* Creates the model and adds it to the document's body.
* @param {function((Object|null|undefined),
* (goog.string.StringBuffer|null|undefined)):
* (string|undefined)} getModelFunc The soy template function
* that creates the console's model.
* @param {Object.<string>=} opt_data Optional data that can be passed to the
* template function.
* @return {Element} Return the element or null on failure.
*/
bite.common.mvc.helper.initModel = function(getModelFunc, opt_data) {
var element = bite.common.mvc.helper.renderModel(getModelFunc, opt_data);
if (!element) {
return null;
}
var body = goog.dom.getDocument().body;
// Note that goog.dom.getFirstElementChild does not recognize certain node
// types such as #text nodes. So manually get first child.
var child = body.firstChild || null;
if (!child) {
goog.dom.appendChild(body, element);
} else {
goog.dom.insertSiblingBefore(element, child);
}
return element;
};
/**
* Adds the view to the document by appending a link tag with the appropriate
* css url to the head of the document.
* @param {function((Object|null|undefined),
* (goog.string.StringBuffer|null|undefined)):
* (string|undefined)} getViewFunc The soy template function
* that creates a link tag to the appropriate css.
* @param {string=} opt_baseUrl The base url to use for relative references.
* @return {boolean} Whether or not the procedure was a success.
*/
bite.common.mvc.helper.initView = function(getViewFunc, opt_baseUrl) {
opt_baseUrl = opt_baseUrl || '';
// Prepare style tag and get first head element.
var style = soy.renderAsElement(getViewFunc, {'baseUrl': opt_baseUrl});
var headResults = goog.dom.getElementsByTagNameAndClass(
goog.dom.TagName.HEAD);
if (!style || !headResults.length) {
return false;
}
var head = headResults[0];
goog.dom.appendChild(head, style);
return true;
};
/**
* Removes all element instances with the given id.
* @param {string} id The element id to search for.
*/
bite.common.mvc.helper.removeElementById = function(id) {
id = '[id="' + id + '"]';
var query = goog.dom.query(id);
// Not assuming that the query results is a live/dynamic node list versus
// a static one, so copy references before removing them from the document.
var element = [];
for (var i = 0, len = query.length; i < len; ++i) {
element.push(query[i]);
}
for (var i = 0, len = element.length; i < len; ++i) {
goog.dom.removeNode(element[i]);
}
};
/**
* Generate an element using a soy template.
* @param {function((Object|null|undefined),
* (goog.string.StringBuffer|null|undefined)):
* (string|undefined)} getModelFunc The soy template function
* that creates the console's model.
* @param {Object.<string>=} opt_data Optional data that can be passed to the
* template function.
* @return {Element} Return the element or null on failure.
*/
bite.common.mvc.helper.renderModel = function(getModelFunc, opt_data) {
var element = soy.renderAsElement(getModelFunc, opt_data);
if (!element) {
return null;
}
return element;
};
/**
* Generate an element using a soy template and the specified tag.
* @param {string} tag The tag name of the created element.
* @param {function((Object|null|undefined),
* (goog.string.StringBuffer|null|undefined)):
* (string|undefined)} getModelFunc The soy template function
* that creates the console's model.
* @param {Object.<string>=} opt_data Optional data that can be passed to the
* template function.
* @return {Element} Return the element or null on failure.
*/
bite.common.mvc.helper.renderModelAs = function(tag, getModelFunc, opt_data) {
var element = goog.dom.createElement(tag);
if (!element) {
return null;
}
soy.renderElement(element, getModelFunc, opt_data);
return element;
};
/**
* Modify the given element's innerHTML to the string returned by the soy
* template.
* @param {Element} element The element to add the model to.
* @param {function((Object|null|undefined),
* (goog.string.StringBuffer|null|undefined)):
* (string|undefined)} getModelFunc The soy template function
* that creates the console's model.
* @param {Object.<string>=} opt_data Optional data that can be passed to the
* template function.
* @return {boolean} Whether or not success occurred.
*/
bite.common.mvc.helper.renderModelFor = function(element, getModelFunc,
opt_data) {
if (!element) {
return false;
}
soy.renderElement(element, getModelFunc, opt_data);
return true;
};
/**
* Validates a specific kind of name that has a limited character set. The
* names follow the rules such that it must begin with a letter and then
* can contain any letter, number, or underscore. This is useful for naming
* things such as project labels, files, test names, etc.
* TODO (jasonstredwick): This function probably does not belong here.
* examine its usefulness and move it where appropriate.
* TODO (jasonstredwick): This function does not take into account non-ascii
* names. Consider making a string helper that handles these types of
* externally facing, user entered names.
* @param {string} name The name to validate.
* @return {boolean} Whether or not the name input value is valid.
*/
bite.common.mvc.helper.validateName = function(name) {
return /^[a-zA-Z][a-zA-Z0-9_]*$/.test(name);
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview BITE constants.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('Bite.Constants');
/**
* Enum for result values.
* @enum {string}
*/
Bite.Constants.WorkerResults = {
FAILED: 'failed',
PASS: 'passed',
STOPPED: 'stop'
};
/**
* The default function name for getting element's descriptor.
* @const
* @type {string}
*/
Bite.Constants.FUNCTION_PARSE_DESCRIPTOR = 'parseElementDescriptor';
/**
* A list of URLs which should trigger automatic recording.
* @const
* @type {Array.<string>}
*/
Bite.Constants.AUTO_RECORD_URLS = [
'maps.google.com'
];
/**
* Enum of the commands for controlling rpf components.
* @enum {string}
*/
Bite.Constants.CONTROL_CMDS = {
CREATE_WINDOW: 'createWindow',
OPEN_CONSOLE_AUTO_RECORD: 'openConsoleAutoRecord',
REMOVE_WINDOW: 'removeWindow',
SET_WORKER_TOKEN: 'setWorkerToken',
SET_WORKER_URL: 'setWorkerUrl',
START_WORKER_MODE: 'startWorkerMode',
STOP_WORKER_MODE: 'stopWorkerMode'
};
/**
* Enum of the event types when a step is completed.
* @enum {string}
*/
Bite.Constants.COMPLETED_EVENT_TYPES = {
AUTOMATE_SAVE_DIALOG: 'automateSaveDialog',
DEFAULT: '',
FAILED: 'failed',
FINISHED_CURRENT_RUN: 'finishedCurrentRun',
FINISHED_LOAD_TEST_IN_CONSOLE: 'finishedLoadTestInConsole',
FINISHED_RUNNING_TEST: 'finishedRunningTest',
FINISHED_UPDATE_TEST_RESULT: 'finishedUpdateTestResult',
HIGHLIGHTED_LINE: 'highlightedLine',
LINE_HIGHLIGHTED: 'lineHighlighted',
LOCAL_PROJECT_LOADED: 'localProjectLoaded',
PLAYBACK_DIALOG_OPENED: 'playbackDialogOpened',
PLAYBACK_STARTED: 'playbackStarted',
PROJECT_LOADED: 'projectLoaded',
PROJECT_SAVED_LOCALLY: 'projectSavedLocally',
RUN_PLAYBACK_COMPLETE: 'runPlaybackComplete',
RUN_PLAYBACK_STARTED: 'runPlaybackStarted',
STOPPED_GROUP_TESTS: 'stoppedGroupTests',
TEST_LOADED: 'testLoaded',
PROJECT_LOADED_IN_EXPORT: 'projectLoadedInExport',
TEST_SAVED: 'testSaved',
RPF_CONSOLE_OPENED: 'rpfConsoleOpened'
};
/**
* Enum of the commands between rpf console and background world.
* @enum {string}
*/
Bite.Constants.CONSOLE_CMDS = {
AUTOMATE_RPF: 'automateRpf',
CALLBACK_AFTER_EXEC_CMDS: 'callBackAfterExecCmds',
CHECK_PLAYBACK_OPTION_AND_RUN: 'checkPlaybackOptionAndRun',
CHECK_READY_TO_RECORD: 'checkReadyToRecord',
CLOSE_CURRENT_TAB: 'closeCurrentTab',
DELETE_CMD: 'deleteCommand',
DELETE_TEST_LOCAL: 'deleteTestLocal',
DELETE_TEST_ON_WTF: 'deleteTestOnWTF',
END_UPDATER_MODE: 'endUpdaterMode',
ENTER_UPDATER_MODE: 'enterUpdaterMode',
EVENT_COMPLETED: 'eventCompleted',
EXECUTE_SCRIPT_IN_RECORD_PAGE: 'executeScriptInRecordPage',
FETCH_DATA_FROM_BACKGROUND: 'fetchDataFromBackground',
FINISH_CURRENT_RUN: 'finishCurrentRun',
GENERATE_NEW_COMMAND: 'generateNewCommand',
GET_ALL_FROM_WEB: 'getAllFromWeb',
GET_HELPER_NAMES: 'getHelperNames',
GET_LAST_MATCH_HTML: 'getLastMatchHtml',
GET_LOCAL_PROJECT: 'getLocalProject',
GET_LOGS_AS_STRING: 'getLogsAsString',
GET_JSON_FROM_WTF: 'getJsonFromWTF',
GET_JSON_LOCALLY: 'getJsonLocally',
GET_PROJECT: 'getProject',
GET_PROJECT_NAMES_FROM_LOCAL: 'getProjectNamesFromLocal',
GET_PROJECT_NAMES_FROM_WEB: 'getProjectNamesFromWeb',
GET_TEST_NAMES_LOCALLY: 'getTestNamesLocally',
INSERT_CMDS_WHILE_PLAYBACK: 'insertCmdsWhilePlayback',
LOAD_PROJECT_FROM_LOCAL_SERVER: 'loadProjectFromLocalServer',
OPEN_XPATH_FINDER: 'openXpathFinder',
PAGE_LOADED_COMPLETE: 'pageLoadedComplete',
PREPARE_RECORD_PLAYBACK_PAGE: 'prepareRecordPlaybackPage',
PREPARE_XPATH_FINDER: 'prepareXpathFinder',
RECORD_PAGE_LOADED_COMPLETE: 'recordPageLoadedComplete',
REFRESH_CODE_TREE: 'refreshCodeTree',
RUN_GROUP_TESTS: 'runGroupTests',
RUN_TEST: 'runTest',
SAVE_LOG_AND_HTML: 'saveLogAndHtml',
SAVE_JSON_LOCALLY: 'saveJsonLocally',
SAVE_PROJECT: 'saveProject',
SAVE_PROJECT_LOCALLY: 'saveProjectLocally',
SAVE_PROJECT_METADATA_LOCALLY: 'saveProjectMetadataLocally',
SAVE_ZIP: 'saveZip',
SET_ACTION_CALLBACK: 'setActionCallback',
SET_CONSOLE_TAB_ID: 'setConsoleTabId',
SET_DEFAULT_TIMEOUT: 'setDefaultTimeout',
SET_INFO_MAP_IN_PLAYBACK: 'setInfoMapInPlayback',
SET_MAXIMUM_RETRY_TIME: 'setMaximumRetryTime',
SET_PLAYBACK_INTERVAL: 'setPlaybackInterval',
SET_RECORDING_TAB: 'setRecordingTab',
SET_TAB_AND_START_RECORDING: 'setTabAndStartRecording',
SET_TAKE_SCREENSHOT: 'setTakeScreenshot',
SET_USE_XPATH: 'setUseXpath',
SET_USER_SPECIFIED_PAUSE_STEP: 'setUserSpecifiedPauseStep',
START_AUTO_RECORD: 'startAutoRecord',
START_RECORDING: 'startRecording',
STOP_GROUP_TESTS: 'stopGroupTests',
STOP_RECORDING: 'stopRecording',
TEST_LOCATOR: 'testLocator',
TEST_DESCRIPTOR: 'testDescriptor',
UPDATE_ON_WEB: 'updateOnWeb',
UPDATE_TEST_RESULT_ON_SERVER: 'updateTestResultOnServer',
USER_SET_PAUSE: 'userSetPause',
USER_SET_STOP: 'userSetStop'
};
/**
* Enum for playback methods.
* @enum {string}
*/
Bite.Constants.PlayMethods = {
ALL: 'all',
STEP: 'step'
};
/**
* Key codes used by BITE
* @enum {number}
*/
Bite.Constants.KeyCodes = {
B_KEY: 66
};
/**
* Urls used to control the Layer Manager.
* @enum {string}
*/
Bite.Constants.LayerUrl = {
DEFAULT_LAYER_LIST: '/layer/config/default_list',
STATIC_RESOURCES: '/layer/'
};
/**
* BITE lock, to ensure only one content script is running on a page.
*
* @type {string}
*/
Bite.Constants.BITE_CONSOLE_LOCK = 'biteConsoleLock';
/**
* Define common actions that everyone can use.
* @enum {string}
*/
Bite.Constants.Action = {
XHR_REQUEST: 'xhrRequest'
};
/**
* Enum of actions handled by the Background script.
* @enum {string}
*/
Bite.Constants.HUD_ACTION = {
CHANGE_RECORD_TAB: 'changeRecordTab',
CREATE_BUG: 'createBug',
CREATE_RPF_WINDOW: 'createRpfWindow',
ENSURE_CONTENT_SCRIPT_LOADED: 'ensureContentScriptLoaded',
FETCH_BUGS: 'fetchBugs',
FETCH_TEST_DATA: 'fetchTestData',
FETCH_BUGS_DATA: 'fetchBugsData',
GET_CURRENT_USER: 'getCurrentUser',
GET_LOCAL_STORAGE: 'getLocalStorage',
GET_RECORDING_LINK: 'getRecordingLink',
GET_SCREENSHOT: 'getScreenshot',
GET_SETTINGS: 'getSettings',
GET_SERVER_CHANNEL: 'getServerChannel',
GET_TEMPLATES: 'getTemplates',
HIDE_ALL_CONSOLES: 'hideAllConsoles',
HIDE_CONSOLE: 'hideConsole',
LOAD_CONTENT_SCRIPT: 'loadContentScript',
LOG_EVENT: 'logEvent',
LOG_TEST_RESULT: 'logTestResult',
REMOVE_LOCAL_STORAGE: 'resetLocalStorage',
SET_LOCAL_STORAGE: 'setLocalStorage',
START_NEW_BUG: 'startNewBug',
TOGGLE_BUGS: 'toggleBugs',
TOGGLE_TESTS: 'toggleTests',
UPDATE_BUG: 'updateBug',
UPDATE_DATA: 'updateData'
};
/**
* Bug binding actions.
* @enum {string}
*/
Bite.Constants.BugBindingActions = {
UPDATE: 'update',
CLEAR: 'clear'
};
/**
* Bug recording actions.
* @enum {string}
*/
Bite.Constants.BugRecordingActions = {
UPDATE: 'update'
};
/**
* Playback failure reasons.
* @enum {string}
*/
Bite.Constants.PlaybackFailures = {
MULTIPLE_RETRY_FIND_ELEM: 'MultipleRetryFindElemFailure',
MULTIPLE_RETRY_CUSTOM_JS: 'MultipleRetryCustomJsFailure',
TIMEOUT: 'TimeoutFailure',
UNSUPPORTED_COMMAND_FAILURE: 'UnsupportedCommandFailure',
USER_PAUSE_FAILURE: 'UserPauseFailure'
};
/**
* HUD console types.
* @enum {string}
*/
Bite.Constants.TestConsole = {
NONE: 'none',
BUGS: 'bugsConsole',
TESTS: 'testConsole',
NEWBUG: 'newBugConsole'
};
/**
* Test result types.
* @enum {string}
*/
Bite.Constants.TestResult = {
PASS: 'pass',
FAIL: 'fail',
SKIP: 'skip'
};
/**
* Bug DB Providers.
* @enum {string}
*/
Bite.Constants.Providers = {
DATASTORE: 'datastore',
ISSUETRACKER: 'issuetracker'
};
/**
* Returns the url of the options page.
* @return {string} The url.
*/
Bite.Constants.getOptionsPageUrl = function() {
return chrome.extension.getURL('options.html');
};
/**
* The test's own lib name.
* @type {string}
*/
Bite.Constants.TEST_LIB_NAME = 'This Test';
/**
* Enum for modes.
* @enum {string}
*/
Bite.Constants.ConsoleModes = {
DEFINE: 'define',
IDLE: 'idle',
PAUSE: 'pause',
PLAY: 'play',
RECORD: 'record',
UPDATER: 'updater',
VIEW: 'view',
WORKER: 'worker'
};
/**
* Enum for modes.
* @enum {string}
*/
Bite.Constants.ListenerDestination = {
CONSOLE: 'console',
EVENT_MANAGER: 'eventManager',
RPF: 'rpf',
CONTENT: 'content'
};
/**
* Enum for console events.
* @enum {string}
*/
Bite.Constants.UiCmds = {
// For main console.
ADD_COMMON_METHOD_DEPS: 'addCommonMethodDeps',
ADD_GENERATED_CMD: 'addGeneratedCmd',
ADD_NEW_COMMAND: 'addNewCommand',
ADD_NEW_TEST: 'addNewTest',
ADD_SCREENSHOT: 'addScreenShot',
CHANGE_MODE: 'changeMode',
CHECK_TAB_READY: 'checkTabReady',
CHECK_TAB_READY_TO_UPDATE: 'checkTabReadyToUpdate',
HIGHLIGHT_LINE: 'highlightLine',
LOAD_CMDS: 'loadCmds',
LOAD_TEST_FROM_LOCAL: 'loadTestFromLocal',
LOAD_TEST_FROM_WTF: 'loadTestFromWtf',
ON_CONSOLE_CLOSE: 'onConsoleClose',
ON_CONSOLE_REFRESH: 'onConsoleRefresh',
ON_KEY_DOWN: 'onKeyDown',
ON_KEY_UP: 'onKeyUp',
ON_SHOW_MORE_INFO: 'onShowMoreInfo',
ON_SHOW_MORE_OPTIONS: 'onShowMoreOptions',
OPEN_COMMON_METHODS_DEPS: 'openCommonMethodsDeps',
OPEN_GENERATE_INVOCATION: 'openGenerateInvocation',
OPEN_VALIDATION_DIALOG: 'openValidationDialog',
RECORD_TAB_CLOSED: 'recordTabClosed',
RESET_SCREENSHOTS: 'resetScreenShots',
SET_CONSOLE_STATUS: 'setConsoleStatus',
SET_FINISHED_TESTS_NUMBER: 'setFinishedTestsNumber',
SET_SHOW_TIPS: 'setShowTips',
SET_START_URL: 'setStartUrl',
SHOW_EXPORT: 'showExport',
SHOW_INFO: 'showInfo',
SHOW_NOTES: 'showNotes',
SHOW_QUICK_CMDS: 'showQuickCmds',
SHOW_SAVE_DIALOG: 'showSaveDialog',
SHOW_SCREENSHOT: 'showScreenshot',
SHOW_SETTING: 'showSetting',
SHOW_PLAYBACK_RUNTIME: 'showPlaybackRuntime',
START_RECORDING: 'startRecording',
START_WORKER_MODE: 'startWorkerMode',
STOP_RECORDING: 'stopRecording',
TOGGLE_CONTENT_MAP: 'showContentMap',
TOGGLE_PROJECT_INFO: 'showProjectInfo',
UPDATE_CURRENT_STEP: 'updateCurrentStep',
UPDATE_ELEMENT_AT_LINE: 'updateElementAtLine',
UPDATE_LOCATOR: 'updateLocator',
UPDATE_PLAYBACK_STATUS: 'updatePlaybackStatus',
UPDATE_SCRIPT_INFO: 'updateScriptInfo',
UPDATE_WHEN_ON_FAILED: 'updateWhenOnFailed',
UPDATE_WHEN_RUN_FINISHED: 'updateWhenRunFinished',
// For console helper.
LOAD_SELECTED_LIB: 'loadSelectedLib',
GENERATE_CUSTOMIZED_FUNCTION_CALL: 'generateCustomizedFunctionCall',
// For details dialog.
ON_CMD_MOVE_DOWN: 'onCmdMoveDown',
ON_CMD_MOVE_UP: 'onCmdMoveUp',
ON_EDIT_CMD: 'onEditCmd',
ON_INSERT_ABOVE: 'onInsertAbove',
ON_INSERT_BELOW: 'onInsertBelow',
ON_LEAVE_COMMENTS: 'onLeaveComments',
ON_PREV_PAGE: 'onPrevPage',
ON_NEXT_PAGE: 'onNextPage',
ON_REMOVE_CUR_LINE: 'onRemoveCurLine',
POST_DEADLINE: 'postDeadline',
UPDATE_HIGHLIGHT_LINE: 'updateHighlightLine',
// For playback dialog.
AUTOMATE_PLAY_MULTIPLE_TESTS: 'automatePlayMultipleTests',
DELETE_CMD: 'deleteCmd',
FAIL_CMD: 'failCmd',
INSERT_CMD: 'insertCmd',
OVERRIDE_CMD: 'overrideCmd',
SET_PLAYBACK_ALL: 'setPlaybackAll',
SET_PLAYBACK_PAUSE: 'setPlaybackPause',
SET_PLAYBACK_STEP: 'setPlaybackStep',
SET_PLAYBACK_STOP: 'setPlaybackStop',
SET_PLAYBACK_STOP_ALL: 'setPlaybackStopAll',
UPDATE_CMD: 'updateCmd',
UPDATE_COMMENT: 'updateComment',
// For validation dialog.
ADD_VALIDATE_POSITION_CMD: 'addValidatePositionCmd',
CHOOSE_VALIDATION_POSITION: 'chooseValidatePosition',
DISPLAY_ALL_ATTRIBUTES: 'displayAllAttributes',
// For savedialog.
SAVE_TEST: 'saveTestToServer',
// For loaddialog.
AUTOMATE_DIALOG_LOAD_PROJECT: 'automateDialogLoadProject',
AUTOMATE_DIALOG_LOAD_TEST: 'automateDialogLoadTest',
SET_PROJECT_INFO: 'setProjectInfo',
// For quick command dialog.
UPDATE_INVOKE_SELECT: 'updateInvokeSelect',
// For settings dialog.
GENERATE_WEBDRIVER_CODE: 'generateWebdriverCode'
};
/**
* The options for the more information panel of the RPF console. This is
* the panel beneath the toolbar, which can be hidden or can show
* additional information about the current test.
* @enum {string}
*/
Bite.Constants.RpfConsoleInfoType = {
NONE: 'none',
PROJECT_INFO: 'projectInfo',
CONTENT_MAP: 'contentMap'
};
/**
* Define ConsoleManager ids for data and management.
* @enum {string}
*/
Bite.Constants.RpfConsoleId = {
CONTENT_MAP_CONTAINER: 'rpf-content-map',
CURRENT_PROJECT: 'rpf-current-project',
DATA_CONTAINER: 'datafileContainer',
ELEMENT_START_URL: 'startUrl',
ELEMENT_STATUS: 'statusLog',
ELEMENT_TEST_ID: 'testId',
ELEMENT_TEST_NAME: 'testName',
PROJECT_INFO_CONTAINER: 'rpf-project-info',
SCRIPTS_CONTAINER: 'scriptsContainer'
};
/**
* The commands in record helper.
* @enum {string}
*/
Bite.Constants.RECORD_ACTION = {
OPEN_XPATH_FINDER: 'openXpathFinder',
START_RECORDING: 'startRecording',
START_UPDATE_MODE: 'startUpdateMode',
STOP_RECORDING: 'stopRecording'
};
/**
* The commands to automate RPF.
* @enum {string}
*/
Bite.Constants.RPF_AUTOMATION = {
ADD_METHOD_TO_RPF: 'addMethodToRpf',
AUTOMATE_SINGLE_SCRIPT: 'automateSingleScript',
LOAD_AND_RUN_FROM_LOCAL: 'loadAndRunFromLocal',
OPEN_TEST_WINDOW: 'openTestWindow',
PLAYBACK_MULTIPLE: 'playbackMultiple',
RUN_METHOD_IN_WINDOW: 'runMethodInWindow'
};
/**
* The constants to playback scripts.
* @enum {number}
*/
Bite.Constants.RPF_PLAYBACK = {
INTERVAL: 700,
REDIRECTION_TIMEOUT: 40 * 1000
};
/**
* Enum for view modes.
* @enum {string}
*/
Bite.Constants.ViewModes = {
CODE: 'code',
READABLE: 'readable',
BOOK: 'book',
UPDATER: 'updater'
};
| JavaScript |
/** @interface */
var AceSession = function() {};
/** @interface */
var AceSessionDoc = function() {};
/** @interface */
var AceRenderer = function() {};
/** @interface */
var AceEditor = function() {};
/** @type {AceSessionDoc} */
AceSession.prototype.doc;
/** @interface */
var RequireOutput = function() {};
/** @return {RequireOutput} */
var require = function(path) {};
/**
* @constructor */
RequireOutput.prototype.Mode;
/** @type {AceRenderer} */
AceEditor.prototype.renderer;
/**
* @param {number} row
* @param {string} className */
AceRenderer.prototype.addGutterDecoration = function(row, className) {};
/**
* @param {number} row
* @param {string} className */
AceRenderer.prototype.removeGutterDecoration = function(row, className) {};
/** @param {boolean} alwaysVisible */
AceRenderer.prototype.setHScrollBarAlwaysVisible = function(alwaysVisible) {};
/** @param {Object} range */
AceSessionDoc.prototype.getTextRange = function(range) {};
/** @return {number} */
AceSession.prototype.getLength = function() {};
/**
* @param {number} row
* @return {string} */
AceSession.prototype.getLine = function(row) {};
/** @return {string} */
AceSession.prototype.getValue = function() {};
/** @param {boolean} useWrap */
AceSession.prototype.setUseWrapMode = function(useWrap) {};
/** @param {string} text */
AceSession.prototype.setValue = function(text) {};
/**
* @param {number} min
* @param {number} max
*/
AceSession.prototype.setWrapLimitRange = function(min, max) {};
/** @param {RequireOutput.prototype.Mode} mode */
AceSession.prototype.setMode = function(mode) {};
/** @return {AceSession} */
AceEditor.prototype.getSession = function() {};
/** @return {Object} */
AceEditor.prototype.getSelectionRange = function() {};
/***/
AceEditor.prototype.resize = function() {};
/** @constructor */
var ace;
/**
* @param {string} elementName The name of the editor element.
* @return {AceEditor}
*/
ace.edit = function(elementName) {};
| JavaScript |
var console = {};
var JSON = {};
var ContentMap = {};
var cmdIndex = 0;
/**
* For selenium-atoms-lib : events.js. Define createTouch for document which
* refers to a touch pad device I believe.
*/
var doc = {};
doc.createTouch = function(a, b, c, d, e, f, g) {};
doc.createTouchList = function(a, b) {};
| JavaScript |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Definitions for the Chromium extensions API.
* @externs
*
*/
/** namespace */
var chrome = {};
/** @see http://code.google.com/chrome/extensions/extension.html */
chrome.extension = {};
/**
* @param {string|Object.<string>=} opt_arg1 Either the extensionId to
* to connect to, in which case connectInfo params can be passed in the
* next optional argument, or the connectInfo params.
* @param {Object.<string>=} opt_connectInfo The connectInfo object,
* if arg1 was the extensionId to connect to.
* @return {Port} New port.
*/
chrome.extension.connect = function(opt_arg1, opt_connectInfo) {};
/**
* @return {Window} The global JS object for the background page.
*/
chrome.extension.getBackgroundPage = function() {};
/**
* @param {number=} opt_windowId An optional windowId.
* @return {Array.<Window>} The global JS objects for each content view.
*/
chrome.extension.getExtensionTabs = function(opt_windowId) {};
/**
* @return {Array.<Window>} The global JS objects for each toolstrip view.
*/
chrome.extension.getToolstrips = function() {};
/**
* @param {string} path A path to a resource within an extension expressed
* relative to it's install directory.
* @return {string} The fully-qualified URL to the resource.
*/
chrome.extension.getURL = function(path) {};
/**
* @param {Object=} fetchProperties An object with optional 'type' and optional
* 'windowId' keys.
* @return {Array.<Window>} The global JS objects for each content view.
*/
chrome.extension.getViews = function(fetchProperties) {};
/**
* @param {number|*=} opt_arg1 Either the extensionId to send the request to,
* in which case the request is passed as the next arg, or the request.
* @param {*=} opt_request The request value, if arg1 was the extensionId.
* @param {function(*) : void=} opt_callback The callback function which
* takes a JSON response object sent by the handler of the request.
*/
chrome.extension.sendRequest = function(opt_arg1, opt_request, opt_callback) {};
/**
* @param {string} data
*/
chrome.extension.setUpdateUrlData = function(data) {};
/** @type {ChromeEvent} */
chrome.extension.onConnect;
/** @type {ChromeEvent} */
chrome.extension.onConnectExternal;
/** @type {ChromeEvent} */
chrome.extension.onRequest;
/** @type {ChromeEvent} */
chrome.extension.onRequestExternal;
/** @see http://code.google.com/chrome/extensions/tabs.html */
chrome.tabs = {};
/**
* @param {number?} windowId Window Id.
* @param {Object?} options parameters of image capture, such as the format of
* the resulting image.
* @param {function(string) : void} callback Callback function which accepts
* the data URL string of a JPEG encoding of the visible area of the
* captured tab. May be assigned to the 'src' property of an HTML Image
* element for display.
*/
chrome.tabs.captureVisibleTab = function(windowId, options, callback) {};
/**
* @param {number} tabId Tab Id.
* @param {Object.<string>=} opt_connectInfo Info Object.
*/
chrome.tabs.connect = function(tabId, opt_connectInfo) {};
/**
* @param {Object} createProperties Info object.
* @param {function(Tab) : void=} opt_callback The callback function.
*/
chrome.tabs.create = function(createProperties, opt_callback) {};
/**
* @param {number?} tabId Tab id.
* @param {function(string) : void} callback Callback function.
*/
chrome.tabs.detectLanguage = function(tabId, callback) {};
/**
* @param {number?} tabId Tab id.
* @param {Object?} details An object which may have 'code', 'file',
* or 'allFrames' keys.
* @param {function() : void=} opt_callback Callback function.
*/
chrome.tabs.executeScript = function(tabId, details, opt_callback) {};
/**
* @param {number} tabId Tab id.
* @param {function(Array.<Tab>) : void} callback Callback.
*/
chrome.tabs.get = function(tabId, callback) {};
/**
* @param {number?} windowId Window id.
* @param {function(Array.<Tab>) : void} callback Callback.
*/
chrome.tabs.getAllInWindow = function(windowId, callback) {};
/**
* @param {number?} windowId Window id.
* @param {function(Tab) : void} callback Callback.
*/
chrome.tabs.getSelected = function(windowId, callback) {};
/**
* @param {number?} tabId Tab id.
* @param {Object?} details An object which may have 'code', 'file',
* or 'allFrames' keys.
* @param {function() : void=} opt_callback Callback function.
*/
chrome.tabs.insertCSS = function(tabId, details, opt_callback) {};
/**
* @param {number} tabId Tab id.
* @param {Object.<string, number>} moveProperties An object with 'index'
* and optional 'windowId' keys.
* @param {function(Tab) : void=} opt_callback Callback.
*/
chrome.tabs.move = function(tabId, moveProperties, opt_callback) {};
/**
* @param {number} tabId Tab id.
* @param {function(Tab) : void=} opt_callback Callback.
*/
chrome.tabs.remove = function(tabId, opt_callback) {};
/**
* @param {number} tabId Tab id.
* @param {*} request The request value of any type.
* @param {function(*) : void=} opt_callback The callback function which
* takes a JSON response object sent by the handler of the request.
*/
chrome.tabs.sendRequest = function(tabId, request, opt_callback) {};
/**
* @param {number} tabId Tab id.
* @param {Object.<string, (string|boolean)>} updateProperties An object which
* may have 'url' or 'selected' key.
* @param {function(Tab) : void=} opt_callback Callback.
*/
chrome.tabs.update = function(tabId, updateProperties, opt_callback) {};
/** @type {ChromeEvent} */
chrome.tabs.onAttached;
/** @type {ChromeEvent} */
chrome.tabs.onCreated;
/** @type {ChromeEvent} */
chrome.tabs.onDetached;
/** @type {ChromeEvent} */
chrome.tabs.onMoved;
/** @type {ChromeEvent} */
chrome.tabs.onRemoved;
/** @type {ChromeEvent} */
chrome.tabs.onSelectionChanged;
/** @type {ChromeEvent} */
chrome.tabs.onUpdated;
/** @see http://code.google.com/chrome/extensions/windows.html */
chrome.windows = {};
/**
* @param {Object?} createData May have 'url', 'left', 'top',
* 'width', or 'height' properties.
* @param {function(ChromeWindow) : void=} opt_callback Callback.
*/
chrome.windows.create = function(createData, opt_callback) {};
/**
* @param {Object.<string, boolean>?} getInfo May have 'populate' key.
* @param {function(Array.<ChromeWindow>): void} callback Callback.
*/
chrome.windows.getAll = function(getInfo, callback) {};
/**
* @param {function(ChromeWindow) : void} callback Callback.
*/
chrome.windows.getCurrent = function(callback) {};
/**
* @param {function(ChromeWindow) : void} callback Callback.
*/
chrome.windows.getLastFocused = function(callback) {};
/**
* @param {number} tabId Tab Id.
* @param {function() : void=} opt_callback Callback.
*/
chrome.windows.remove = function(tabId, opt_callback) {};
/**
* @param {number} tabId Tab Id.
* @param {Object.<string, number>} updateProperties An object which may
* have 'left', 'top', 'width', or 'height' keys.
* @param {function() : void=} opt_callback Callback.
*/
chrome.windows.update = function(tabId, updateProperties, opt_callback) {};
/** @type {ChromeEvent} */
chrome.windows.onCreated;
/** @type {ChromeEvent} */
chrome.windows.onFocusChanged;
/** @type {ChromeEvent} */
chrome.windows.onRemoved;
/**
* @see http://code.google.com/chrome/extensions/windows.html#property-WINDOW_ID_NONE
* @type {number}
*/
chrome.windows.WINDOW_ID_NONE;
/** @see http://code.google.com/chrome/extensions/i18n.html */
chrome.i18n = {};
/**
* @param {function(Array.<string>) : void} callback The callback function which
* accepts an array of the accept languages of the browser, such as
* 'en-US','en','zh-CN'.
*/
chrome.i18n.getAcceptLanguages = function(callback) {};
/**
* @param {string} messageName
* @param {(string|Array.<string>)=} opt_args
* @return {string}
*/
chrome.i18n.getMessage = function(messageName, opt_args) {};
/** @see http://code.google.com/chrome/extensions/pageAction.html */
chrome.pageAction = {};
/**
* @param {number} tabId Tab Id.
*/
chrome.pageAction.hide = function(tabId) {};
/**
* @param {number} tabId Tab Id.
*/
chrome.pageAction.show = function(tabId) {};
/**
* @param {Object} details An object which has 'tabId' and either
* 'imageData' or 'path'.
*/
chrome.pageAction.setIcon = function(details) {};
/**
* @param {Object} details An object which may have 'popup' or 'tabId' as keys.
*/
chrome.pageAction.setPopup = function(details) {};
/**
* @param {Object} details An object which has 'tabId' and 'title'.
*/
chrome.pageAction.setTitle = function(details) {};
/** @type {ChromeEvent} */
chrome.pageAction.onClicked;
/** @see http://code.google.com/chrome/extensions/browserAction.html */
chrome.browserAction = {};
/**
* @param {Object} details An object whose keys are 'color' and
* optionally 'tabId'.
*/
chrome.browserAction.setBadgeBackgroundColor = function(details) {};
/**
* @param {Object} details An object whose keys are 'text' and
* optionally 'tabId'.
*/
chrome.browserAction.setBadgeText = function(details) {};
/**
* @param {Object} details An object which may have 'imageData',
* 'path', or 'tabId' as keys.
*/
chrome.browserAction.setIcon = function(details) {};
/**
* @param {Object} details An object which may have 'popup' or 'tabId' as keys.
*/
chrome.browserAction.setPopup = function(details) {};
/**
* @param {Object} details An object which has 'title' and optionally
* 'tabId'.
*/
chrome.browserAction.setTitle = function(details) {};
/** @type {ChromeEvent} */
chrome.browserAction.onClicked;
/** @see http://code.google.com/chrome/extensions/bookmarks.html */
chrome.bookmarks = {};
/**
* @param {Object} bookmark An object which has 'parentId' and
* optionally 'index', 'title', and 'url'.
* @param {function(BookmarkTreeNode) : void=} opt_callback The
* callback function which accepts a BookmarkTreeNode object.
* @return {BookmarkTreeNode}
*/
chrome.bookmarks.create = function(bookmark, opt_callback) {};
/**
* @param {(string|Array.<string>)} idOrIdList
* @param {function(Array.<BookmarkTreeNode>) : void} callback The
* callback function which accepts an array of BookmarkTreeNode.
* @return {Array.<BookmarkTreeNode>}
*/
chrome.bookmarks.get = function(idOrIdList, callback) {};
/**
* @param {string} id
* @param {function(Array.<BookmarkTreeNode>) : void} callback The
* callback function which accepts an array of BookmarkTreeNode.
* @return {Array.<BookmarkTreeNode>}
*/
chrome.bookmarks.getChildren = function(id, callback) {};
/**
* @param {function(Array.<BookmarkTreeNode>) : void} callback The
* callback function which accepts an array of BookmarkTreeNode.
* @return {Array.<BookmarkTreeNode>}
*/
chrome.bookmarks.getTree = function(callback) {};
/**
* @param {string} id
* @param {Object} destination An object which has 'parentId' and
* optionally 'index'.
* @param {function(Array.<BookmarkTreeNode>) : void=} opt_callback
* The callback function which accepts an array of
* BookmarkTreeNode.
* @return {BookmarkTreeNode}
*/
chrome.bookmarks.move = function(id, destination, opt_callback) {};
/**
* @param {string} id
* @param {function() : void=} opt_callback
*/
chrome.bookmarks.remove = function(id, opt_callback) {};
/**
* @param {string} id
* @param {function() : void=} opt_callback
*/
chrome.bookmarks.removeTree = function(id, opt_callback) {};
/**
* @param {string} query
* @param {function(Array.<BookmarkTreeNode>) : void} callback
* @return {Array.<BookmarkTreeNode>}
*/
chrome.bookmarks.search = function(query, callback) {};
/**
* @param {string} id
* @param {Object} changes An object which may have 'title' as a key.
* @param {function(BookmarkTreeNode) : void=} opt_callback The
* callback function which accepts a BookmarkTreeNode object.
* @return {BookmarkTreeNode}
*/
chrome.bookmarks.update = function(id, changes, opt_callback) {};
/** @type {ChromeEvent} */
chrome.bookmarks.onChanged;
/** @type {ChromeEvent} */
chrome.bookmarks.onChildrenReordered;
/** @type {ChromeEvent} */
chrome.bookmarks.onCreated;
/** @type {ChromeEvent} */
chrome.bookmarks.onMoved;
/** @type {ChromeEvent} */
chrome.bookmarks.onRemoved;
/** @see http://code.google.com/chrome/extensions/dev/contextMenus.html */
chrome.contextMenus = {};
/**
* @param {!Object} createProperties
* @param {function()=} opt_callback
*/
chrome.contextMenus.create = function(createProperties, opt_callback) {};
/**
* @param {number} menuItemId
* @param {function()=} opt_callback
*/
chrome.contextMenus.remove = function(menuItemId, opt_callback) {};
/**
* @param {function()=} opt_callback
*/
chrome.contextMenus.removeAll = function(opt_callback) {};
/**
* @param {number} id
* @param {!Object} updateProperties
* @param {function()=} opt_callback
*/
chrome.contextMenus.update = function(id, updateProperties, opt_callback) {};
/** @see http://code.google.com/chrome/extensions/dev/cookies.html */
chrome.cookies = {};
/**
* @param {Object} details
* @param {function(Cookie=) : void} callback
*/
chrome.cookies.get = function(details, callback) {};
/**
* @param {Object} details
* @param {function(Array.<Cookie>) : void} callback
*/
chrome.cookies.getAll = function(details, callback) {};
/**
* @param {function(Array.<CookieStore>) : void} callback
*/
chrome.cookies.getAllCookieStores = function(callback) {};
/**
* @param {Object} details
*/
chrome.cookies.remove = function(details) {};
/**
* @param {Object} details
*/
chrome.cookies.set = function(details) {};
/** @type {ChromeEvent} */
chrome.cookies.onChanged;
/** @see http://code.google.com/chrome/extensions/experimental.html */
chrome.experimental = {};
/** @see http://code.google.com/chrome/extensions/experimental.clipboard.html */
chrome.experimental.clipboard = {};
/**
* @param {number} tabId
* @param {function()=} opt_callback
*/
chrome.experimental.clipboard.executeCopy = function(tabId, opt_callback) {};
/**
* @param {number} tabId
* @param {function()=} opt_callback
*/
chrome.experimental.clipboard.executeCut = function(tabId, opt_callback) {};
/**
* @param {number} tabId
* @param {function()=} opt_callback
*/
chrome.experimental.clipboard.executePaste = function(tabId, opt_callback) {};
/** @see http://code.google.com/chrome/extensions/experimental.contextMenu.html */
chrome.experimental.contextMenu = {};
/**
* @param {!Object} createProperties
* @param {function(number)=} opt_callback
*/
chrome.experimental.contextMenu.create =
function(createProperties, opt_callback) {};
/**
* @param {number} menuItemId
* @param {function()=} opt_callback
*/
chrome.experimental.contextMenu.remove = function(menuItemId, opt_callback) {};
/** @see http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/api/extension_api.json */
chrome.experimental.extension = {};
/**
* @return {Window}
*/
chrome.experimental.extension.getPopupView = function() {};
/** @see http://code.google.com/chrome/extensions/experimental.infobars.html */
chrome.experimental.infobars = {};
/**
* @param {!Object} details
* @param {function(Window)=} opt_callback
*/
chrome.experimental.infobars.show = function(details, opt_callback) {};
/** @see http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/api/extension_api.json */
chrome.experimental.metrics = {};
/**
* @param {string} metricName
*/
chrome.experimental.metrics.recordUserAction = function(metricName) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordPercentage = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordCount = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordSmallCount = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordMediumCount = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordTime = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordMediumTime = function(metricName, value) {};
/**
* @param {string} metricName
* @param {number} value
*/
chrome.experimental.metrics.recordLongTime = function(metricName, value) {};
/**
* @param {MetricType} metric
* @param {number} value
*/
chrome.experimental.metrics.recordValue = function(metric, value) {};
/** @see http://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/extensions/api/extension_api.json */
chrome.experimental.popup = {};
/**
* @param {string} url
* @param {Object} showDetails
* @param {function() : void=} opt_callback
*/
chrome.experimental.popup.show = function(url, showDetails, opt_callback) {};
/** @type {ChromeEvent} */
chrome.experimental.popup.onClosed;
/** @see http://code.google.com/chrome/extensions/experimental.processes.html */
chrome.experimental.processes = {};
/**
* @param {number} tabId
* @param {function(Process)} callback
*/
chrome.experimental.processes.getProcessForTab = function(tabId, callback) {}
chrome.experimental.rlz = {};
/**
* @param {string} product
* @param {string} accessPoint
* @param {string} event
*/
chrome.experimental.rlz.recordProductEvent = function(product, accessPoint,
event) {};
/**
* @param {string} product
* @param {Array.<string>} accessPoints
*/
chrome.experimental.rlz.clearProductState = function(product, accessPoints) {};
/**
* @param {string} product
* @param {Array.<string>} accessPoints
* @param {string} signature
* @param {string} brand
* @param {string} id
* @param {string} lang
* @param {boolean} excludeMachineId
* @param {function(boolean): void} callback
*/
chrome.experimental.rlz.sendFinancialPing = function(product, accessPoints,
signature, brand, id, lang,
excludeMachineId,
callback) {};
/**
* @param {string} accessPoint
* @param {function(string): void} callback
*/
chrome.experimental.rlz.getAccessPointRlz = function(accessPoint, callback) {};
chrome.management = {};
/**
* @param {function(Array.<ExtensionInfo>): void} callback
*/
chrome.management.getAll = function(callback) {};
/**
* @param {string} id
* @param {function(ExtensionInfo): void} callback
*/
chrome.management.get = function(id, callback) {};
/**
* @param {string} id
* @param {boolean} enabled
* @param {function(): void} callback
*/
chrome.management.setEnabled = function(id, enabled, callback) {};
/**
* @param {string} id
* @param {function(): void} callback
*/
chrome.management.uninstall = function(id, callback) {};
/**
* @param {string} id
* @param {function(): void} callback
*/
chrome.management.launchApp = function(id, callback) {};
/** @type {ChromeEvent} */
chrome.management.onDisabled;
/** @type {ChromeEvent} */
chrome.management.onEnabled;
/** @type {ChromeEvent} */
chrome.management.onInstalled;
/** @type {ChromeEvent} */
chrome.management.onUninstalled;
/** @see http://code.google.com/chrome/extensions/idle.html */
chrome.idle = {};
/**
* @param {number} thresholdSeconds Threshold in seconds, used to determine
* when a machine is in the idle state.
* @param {function(string) : void} callback Callback to handle the state.
*/
chrome.idle.queryState = function(thresholdSeconds, callback) {};
/** @type {ChromeEvent} */
chrome.idle.onStateChanged;
// Classes
/**
* @see http://code.google.com/chrome/extensions/management.html
* @constructor
*/
function ExtensionInfo() {}
/** @type {string} */
ExtensionInfo.prototype.id;
/** @type {string} */
ExtensionInfo.prototype.name;
/** @type {string} */
ExtensionInfo.prototype.version;
/** @type {boolean} */
ExtensionInfo.prototype.enabled;
/** @type {boolean} */
ExtensionInfo.prototype.isApp;
/** @type {string} */
ExtensionInfo.prototype.appLaunchUrl;
/** @type {string} */
ExtensionInfo.prototype.optionsUrl;
/** @type {Array.<IconInfo>} */
ExtensionInfo.prototype.icons;
/**
* @see http://code.google.com/chrome/extensions/management.html
* @constructor
*/
function IconInfo() {}
/** @type {number} */
IconInfo.prototype.size;
/** @type {string} */
IconInfo.prototype.url;
/**
* @see http://code.google.com/chrome/extensions/tabs.html
* @constructor
*/
function Tab() {}
/** @type {number} */
Tab.prototype.id;
/** @type {number} */
Tab.prototype.index;
/** @type {number} */
Tab.prototype.windowId;
/** @type {boolean} */
Tab.prototype.selected;
/** @type {string} */
Tab.prototype.url;
/** @type {string} */
Tab.prototype.title;
/** @type {string} */
Tab.prototype.favIconUrl;
/** @type {string} */
Tab.prototype.status;
/**
* @see http://code.google.com/chrome/extensions/windows.html
* @constructor
*/
function ChromeWindow() {}
/** @type {number} */
ChromeWindow.prototype.id;
/** @type {boolean} */
ChromeWindow.prototype.focused;
/** @type {number} */
ChromeWindow.prototype.top;
/** @type {number} */
ChromeWindow.prototype.left;
/** @type {number} */
ChromeWindow.prototype.width;
/** @type {number} */
ChromeWindow.prototype.height;
/** @type {Array.<Tab>} */
ChromeWindow.prototype.tabs;
/** @type {boolean} */
ChromeWindow.prototype.incognito;
/** @type {string} */
ChromeWindow.prototype.type;
/**
* @see http://code.google.com/chrome/extensions/events.html
* @constructor
*/
function ChromeEvent() {}
/** @param {Function} callback */
ChromeEvent.prototype.addListener = function(callback) {};
/** @param {Function} callback */
ChromeEvent.prototype.removeListener = function(callback) {};
/** @param {Function} callback */
ChromeEvent.prototype.hasListener = function(callback) {};
/** @param {Function} callback */
ChromeEvent.prototype.hasListeners = function(callback) {};
/**
* @see http://code.google.com/chrome/extensions/extension.html#type-Port
* @constructor
*/
function Port() {}
/** @type {string} */
Port.prototype.name;
/** @type {Tab} */
Port.prototype.tab;
/** @type {MessageSender} */
Port.prototype.sender;
/** @type {ChromeEvent} */
Port.prototype.onMessage;
/** @type {ChromeEvent} */
Port.prototype.onDisconnect;
/**
* @param {Object.<string>} obj Message object.
*/
Port.prototype.postMessage = function(obj) {};
Port.prototype.disconnect = function() {};
/**
* @see http://code.google.com/chrome/extensions/extension.html#type-MessageSender
* @constructor
*/
function MessageSender() {}
/** @type {Tab} */
MessageSender.prototype.tab;
/** @type {string} */
MessageSender.prototype.id;
/**
* @see http://code.google.com/chrome/extensions/bookmarks.html#type-BookmarkTreeNode
* @constructor
*/
function BookmarkTreeNode() {}
/** @type {string} */
BookmarkTreeNode.prototype.id;
/** @type {string} */
BookmarkTreeNode.prototype.parentId;
/** @type {number} */
BookmarkTreeNode.prototype.index;
/** @type {string} */
BookmarkTreeNode.prototype.url;
/** @type {string} */
BookmarkTreeNode.prototype.title;
/** @type {number} */
BookmarkTreeNode.prototype.dateAdded;
/** @type {number} */
BookmarkTreeNode.prototype.dateGroupModified;
/** @type {Array.<BookmarkTreeNode>} */
BookmarkTreeNode.prototype.children;
/**
* @see http://code.google.com/chrome/extensions/dev/cookies.html#type-Cookie
* @constructor
*/
function Cookie() {}
/** @type {string} */
Cookie.prototype.name;
/** @type {string} */
Cookie.prototype.value;
/** @type {string} */
Cookie.prototype.domain;
/** @type {boolean} */
Cookie.prototype.hostOnly;
/** @type {string} */
Cookie.prototype.path;
/** @type {boolean} */
Cookie.prototype.secure;
/** @type {boolean} */
Cookie.prototype.httpOnly;
/** @type {boolean} */
Cookie.prototype.session;
/** @type {number} */
Cookie.prototype.expirationDate;
/** @type {string} */
Cookie.prototype.storeId;
/**
* @see http://code.google.com/chrome/extensions/dev/cookies.html#type-CookieStore
* @constructor
*/
function CookieStore() {}
/** @type {string} */
CookieStore.prototype.id;
/** @type {Array.<number>} */
CookieStore.prototype.tabIds;
/**
* Experimental MetricType
* @constructor
*/
function MetricType() {}
/** @type {string} */
MetricType.prototype.metricName;
/** @type {string} */
MetricType.prototype.type;
/** @type {number} */
MetricType.prototype.min;
/** @type {number} */
MetricType.prototype.max;
/** @type {number} */
MetricType.prototype.buckets;
/**
* Experimental Process type.
* @see http://code.google.com/chrome/extensions/experimental.processes.html#type-Process
* @constructor
*/
function Process() {}
/** @type {number} */
Process.prototype.id;
/**
* @see http://code.google.com/chrome/extensions/dev/contextMenus.html#type-OnClickData
* @constructor
*/
function OnClickData() {}
/** @type {number} */
OnClickData.prototype.menuItemId;
/** @type {number} */
OnClickData.prototype.parentMenuItemId;
/** @type {string} */
OnClickData.prototype.mediaType;
/** @type {string} */
OnClickData.prototype.linkUrl;
/** @type {string} */
OnClickData.prototype.srcUrl;
/** @type {string} */
OnClickData.prototype.pageUrl;
/** @type {string} */
OnClickData.prototype.frameUrl;
/** @type {string} */
OnClickData.prototype.selectionText;
/** @type {string} */
OnClickData.prototype.editable;
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Handles login interactions between the
* bite client and the server.
*
* @author michaelwill@google.com (Michael Williamson)
*/
goog.provide('bite.LoginManager');
goog.require('bite.common.net.xhr.async');
goog.require('goog.Uri');
goog.require('goog.json');
goog.require('goog.string');
/**
* Singleton class for handling interactions with the server.
* @constructor
* @export
*/
bite.LoginManager = function() {
/**
* The current logged in user.
* @type {string}
* @private
*/
this.username_ = '';
/**
* The login or out url.
* @type {string}
* @private
*/
this.loginOrOutUrl_ = '';
};
goog.addSingletonGetter(bite.LoginManager);
/**
* Url used to check the login status of the current user.
* @type {string}
* @private
*/
bite.LoginManager.CHECK_LOGIN_STATUS_PATH_ = '/check_login_status';
/**
* Retrieves the current user, checking the server on every
* call.
* @param {function({success: boolean, url: string, username: string})}
* callback A callback which will be invoked
* with a loginOrOutUrl that can be used by the client and optionally
* the username, if it exists.
* @param {string} server The server URL.
* @export
*/
bite.LoginManager.prototype.getCurrentUser = function(callback, server) {
if (this.username_) {
// If the username exists, no need to send an additional ping to server,
// if the sync issue happens, we should periodically ping server to
// refresh.
callback(this.buildResponseObject_(
true, this.loginOrOutUrl_, this.username_));
return;
}
var url = goog.Uri.parse(server);
url.setPath(bite.LoginManager.CHECK_LOGIN_STATUS_PATH_);
bite.common.net.xhr.async.get(url.toString(),
goog.bind(this.getCurrentUserCallback_, this, callback, server));
};
/**
* Callback invoked when the getCurrentUser request finishes.
* @param {function({success: boolean, url: string, username: string})}
* operationFinishedCallback A callback invoked on completion.
* @param {string} server The server URL.
* @param {boolean} success Whether or not the request was successful.
* @param {string} data The data from the request or an error string.
* @param {number} status The status of the request.
* @private
*/
bite.LoginManager.prototype.getCurrentUserCallback_ =
function(operationFinishedCallback, server, success, data, status) {
var responseObj = null;
try {
if (!success) {
throw '';
}
var response = goog.json.parse(data);
var loginOrOutUrl = response['url'] || '';
if (!goog.string.startsWith(loginOrOutUrl, 'http')) {
// The dev appengine server returns a login url that is simply a path
// on the current dev server url whereas production returns
// a path that is a fully qualified url.
loginOrOutUrl = server + loginOrOutUrl;
}
this.username_ = response['user'] || '';
this.loginOrOutUrl_ = loginOrOutUrl;
responseObj = this.buildResponseObject_(
true, loginOrOutUrl, this.username_);
} catch (e) {
responseObj = this.buildResponseObject_(false, '', '');
}
operationFinishedCallback(responseObj);
};
/**
* Helper utility that wraps up a response object.
* @return {{success: boolean, url: string, username: string}}
* @private
*/
bite.LoginManager.prototype.buildResponseObject_ = function(
success, url, username) {
return {
'success': success,
'url': url,
'username': username
};
};
| JavaScript |
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-20998404-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.signal.Simple.
*
* Test cases:
* testIncrementAndOptCalls
* testIncrement
* testRepeatFire
* testNoOptCalls
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.utils.Barrier');
/**
* Sets up the environment for each unit test.
*/
function setUp() {}
/**
* Cleans up the environment for each unit test.
*/
function tearDown() {}
/**
* Tests that incrementing after the barrier is created with opt_numCalls by
* starting the barrier at one and then incrementing by one. When fired three
* times, the callback will be fired once.
*/
function testIncrementAndOptCalls() {
var counter = 0;
var callback = function() {
++counter;
};
var barrier = new bite.common.utils.Barrier(callback, 1);
barrier.increment();
barrier.fire();
barrier.fire(); // Fires immediately because it reaches zero on this firing.
barrier.fire();
assertEquals(2, counter);
}
/**
* Tests that the increment function causes the barrier to prevent firing until
* the the counter reaches zero. Test increments by two and fires four times
* to ensure the callback is only fired twice.
*/
function testIncrement() {
var counter = 0;
var callback = function() {
++counter;
};
var barrier = new bite.common.utils.Barrier(callback);
barrier.increment();
barrier.increment();
barrier.fire();
barrier.fire(); // Fires immediately because it reaches zero on this firing.
barrier.fire();
barrier.fire();
assertEquals(3, counter);
}
/**
* Tests that the barrier can fire repeatedly after it has been called once.
*/
function testRepeatFire() {
var counter = 0;
var callback = function() {
++counter;
};
var barrier = new bite.common.utils.Barrier(callback);
barrier.fire();
barrier.fire();
barrier.fire();
assertEquals(3, counter);
}
/**
* Tests creating a barrier with no initial counter and ensure the barrier can
* fire immediately.
*/
function testNoOptCalls() {
var counter = 0;
var callback = function() {
++counter;
};
var barrier = new bite.common.utils.Barrier(callback);
barrier.fire();
assertEquals(1, counter);
}
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The barrier concept is a function that blocks while there are
* outstanding users of the barrier. Each user increments a counter on the
* barrier to mark themselves as barrier users. When the user is done they can
* fire the barrier, decreasing the counter by one. When the counter reaches
* zero the associated callback function is called. The barrier is considered
* down once the count reaches zero and can continue to be fired. Subsequent
* calls to increment will start the counter moving up again from zero.
*
* When creating a new Barrier object the associated callback does not
* receive any inputs as the Barrier has no context for the callback. If
* specific values are to be passed on to the callback then they should be
* bound before creating the barrier.
*
* If opt_numCalls is not supplied then the barrier will fire immediately.
* Otherwise, the barrier starts with a positive counter that must be counted
* down before firing.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.utils.Barrier');
/**
* Constructs a new Barrier object; see the file overview for more details.
* @param {function()} callback The callback function to be fired when the
* appropriate conditions have been met.
* @param {number=} opt_numCalls The number of calls before calling the given
* callback.
* @constructor
*/
bite.common.utils.Barrier = function(callback, opt_numCalls) {
/**
* The callback function to fire when the barrier is down.
* @type {function()}
* @private
*/
this.callback_ = callback;
/**
* The number of calls to fire that must occur before the associated callback
* is fired. Acts like a count down.
* @type {number}
* @private
*/
this.numCalls_ = opt_numCalls && opt_numCalls > 0 ? opt_numCalls : 0;
};
/**
* Increase the count before the callback is fired.
*/
bite.common.utils.Barrier.prototype.increment = function() {
++this.numCalls_;
};
/**
* Subtract one from the count. Once the count reaches zero the callback will
* fire and will continue to fire with each subsequent call where the count
* is zero.
*/
bite.common.utils.Barrier.prototype.fire = function() {
this.numCalls_ && --this.numCalls_; // Decrement if > 0.
this.numCalls_ || this.callback_(); // Fire callback if == 0.
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define an event that also passes out data in the form of an
* optional object.
*
* This is a generic event beyond that which is provided by goog.events.Event.
* However, at a later time there may be a desire for more events. In that
* case, this file will need to be altered to reflect a more specific usage.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.events.DataBearingEvent');
goog.require('goog.events.Event');
/**
* See fileoverview.
* @param {string} type The Event type.
* @param {Object=} opt_data The data to pass on.
* @extends {goog.events.Event}
* @constructor
* @export
*/
bite.common.events.DataBearingEvent = function(type, opt_data) {
goog.base(this, type);
/**
* The data passed on by the EventTarget.
* @type {?Object}
* @private
*/
this.data_ = opt_data || null;
};
goog.inherits(bite.common.events.DataBearingEvent, goog.events.Event);
/**
* Retrieve the data from the event.
* @return {Object} The data encompassed by the event.
* @export
*/
bite.common.events.DataBearingEvent.prototype.getData = function() {
return this.data_;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The file provides utility functions for manipulating urls.
*
* Public data:
* Regex - An enumeration of useful regular expressions.
*
* Public functions:
* isAbsolute(url, opt_scheme) - Determines if the given url is an absolute
* url or not.
* toAbsolute(url, base, opt_scheme) - Converts url to an absolute url using
* base. If the url is already absolute then do nothing.
*
* Usage:
* bite.common.net.url.Regex.VALID_SCHEME.test('http://a/'); // true
*
* bite.common.net.url.isAbsolute('other://a/b/c', 'other'); // true
* bite.common.net.url.isAbsolute('/a/b/c'); // false
*
* bite.common.net.url.toAbsolute('/b/c', 'http:/a/'); // 'http:/a/b/c'
* bite.common.net.url.toAbsolute('b/c', 'http:/a'); // 'http:/a/b/c'
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.net.url');
/**
* A regular expression representing valid url schemes.
* @enum {RegExp}
*/
bite.common.net.url.Regex = {
// Valid url root (scheme://).
VALID_ROOT: /^(http|https|ftp|file)[:][/][/]/,
// Valid url schemes (standard).
VALID_SCHEME: /^(http|https|ftp|file)/
};
/**
* Determines if the url is absolute by examining the beginning of the url
* looking for a valid root (scheme://). The function does not validate the
* full url to ensure it is valid; it assumes the user passes a valid url.
* @param {string} url The url to check.
* @param {string=} opt_scheme If an optional scheme is supplied then use it
* to check if a url is absolute. This is useful for non-standard urls
* such as chrome://.
* @return {boolean} Whether or not the url is absolute.
*/
bite.common.net.url.isAbsolute = function(url, opt_scheme) {
if (opt_scheme) {
return RegExp(opt_scheme + '[:][/][/]').test(url);
}
return bite.common.net.url.Regex.VALID_ROOT.test(url);
};
/**
* Converts a url to an absolute url unless the url is already an absolute url
* in which case nothing changes. Otherwise the base and url are concatenated
* to form a new absolute url. Upon invalid base url, the function will return
* the empty string.
* @param {string} url The original url.
* @param {string} base The base url.
* @param {string=} opt_scheme If an optional scheme is supplied then use it
* to check if a url is absolute. This is useful for non-standard urls
* such as chrome://.
* @return {string} The new url, the same if it is already absolute, or the
* empty string for invalid inputs.
*/
bite.common.net.url.toAbsolute = function(url, base, opt_scheme) {
// If the url starts with a valid scheme then consider it an absolute url and
// return it.
if (bite.common.net.url.isAbsolute(url, opt_scheme)) {
return url;
}
// Check for invalid inputs. Testing whether the base url is absolute also
// checks for the empty string.
if (!bite.common.net.url.isAbsolute(base, opt_scheme)) {
return '';
}
// Ensure that a single slash will join the two strings.
return [
base.substr(0, base.length - (base[base.length - 1] == '/' ? 1 : 0)),
url.substr((url[0] == '/' ? 1 : 0), url.length)
].join('/');
};
/**
* Converts a url to its full path meaning everything from the scheme to the
* final slash; i.e. cut off anything after the final slash.
* @param {string} url The url to manipulate.
* @return {string} The full path.
*/
bite.common.net.url.getFullPath = function(url) {
return url.replace(/[^/]+$/, '');
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.net.xhr.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.net.xhr');
goog.require('goog.testing.PropertyReplacer');
/**
* Create an event that will return false meaning the request failed. It
* also provides an error code and error message.
* @type {!Object}
*/
var failEvent = {
target: {
getLastError: function() { return 'error' },
getLastErrorCode: function() { return 400; },
getResponseText: function() { return 'fail'; },
getStatus: function() { return 400; },
isSuccess: function() { return false; }
}
}
/**
* A string represent the error message sent back by the fail event.
* @type {string}
*/
var FAIL_MESSAGE = '[' + failEvent.target.getLastErrorCode() + '] ' +
failEvent.target.getLastError();
/**
* A string represent the success message sent back by the success event.
* @type {string}
*/
var SUCCESS_MESSAGE = 'success';
/**
* Create an event that will return false meaning the request failed. It
* also provides an error code and error message.
* @type {!Object}
*/
var successEvent = {
target: {
getLastError: function() { return 'none' },
getLastErrorCode: function() { return 200; },
getResponseText: function() { return SUCCESS_MESSAGE; },
getStatus: function() { return 200; },
isSuccess: function() { return true; }
}
}
/**
* Replace the Xhr send function.
* @param {string} url The url.
* @param {Function} callback The callback.
*/
function send(url, callback) {
if (url == 'fail') {
callback(failEvent);
} else {
callback(successEvent);
}
}
/**
* Create stub object.
* @type {goog.testing.PropertyReplacer}
*/
var stubs_ = new goog.testing.PropertyReplacer();
stubs_.set(goog.net.XhrIo, 'send', send);
/**
* Setup performed for each test.
*/
function setUp() {
}
/**
* Cleanup performed for each test.
*/
function tearDown() {
}
/**
* Callback function that validates inputs sent from an XHR call.
* @param {string} msg The message given to assert to identify the specific
* test.
* @param {boolean} expectedSuccess The expected value for success.
* @param {string} expectedData The expected value for data.
* @param {boolean} success The value passed from the request.
* @param {string} data The data passed from the request.
* @param {number} status The status of the response.
*/
function validate(msg, expectedSuccess, expectedData, expectedStatus,
success, data, status) {
assertEquals(msg, expectedSuccess, success);
assertEquals(msg, expectedData, data);
assertEquals(msg, expectedStatus, status);
}
/**
* Test the functions expecting a valid response.
*/
function testResponse() {
var msg = '(Response)';
var url = 'pass';
var data = '';
var response = SUCCESS_MESSAGE;
var callback = goog.partial(validate, 'AsyncGet' + msg, true, response, 200);
bite.common.net.xhr.async.get(url, callback);
callback = goog.partial(validate, 'AsyncPost' + msg, true, response, 200);
bite.common.net.xhr.async.post(url, data, callback);
callback = goog.partial(validate, 'AsyncPut' + msg, true, response, 200);
bite.common.net.xhr.async.put(url, data, callback);
}
/**
* Test the functions expecting a valid response but no callback provided.
*/
function testNoCallback() {
var msg = '(No callback)';
var url = 'pass';
var data = '';
var errorMsg = ' failed when optional callback was not supplied: ';
try {
bite.common.net.xhr.async.get(url);
} catch (error) {
fail(msg + 'AsyncGet' + errorMsg + error);
}
try {
bite.common.net.xhr.async.post(url, data);
} catch (error) {
fail(msg + 'AsyncPost' + errorMsg + error);
}
try {
bite.common.net.xhr.async.put(url, data);
} catch (error) {
fail(msg + 'AsyncPut' + errorMsg + error);
}
}
/**
* Test the functions where the request receives a response but the request
* failed with a specific error code and error message.
*/
function testRequestFailedException() {
var msg = '(Request Failed)';
var url = 'fail';
var data = '';
var callback =
goog.partial(validate, 'AsyncGet' + msg, false, FAIL_MESSAGE, 400);
bite.common.net.xhr.async.get(url, callback);
callback =
goog.partial(validate, 'AsyncPost' + msg, false, FAIL_MESSAGE, 400);
bite.common.net.xhr.async.post(url, data, callback);
callback =
goog.partial(validate, 'AsyncPut' + msg, false, FAIL_MESSAGE, 400);
bite.common.net.xhr.async.put(url, data, callback);
}
/**
* Test the functions with no url. Assumes that any false input will suffice
* for "no url" meaning null, undefined, and ''.
*/
function testMissingUrl() {
var msg = '(Missing Url)';
var url = '';
var data = '';
var callback = goog.partial(validate, 'AsyncGet' + msg, false,
bite.common.net.xhr.ErrorMessage_.MISSING_URL,
400);
bite.common.net.xhr.async.get(url, callback);
callback = goog.partial(validate, 'AsyncPost' + msg, false,
bite.common.net.xhr.ErrorMessage_.MISSING_URL,
400);
bite.common.net.xhr.async.post(url, data, callback);
callback = goog.partial(validate, 'AsyncPut' + msg, false,
bite.common.net.xhr.ErrorMessage_.MISSING_URL,
400);
bite.common.net.xhr.async.put(url, data, callback);
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.net.url.
*
* Test cases:
* testGetFullPath
* testToAbsolute
* testIsAbsolute
* testRegex
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.net.url');
/**
* Tests that getFullPath works as expected.
*/
function testGetFullPath() {
var getFullPath = bite.common.net.url.getFullPath;
assertEquals('1', '', getFullPath(''));
assertEquals('2', '', getFullPath('a'));
assertEquals('3', '/', getFullPath('/b'));
assertEquals('4', '/', getFullPath('/'));
assertEquals('5', 'a/', getFullPath('a/b'));
assertEquals('6', 'http://', getFullPath('http://'));
assertEquals('7', 'http://', getFullPath('http://a'));
assertEquals('8', 'http://a/', getFullPath('http://a/b'));
assertEquals('9', 'http://a/', getFullPath('http://a/b.html'));
}
/**
* Tests that the given url can be correctly converted to an absolute url.
*/
function testToAbsolute() {
var toAbsolute = bite.common.net.url.toAbsolute;
// Valid tests.
assertEquals('1', 'http://a/b', toAbsolute('b', 'http://a'));
assertEquals('2', 'http://a/b', toAbsolute('a/b', 'http://'));
assertEquals('3', 'http://a/b/', toAbsolute('', 'http://a/b'));
// Test valid slash concatenation.
assertEquals('4', 'http://a/b', toAbsolute('b', 'http://a'));
assertEquals('5', 'http://a/b', toAbsolute('/b', 'http://a'));
assertEquals('6', 'http://a/b', toAbsolute('b', 'http://a/'));
assertEquals('7', 'http://a/b', toAbsolute('/b', 'http://a/'));
// Test optional scheme.
assertEquals('8', 'other://a/b', toAbsolute('b', 'other://a', 'other'));
// Invalid tests.
assertEquals('9', '', toAbsolute('b', 'other://a'));
assertEquals('10', '', toAbsolute('b', ''));
assertEquals('11', '', toAbsolute('b', 'text'));
}
/**
* Tests that isAbsolute correctly matches urls with the appropriate scheme and
* the optional scheme.
*/
function testIsAbsolute() {
// Valid tests.
assertTrue('1', bite.common.net.url.isAbsolute('http://a/'));
assertTrue('2', bite.common.net.url.isAbsolute('https://a/'));
assertTrue('3', bite.common.net.url.isAbsolute('ftp://a/'));
assertTrue('4', bite.common.net.url.isAbsolute('file:///'));
assertTrue('5', bite.common.net.url.isAbsolute('other://a/', 'other'));
// Invalid tests.
// Invalid due to space before http.
assertFalse('6', bite.common.net.url.isAbsolute(' http://a/'));
// Invalid due to missing '/'.
assertFalse('7', bite.common.net.url.isAbsolute('http:/a/'));
// Invalid due to invalid scheme.
assertFalse('8', bite.common.net.url.isAbsolute('other://a/'));
}
/**
* Tests the regular expressions to ensure they match properly.
*/
function testRegex() {
// Test bite.common.net.url.Regex.VALID_ROOT.
// Valid tests.
assertTrue('1', bite.common.net.url.Regex.VALID_ROOT.test('http://'));
assertTrue('2', bite.common.net.url.Regex.VALID_ROOT.test('https://'));
assertTrue('3', bite.common.net.url.Regex.VALID_ROOT.test('ftp://'));
assertTrue('4', bite.common.net.url.Regex.VALID_ROOT.test('file://'));
// Invalid tests.
// Invalid due to space before http.
assertFalse('5', bite.common.net.url.Regex.VALID_ROOT.test(' http://'));
// Invalid due to missing '/'.
assertFalse('6', bite.common.net.url.Regex.VALID_ROOT.test('http:/'));
// Invalid due to invalid scheme.
assertFalse('7', bite.common.net.url.Regex.VALID_ROOT.test('other://'));
// Test bite.common.net.url.Regex.VALID_SCHEME.
// Valid tests.
assertTrue('8', bite.common.net.url.Regex.VALID_SCHEME.test('http'));
assertTrue('9', bite.common.net.url.Regex.VALID_SCHEME.test('https'));
assertTrue('10', bite.common.net.url.Regex.VALID_SCHEME.test('ftp'));
assertTrue('11', bite.common.net.url.Regex.VALID_SCHEME.test('file'));
// Invalid tests.
// Invalid due to space before http.
assertFalse('12', bite.common.net.url.Regex.VALID_SCHEME.test(' http'));
// Invalid due to invalid scheme.
assertFalse('13', bite.common.net.url.Regex.VALID_SCHEME.test('other'));
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides an interface for doing XMLHttpRequests (Get/Post).
* The mechanisms handle sending, receiving, and processing of a request
* including error handling. The raw data received by the request is returned
* to the caller through an optionally provided callback. When the caller
* provides a callback, the callback function is expected to take two inputs; a
* boolean success and a data string. Upon error, the callback will be
* provided a false value and the data string containing an error message.
*
* Public functions:
* get(url, opt_callback) - Performs a get.
* getMultiple(array, getUrl, app, opt_complete) - Recursively gets a number
* of urls asynchronously. *Looking to refactor.*
* post(url, data, opt_callback, opt_headers) - Performs a post.
* put(url, data, opt_callback, opt_headers) - Performs a put.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.net.xhr');
goog.provide('bite.common.net.xhr.async');
goog.require('bite.common.utils.Barrier');
goog.require('goog.net.XhrIo');
/**
* A set of messages used to communicate externally.
* @enum {string}
* @private
*/
bite.common.net.xhr.ErrorMessage_ = {
EXCEPTION: 'Exception: ',
MISSING_URL: 'No url supplied.',
REQUEST_FAILED: 'Request failed.'
};
/**
* Sends a request to the given url and returns the response.
* @param {string} url The url.
* @param {function(boolean, string, number)=} opt_callback The callback that
* is fired when the request is complete. The boolean input is the success
* of the request. The string is the request response text or an error
* message if the request failed. The number is the request status.
* Decoding does not occur for the response string, and is up to the caller
* if necessary.
* @param {Object.<string>=} opt_headers Headers to be added to the request.
*/
bite.common.net.xhr.async.get = function(url, opt_callback, opt_headers) {
var callback = opt_callback || null;
var headers = opt_headers || null;
bite.common.net.xhr.async.send_(url, callback, 'GET', null, headers);
};
/**
* Sends a request to the given url and returns the response.
* @param {string} url The url.
* @param {function(boolean, string, number)=} opt_callback The callback that
* is fired when the request is complete. The boolean input is the success
* of the request. The string is the request response text or an error
* message if the request failed. The number is the request status.
* Decoding does not occur for the response string, and is up to the caller
* if necessary.
* @param {Object.<string>=} opt_headers Headers to be added to the request.
*/
bite.common.net.xhr.async.del = function(url, opt_callback, opt_headers) {
var callback = opt_callback || null;
var headers = opt_headers || null;
bite.common.net.xhr.async.send_(url, callback, 'DELETE', null, headers);
};
/**
* Posts data to the given url and returns the response.
* @param {string} url The url.
* @param {string} data The data to send; in string form. Caller is
* responsible for encoding the string if necessary.
* @param {function(boolean, string, number)=} opt_callback The callback that
* is fired when the request is complete. The boolean input is the success
* of the request. The string is the request response text or an error
* message if the request failed. The number is the request status.
* Decoding does not occur for the response string, and is up to the caller
* if necessary.
* @param {Object.<string>=} opt_headers Headers to be added to the request.
*/
bite.common.net.xhr.async.post = function(url, data, opt_callback,
opt_headers) {
var callback = opt_callback || null;
var headers = opt_headers || null;
bite.common.net.xhr.async.send_(url, callback, 'POST', data, headers);
};
/**
* Puts data to the given url and returns the response.
* @param {string} url The url.
* @param {string} data The data to send; in string form. Caller is
* responsible for encoding the string if necessary.
* @param {function(boolean, string, number)=} opt_callback The callback that
* is fired when the request is complete. The boolean input is the success
* of the request. The string is the request response text or an error
* message if the request failed. The number is the request status.
* Decoding does not occur for the response string, and is up to the caller
* if necessary.
* @param {Object.<string>=} opt_headers Headers to be added to the request.
*/
bite.common.net.xhr.async.put = function(url, data, opt_callback,
opt_headers) {
var callback = opt_callback || null;
var headers = opt_headers || null;
bite.common.net.xhr.async.send_(url, callback, 'PUT', data, headers);
};
/**
* Start an asynchronous request for each element in the array at the same
* time. Each time a request completes the app function is applied to the
* element along with the success of the request and the data, or error, from
* the request. Once all requests have completed the complete function will be
* called on the entire array of elements. If during the app call more
* requests are sent out then the current group will also wait for those
* requests to finish.
* TODO (jasonstredwick): Refactor this code. It is legacy but the design
* could much improved and generalized.
* @param {!Array.<*>} array An array of elements.
* @param {function(*): string} getUrl A function that when applied to an
* element from the array will return a url. If the function returns a
* "false" value that element will not be added to the download list.
* @param {function(*, boolean, string)} app A function that when applied to an
* array element sending in the success and data from the request.
* @param {function(Array.<*>)=} opt_complete The function to be called once
* all the requests and child requests have completed. The original array
* is passed in.
* @param {Object.<string>=} opt_headers Headers to be added to the request.
*/
bite.common.net.xhr.async.getMultiple = function(array, getUrl, app,
opt_complete, opt_headers) {
var async = bite.common.net.xhr.async;
var openBarrier = async.getMultiple.prototype.openBarrier_;
// If there is already a barrier in use and a new barrier is being created
// then the current barrier needs to wait for the new one to finish thus
// increment its count by one.
//
openBarrier && openBarrier.increment();
// The completeFunc is necessary regardless of whether or not the
// opt_complete function is given in order to handle possible hierarchical
// requests.
var completeFunc = function() {
opt_complete && opt_complete(array);
// If there was a barrier active during this call it will need to be fired
// upon the completion of this group of events.
openBarrier && openBarrier.fire();
};
// Create a new barrier and set it to fire completeFunc after one fire. The
// one is for this function so that if there are no elements to request this
// function will fire at the end causing the completeFunc to fire. Each
// element that is requested will increase the number of fires by one.
var barrier = new bite.common.utils.Barrier(completeFunc, 1);
for (var i = 0, len = array.length; i < len; ++i) {
var element = array[i];
var url = getUrl(element);
// The user has the ability to return null with getUrl to indicate that
// the current element is not to be included in the set to load.
if (!url) {
continue;
}
// Create a function callback for each app(element) to ensure the proper
// handling of hierarchical calls to getMultiple.
var appFunc = (function(e, b, f) {
return function(success, data) {
async.getMultiple.prototype.openBarrier_ = b;
try {
f(e, success, data);
} catch (e) {
console.error('Error when calling apply function. Error: ' + e);
}
async.getMultiple.prototype.openBarrier_ = null;
b.fire();
};
})(element, barrier, app);
barrier.increment();
async.get(url, appFunc, opt_headers);
}
element = array[0];
barrier.fire();
};
/**
* If a barrier is being accessed then this variable will be set across all
* barriers. That way if a new barrier is created it will know that it needs
* to ensure this one waits until it is done.
*
* Note that this variable is not an array. The reason is that the creation
* of a barrier in getMultiple does not call any user functions therefore no
* nested calls are possible. The only barrier that is of potential concern is
* the one calling the app callback, all the barriers created at that point are
* essentially on the same level and have no interaction.
* @type {?bite.common.utils.Barrier}
* @private
*/
bite.common.net.xhr.async.getMultiple.prototype.openBarrier_ = null;
/**
* The callback that is fired when bite.common.net.xhr.async.get or
* bite.common.net.xhr.async.post request completes.
* @param {EventTarget} event The event.
* @param {?function(boolean, string, number)} callback The callback will be
* fired when the request returns. It will be passed a boolean for the
* success of the request and either the responseText or error message
* respective to that success. The number is the request status. If the
* callback is null then the response is ignored.
* @private
*/
bite.common.net.xhr.async.requestComplete_ = function(event, callback) {
// Ignore response if no callback was supplied.
if (!callback) {
return;
}
var success = false;
var responseText = bite.common.net.xhr.ErrorMessage_.REQUEST_FAILED;
var status = -1;
try {
var xhrIo = event.target;
if (xhrIo.isSuccess()) {
success = true;
responseText = xhrIo.getResponseText() || '';
status = xhrIo.getStatus();
} else {
responseText =
'[' + xhrIo.getLastErrorCode() + '] ' + xhrIo.getLastError();
}
} catch (error) {
responseText = bite.common.net.xhr.ErrorMessage_.EXCEPTION + error;
}
callback(success, responseText, status);
};
/**
* Sends the asynchronous request given well defined inputs.
* @param {string} url See bite.common.net.xhr.async.get.
* @param {?function(boolean, string, number)} callback The callback to be
* fired when the request is complete. Can be null if no callback was
* supplied.
* @param {string} method The method used to send the request.
* @param {string?} data The data to send or null if no data is supplied.
* @param {Object.<string>} headers Optional request headers. Can be null if
* no headers are supplied.
* @private
*/
bite.common.net.xhr.async.send_ = function(url, callback, method, data,
headers) {
if (!url) {
callback && callback(false, bite.common.net.xhr.ErrorMessage_.MISSING_URL,
-1);
return;
}
var localCallback = function(event) {
bite.common.net.xhr.async.requestComplete_(event, callback);
};
try {
goog.net.XhrIo.send(url, localCallback, method, data, headers);
} catch (error) {
var messages = bite.common.net.xhr.ErrorMessage_;
callback && callback(false, messages.EXCEPTION + error, -1);
}
};
/*---------------------------------------------------------------------------*/
/* TODO (jasonstredwick): Code below is outline for refactoring getMultiple. */
/*---------------------------------------------------------------------------*/
/**
* Start a set of asynchronous requests for each element in an array of input
* data. Each element in the array holds the information necessary to send the
* request for itself. Once all the requests have completed, an optional all
* complete callback will be fired given a list of objects containing the
* success and data or potential error message corresponding with the list of
* input data. If the user specifies a handler for an input data element to
* process a completed request then its data upon success will not be recorded
* in the final output list.
*
* To facilitate flexibility the function takes four functions that when
* applied to an input data element will return specific information about that
* element. This information is used to determine the appropriate type of
* request for that element.
*
* @param {Array.<*>} inputData An array of data.
* @param {function(*): string} getUrl A function that when applied to an
* input data element will return a url. If the function returns an empty
* string then that request will be ignored.
* @param {function(*): ?function(boolean, string)} getHandler A function that
* when applied to an input data element will return the a handler to
* process the results of a completed request. If null then no handler
* will be applied to the results and the data will appear in the final
* output. If it is present then the final output will contain an empty
* string.
* @param {function(*): bite.common.net.xhr.Method} getMethod A function that
* when applied to an input data element will return the method to use for
* the request.
* @param {function(*): string} getData A function that when applied to an
* input data element will return the data for the request. If the method
* does not support data then this function will not be called.
* @param {function(Array.<?{success: string, result: string}>)=} opt_complete
* The function to be called once all the requests are completed. The
* function will be passed an array of objects containing the results of
* requests that correspond to the input data list; same order. Skipped
* requests will have null instead of an object.
* @param {number=} opt_max The maximum number of simultaneous requests. If
* not supplied then defaults to all.
*/
/*
bite.common.net.xhr.async.multipleRequests = function(inputData,
getUrl,
getHandler,
getMethod,
getData,
opt_complete,
opt_max) {
var onComplete = opt_complete || null;
var maxAtOnce = opt_max || null;
bite.common.net.xhr.async.sendMultiple_(inputData, getUrl, getHandler,
getMethod, getData, onComplete,
maxAtOnce);
};
*/
/**
* See bite.common.net.xhr.async.multipeRequests for details about the function
* and parameters.
* @param {Array.<*>} inputData An array of data.
* @param {function(*): string} getUrl A function.
* @param {function(*): ?function(boolean, string)} getHandler A function.
* @param {function(*): bite.common.net.xhr.Method} getMethod A function.
* @param {function(*): string} getData A function.
* @param {?function(Array.<?{success: string, result: string}>)} complete
* An optional callback function.
* @param {?number} maxAtOnce The maximum number of simultaneous requests. If
* null then send all at once.
*/
/*
bite.common.net.xhr.async.sendMultiple_ = function(inputData,
getUrl,
getHandler,
getMethod,
getData,
complete) {
};
*/
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Signals provide an event-like procedure for associating
* callbacks to those that have the data needed by those callbacks. Instead of
* the typical event procedure where an object must "be" an event target and
* dispatches multiple event types through a single function. The Signal
* approach allows objects to designate/own only those signals that it creates.
* Then listeners will attach to the specific signal of interest, and are
* called immediately when the signal fires. The signal is meant to offer a
* non-DOM oriented approach that does not include event bubbling or others
* to intercept data being listened to.
*
* Notice that all the public functions are not exported. That is left to the
* user to either export the properties or create an object that maps the
* correct namespace.
*
* Public Interface:
* bite.common.signal.Simple (constructor) - Constructs a new Signal object.
* See constructor documentation for more details.
*
* Public prototype functions for bite.common.signal.Simple:
* addListener - Allows handler functions to be registered for the event
* associated with the Signal object. When the object fires, all
* handlers will be called and passed data in the form of an object.
* hasListener - Determines where or not a handler has been registered.
* removeListener - Allows handlers to be unregistered for an event.
*
* Public prototype functions for bite.common.signal.Simple (only intended to
* be called by the owner):
* clear - Removes all listeners.
* fire - Called by the owning object with specific data. The data is
* then passed to each handler as it is executed.
*
* TODO (jasonstredwick):
* -Decide on a proper namespace now that I have two variants.
* -Figure out if there is a way to decouple the clear/fire functions from
* the addListener, hasListener, and removeListener so only those
* available externally is visible to them.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.signal.Simple');
/**
* Provides a class that can manage a set of unique handler functions that will
* be called when the class is fired. Any callback registered with the
* listener is not modified.
* @constructor
*/
bite.common.signal.Simple = function() {
/**
* Maintain a list of listeners and their related information. Each entry
* contains the callback wrapper and a key for identifying the corresponding
* listener.
* @type {Array.<{handler: function(...[*]), key: function(...[*])}>}
* @private
*/
this.listeners_ = [];
};
/**
* Adds a handler to the managed set unless it is already present.
* @param {function(...[*])} handler The callback to register. This is the
* function that will be called when the signal is fired.
* @param {function(...[*])=} opt_key A function used to identify the
* presence of the handler as a listener instead of the handler itself.
* This can be used in place of storing dynamic functions such as those
* generated by goog.partial.
*/
bite.common.signal.Simple.prototype.addListener = function(handler, opt_key) {
if (!goog.isFunction(handler) || (opt_key && !goog.isFunction(opt_key))) {
return;
}
var key = opt_key || handler;
if (this.getIndex_(key) >= 0) {
return;
}
this.listeners_.push({handler: handler, key: key});
};
/**
* Determines if the handler identified by the given key is in the managed set.
* @param {function(...[*])} key A function used to identify the handler to
* remove. Typically, the key will be the handler itself unless the
* opt_key was given to addListener.
* @return {boolean} Whether or not the handle is present.
*/
bite.common.signal.Simple.prototype.hasListener = function(key) {
if (!goog.isFunction(key)) {
return false;
}
var index = this.getIndex_(key);
return index >= 0;
};
/**
* Removes the handler identified by the given key from the managed set if
* present.
* @param {function(...[*])} key A function used to identify the handler to
* remove. Typically, the key will be the handler itself unless the
* opt_key was given to addListener.
*/
bite.common.signal.Simple.prototype.removeListener = function(key) {
if (!goog.isFunction(key)) {
return;
}
var index = this.getIndex_(key);
if (index < 0) {
return;
}
this.listeners_.splice(index, 1);
};
/**
* Removes all the listeners that are being managed.
*/
bite.common.signal.Simple.prototype.clear = function() {
this.listeners_ = [];
};
/**
* Calls all the listeners managed by this signal and pass on the given data.
* The input to this function will be an arbitrary number of arguments.
* @param {...*} var_args Can take a variable number of arguments or none.
*/
bite.common.signal.Simple.prototype.fire = function(var_args) {
for (var i = 0; i < this.listeners_.length; ++i) {
var handler = this.listeners_[i].handler;
// TODO (jasonstredwick): Determine the security risk of passing an object
// reference instead of a copy/readonly version of the object.
handler.apply(null, arguments);
}
};
/**
* Traverses the list of listeners and returns listener's index that matches
* the given key, or -1 if no match is found.
* @param {function(...[*])} key A function used to identify the handler to
* remove. Typically, the key will be the handler itself unless the
* opt_key was given to addListener.
* @return {number} The matched listener's index or -1.
* @private
*/
bite.common.signal.Simple.prototype.getIndex_ = function(key) {
for (var i = 0; i < this.listeners_.length; ++i) {
if (key == this.listeners_[i].key) {
return i;
}
}
return -1;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.signal.Simple.
*
* Test cases:
* testMultipleListeners
* testBoundListeners
* testSignal
* noListeners
* testBadInputs
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.signal.Simple');
/**
* The signal created and destroyed for each test.
* @type {bite.common.signal.Simple}
*/
var signal = null;
/**
* Sets up the environment for each unit test.
*/
function setUp() {
signal = new bite.common.signal.Simple();
}
/**
* Cleans up the environment for each unit test.
*/
function tearDown() {
signal = null;
}
/**
* Tests the addition of multiple listeners to a signal. The test add five
* listeners to the signal in a specific order and the signal fired. Then
* the listeners are removed in a particular order to ensure that the listeners
* requested for removal are the ones actually removed. The signal is fired
* to test the correct removal.
*/
function testMultipleListeners() {
var counter = 0;
var f1Counter = 0;
var f2Counter = 0;
var f3Counter = 0;
var f4Counter = 0;
var f5Counter = 0;
var f1 = function(obj) { obj.X == 3; ++counter; ++f1Counter; };
var f2 = function(obj) { obj.X == 3; ++counter; ++f2Counter; };
var f3 = function(obj) { obj.X == 3; ++counter; ++f3Counter; };
var f4 = function(obj) { obj.X == 3; ++counter; ++f4Counter; };
var f5 = function(obj) { obj.X == 3; ++counter; ++f5Counter; };
signal.addListener(f1);
signal.addListener(f2);
signal.addListener(f3);
signal.addListener(f4);
signal.addListener(f5);
signal.fire({X: 3});
assertEquals(5, counter);
// Make sure that removing from front, middle, and end will cause the
// correct listeners to be removed.
signal.removeListener(f1);
signal.removeListener(f5);
signal.removeListener(f3);
signal.fire({X: 3});
assertEquals(7, counter);
assertEquals(1, f1Counter);
assertEquals(2, f2Counter);
assertEquals(1, f3Counter);
assertEquals(2, f4Counter);
assertEquals(1, f5Counter);
signal.clear();
signal.fire({X: 3});
assertEquals(7, counter);
}
/**
* Tests adding listeners by key. Each goog.partial should return a unique
* function literal allowing f1 to be added multiple times as a listener.
*/
function testBoundListeners() {
var counter = 0;
var f1 = function(obj) { obj.X == 3 && ++counter; };
var f2 = goog.partial(f1);
var f3 = goog.partial(f1);
signal.addListener(f1);
signal.addListener(f1, f2);
signal.addListener(f1, f3);
signal.fire({X: 3});
assertEquals(3, counter);
assertTrue(signal.hasListener(f1));
assertTrue(signal.hasListener(f2));
assertTrue(signal.hasListener(f3));
signal.removeListener(f1);
signal.fire({X: 3});
assertEquals(5, counter);
signal.removeListener(f2);
signal.removeListener(f3);
signal.fire({X: 3});
assertEquals(5, counter);
}
/**
* Tests the signal object's ability to add and fire listeners. There are
* three listeners that test for different types of inputs: numeric, not
* undefined, and undefined. The not undefined input should take any kind
* of input.
*/
function testSignal() {
var funcXNum = function(data) { assertEquals(data.X, 3); }
var funcNotUndefined = function(data) { assertNotUndefined(data); }
var funcUndefined = function(data) { assertUndefined(data); }
// Test fire with actual values.
signal.addListener(funcXNum);
assertTrue(signal.hasListener(funcXNum));
signal.fire({X: 3});
signal.removeListener(funcXNum);
// Test fire with empty object.
signal.addListener(funcNotUndefined);
assertTrue(signal.hasListener(funcNotUndefined));
signal.fire({});
signal.removeListener(funcNotUndefined);
// Test fire with no object.
signal.addListener(funcUndefined);
assertTrue(signal.hasListener(funcUndefined));
signal.fire();
signal.removeListener(funcUndefined);
}
/**
* Tests the presence and removal of a listener that has not been added.
*/
function noListeners() {
var f = function() {};
try {
signal.hasListener(f);
signal.removeListener(f);
} catch (error) {
fail(error);
}
}
/**
* Tests non-function inputs to addListener, hasListener, removeListener.
*/
function testBadInputs() {
try {
signal.addListener();
signal.addListener(0);
signal.addListener('string');
signal.addListener({x: true});
signal.addListener(null);
signal.addListener(undefined);
signal.hasListener();
signal.hasListener(0);
signal.hasListener('string');
signal.hasListener({x: true});
signal.hasListener(null);
signal.hasListener(undefined);
signal.removeListener();
signal.removeListener(0);
signal.removeListener('string');
signal.removeListener({x: true});
signal.removeListener(null);
signal.removeListener(undefined);
} catch (error) {
fail(error);
}
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.chrome.extension.urlMatching.
*
* Test cases:
* testMatchAll
* testSchemeConversion
* testHostConversion
* testPathConversion
* testBadFormat
* testNoPattern
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.chrome.extension.urlMatching');
/**
* Sets up the environment for each unit test.
*/
function setUp() {}
/**
* Cleans up the environment for each unit test.
*/
function tearDown() {}
/**
* Tests conversion the match all url patterns. Match all does not match
* no url and the scheme must be valid.
*/
function testMatchAll() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
// Match all urls and match all using wild cards gives the same result.
var pattern = '*://*/*';
assertTrue(convert(pattern).test('http://www.google.com/test1'));
pattern = '<all_urls>';
assertTrue(convert(pattern).test('http://www.google.com/test1'));
assertTrue(convert(pattern).test('http://a/b/c/d'));
assertTrue(convert(pattern).test('http://a/b'));
assertTrue(convert(pattern).test('http://a/'));
// Invalid match due to invalid scheme.
assertFalse(convert(pattern).test('other://www.google.com/test1'));
}
/**
* Tests the conversion and validation of scheme components including the
* match all scheme pattern.
*/
function testSchemeConversion() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
// Invalid schemes as they must be one of the valid schemes given in
// bite.common.chrome.extension.urlMatching.Regexp.MATCH_SCHEME_EXPLICIT.
// The star is a valid scheme, but cannot be used in conjunction with any
// text, it must the single star character.
var pattern = 'bhttp://*/*';
assertNull(convert(pattern));
pattern = 'httpb://*/*';
assertNull(convert(pattern));
pattern = 'http*://*/*';
assertNull(convert(pattern));
pattern = 'chrome://*/*';
assertNull(convert(pattern));
pattern = 'other://*/*';
assertNull(convert(pattern));
// Valid explicit schemes; does not include match all scheme pattern.
pattern = 'http://*/*';
assertTrue(convert(pattern).test('http://www.google.com/'));
pattern = 'https://*/*';
assertTrue(convert(pattern).test('https://www.google.com/'));
assertFalse(convert(pattern).test('http://www.google.com/'));
pattern = 'file:///*';
assertTrue(convert(pattern).test('file:///'));
pattern = 'ftp://*/*';
assertTrue(convert(pattern).test('ftp://www.google.com/'));
// Valid match all scheme patterns.
pattern = '*://*/*';
assertTrue(convert(pattern).test('ftp://www.google.com/'));
assertTrue(convert(pattern).test('http://www.google.com/'));
assertTrue(convert(pattern).test('https://www.google.com/'));
// Invalid match all scheme patterns.
pattern = '*://*/*';
assertFalse(convert(pattern).test('other://www.google.com/'));
}
/**
* Tests the conversion and validation of host components including the
* match all pattern. This test examines bad wild card usage. When examining
* proper wild card usage it can match anything that ends with the substring
* following the wild card.
*/
function testHostConversion() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
// Invalid pattern; the match all pattern must be the first character in the
// host pattern if present.
var pattern = '*://www.*/*';
assertNull(convert(pattern));
// Invalid pattern; only a single match all pattern is allowed in the host.
pattern = '*://*.google.*/*';
assertNull(convert(pattern));
// Match an explicit host.
pattern = '*://www.google.com/*';
assertTrue(convert(pattern).test('http://www.google.com/'));
assertFalse(convert(pattern).test('http://maps.google.com/'));
// Match any hosts that ends with '.google.com'.
pattern = '*://*.google.com/*';
assertTrue(convert(pattern).test('http://www.google.com/'));
assertTrue(convert(pattern).test('http://maps.google.com/'));
assertTrue(convert(pattern).test('http://maps.google.google.com/'));
assertFalse(convert(pattern).test('http://maps.com/'));
// Match any host that ends with 'oogle.com'.
pattern = '*://*oogle.com/*';
assertTrue(convert(pattern).test('http://www.google.com/'));
assertTrue(convert(pattern).test('http://maps.google.com/'));
assertTrue(convert(pattern).test('http://www.froogle.com/'));
assertTrue(convert(pattern).test('http://froogle.com/'));
// Match any host.
pattern = '*://*/*';
assertTrue(convert(pattern).test('http://www.google.com/'));
assertTrue(convert(pattern).test('http://a.b.c/'));
assertTrue(convert(pattern).test('http://a/'));
assertFalse(convert(pattern).test('http:///'));
}
/**
* Tests conversion and validation of path components including the match
* all patterns.
*/
function testPathConversion() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
// Match exact path that only matches a single slash.
var pattern = '*://*/';
assertTrue(convert(pattern).test('http://www.google.com/'));
assertFalse(convert(pattern).test('http://www.google.com'));
assertFalse(convert(pattern).test('http://www.google.com/x'));
// Match any path that starts with '/test'.
pattern = '*://*/test*';
assertTrue(convert(pattern).test('http://www.google.com/test'));
assertTrue(convert(pattern).test('http://www.google.com/test/'));
assertTrue(convert(pattern).test('http://www.google.com/test/*'));
assertTrue(convert(pattern).test('http://www.google.com/testing'));
assertTrue(convert(pattern).test('http://www.google.com/test/test1/test'));
// Match any path that starts with a slash and ends with 'test'.
pattern = '*://*/*test';
assertTrue(convert(pattern).test('http://www.google.com/test'));
assertTrue(convert(pattern).test('http://www.google.com/testtest'));
assertTrue(convert(pattern).test('http://www.google.com/footest'));
assertTrue(convert(pattern).test('http://www.google.com/foo/test'));
assertFalse(convert(pattern).test('http://www.google.com/foo/test/'));
// Match any path that starts with a slash and contains 'test'.
pattern = '*://*/*test*';
assertTrue(convert(pattern).test('http://www.google.com/test'));
assertTrue(convert(pattern).test('http://www.google.com/testtest'));
assertTrue(convert(pattern).test('http://www.google.com/footestbar'));
assertTrue(convert(pattern).test('http://www.google.com/foo/test/bar'));
// Match any path that contains a partial path of '/test1/'.
pattern = '*://*/test1/*';
assertFalse(convert(pattern).test('http://www.google.com/test1'));
assertTrue(convert(pattern).test('http://www.google.com/test1/'));
assertTrue(convert(pattern).test('http://www.google.com/test1/foo/bar/x'));
// Match any path bounded by two exact path fragments.
pattern = '*://*/test1/*/test2';
assertFalse(convert(pattern).test('http://www.google.com/test1/test2'));
assertTrue(convert(pattern).test('http://www.google.com/test1/foo/test2'));
assertTrue(convert(pattern).test(
'http://www.google.com/test1/foo/bar/test2'));
// Match any path that begins with a specific path fragment and ends with a
// slash.
pattern = '*://*/test1/*/';
assertTrue(convert(pattern).test('http://www.google.com/test1/foo/'));
assertTrue(convert(pattern).test('http://www.google.com/test1/foo/bar/x/'));
assertFalse(convert(pattern).test('http://www.google.com/test1/'));
// Match a path that begins with a specific path fragment and the pattern
// contains multiple consecutive stars.
pattern = '*://*/test1**';
assertTrue(convert(pattern).test('http://www.google.com/test1'));
assertTrue(convert(pattern).test('http://www.google.com/test1/foo/bar'));
}
/**
* Tests conversion of Chrome Extension match patterns into a RegExp when
* supplied with invalid patterns.
*/
function testBadFormat() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
var pattern = '*'; // Attempt to match everything.
assertNull(convert(pattern));
pattern = '*//*/*'; // Missing ':' after scheme.
assertNull(convert(pattern));
pattern = '*:*/*'; // Missing '//' after scheme.
assertNull(convert(pattern));
pattern = '*:/*/*'; // Missing '/' after scheme.
assertNull(convert(pattern));
pattern = '*://*'; // Missing path.
assertNull(convert(pattern));
pattern = '*:///*'; // Only valid when scheme is file.
assertNull(convert(pattern));
pattern = '*://**/*'; // Second star in host is invalid.
assertNull(convert(pattern));
pattern = '*://*.google.*/*'; // Second star in host is invalid.
assertNull(convert(pattern));
pattern = '*://www.google.*/*'; // Star in host is invalid, must be first
assertNull(convert(pattern)); // character.
pattern = 'file://*/*'; // Host is invalid, file scheme cannot have a host.
assertNull(convert(pattern));
pattern = ' <all_urls>'; // Space before <all_urls> is invalid.
assertNull(convert(pattern));
pattern = '<all_urls> '; // Space after <all_urls> is invalid.
assertNull(convert(pattern));
pattern = '<ALL_URLS>'; // Capitalization invalid, test is case sensitive.
assertNull(convert(pattern));
}
/**
* Tests conversion when given nothing; i.e. undefined, null, and the empty
* string.
*/
function testNoPattern() {
var convert = bite.common.chrome.extension.urlMatching.convertToRegExp;
assertNull(convert(undefined));
assertNull(convert(null));
assertNull(convert(''));
}
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define functions for processing url match patterns as
* specified by the chrome extensions API, see
*
* http://code.google.com/chrome/extensions/match_patterns.html (Oct 2011)
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.chrome.extension.urlMatching');
/**
* Various replacement patterns that are used to covert from extension format
* to RegExp format.
* @enum {string}
*/
bite.common.chrome.extension.urlMatching.MatchPatterns = {
ALL_URLS: '<all_urls>',
MATCH_ALL_HOST: '*',
MATCH_ALL_PATH: '[/]*',
MATCH_ALL_SCHEME: '*',
STAR_HOST: '[^/*]+',
STAR_PATH: '.*',
STAR_SCHEME: '(http|https|file|ftp)'
};
/**
* Various regular expressions for parsing extension match patterns.
* @enum {RegExp}
*/
bite.common.chrome.extension.urlMatching.Regexp = {
ALL_EXPRESSIONS_TRUE: /^<all_urls>$/, // matches everything except no match
CONVERT_HOST: /^[*]/,
CONVERT_PATH_ALL: /([^.])[*]/g,
CONVERT_SCHEME_ALL: /^[*]$/,
MATCH_ALL:
/^([*]|http|https|file|ftp):[/][/]([*]|[*]?[^/*]+)?([/].*)$/,
MATCH_HOST: /^[*]$|^[*]?[^/*]+$/,
MATCH_HOST_ALL: /^[*]$/,
MATCH_PATH: /([/].*)$/,
MATCH_SCHEME: /^([*]|http|https|file|ftp)/,
MATCH_SCHEME_EXPLICIT: /^(http|https|file|ftp)/
};
/**
* Converts the chrome extension match pattern into a RegExp. Can throw an
* exception with an error string.
* @param {string} pattern The extension-based pattern.
* @return {RegExp} Either a RegExp or null if the match is not valid.
*/
bite.common.chrome.extension.urlMatching.convertToRegExp = function(pattern) {
try {
var urlMatching = bite.common.chrome.extension.urlMatching;
var data = null;
if (pattern == urlMatching.MatchPatterns.ALL_URLS) {
data = {
scheme: urlMatching.MatchPatterns.MATCH_ALL_SCHEME,
host: urlMatching.MatchPatterns.MATCH_ALL_HOST,
path: urlMatching.MatchPatterns.MATCH_ALL_PATH
};
} else {
var matches = urlMatching.Regexp.MATCH_ALL.exec(pattern);
if (matches) {
// matches[0] == matched text for the entire expression.
// matches[1..3] correlate to substrings found by the subpatterns in
// MATCH_ALL.
// Note: Subpattern matching will return undefined if not matched.
data = {
scheme: matches[1],
host: matches[2],
path: matches[3]
};
}
}
return urlMatching.formRegExp_(data);
} catch (error) {
throw 'ERROR (bite.common.chrome.extension.urlMatching.convertToRegExp):' +
' Given pattern: ' + pattern + ' - Exception was thrown: ' + error;
}
};
/**
* Converts the piece-wise match patterns from convertToRegExp into a single
* regular expression that will match correct urls, using correct regular
* expression syntax. Can throw an exception when creating a new RegExp. Host
* data is optional since it should be undefined when the scheme is 'file'.
* @param {?{scheme: string, host: string, path: string}} input An object
* containing the components of a match: scheme, host, and path.
* @return {RegExp} A regular expression that captures the match, or null if
* inputs are not valid.
* @private
*/
bite.common.chrome.extension.urlMatching.formRegExp_ = function(input) {
// A valid expression must have a scheme and path.
// If the scheme is not a file then it must have a component.
// If the scheme is file then it cannot have a host component.
if (!input || !input.scheme || !input.path ||
(input.scheme != 'file' && !input.host) ||
(input.scheme == 'file' && input.host)) {
return null;
}
var urlMatching = bite.common.chrome.extension.urlMatching;
// If scheme can be any scheme (*) then convert the scheme match into
// specific valid options as specified in STAR_SCHEME.
var scheme = input.scheme.replace(urlMatching.Regexp.CONVERT_SCHEME_ALL,
urlMatching.MatchPatterns.STAR_SCHEME);
var host = '';
if (input.host) {
if (urlMatching.Regexp.MATCH_HOST_ALL.test(input.host)) {
host = input.host.replace(urlMatching.Regexp.CONVERT_HOST,
urlMatching.MatchPatterns.STAR_HOST);
} else if (urlMatching.Regexp.MATCH_HOST.test(input.host)) {
host = input.host.replace(urlMatching.Regexp.CONVERT_HOST,
urlMatching.MatchPatterns.STAR_HOST);
} else {
return null;
}
}
// Replace consecutive *s with a single * first then replace all *s with
// '.*'. $1 is required to conserve the character before the * otherwise it
// would be stripped out during the replace.
var path = input.path.replace(/[*]+/g, '*');
path = path.replace(urlMatching.Regexp.CONVERT_PATH_ALL,
'$1' + urlMatching.MatchPatterns.STAR_PATH);
return new RegExp('^' + scheme + '://' + host + path + '$');
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for elementhelper.
*
* @author phu@google.com (Po Hu)
*/
goog.require('common.client.ElementDescriptor');
goog.require('goog.testing.MockControl');
goog.require('goog.testing.PropertyReplacer');
var stubs_ = new goog.testing.PropertyReplacer();
var mockControl_ = null;
var chrome = {};
function setUp() {
mockControl_ = new goog.testing.MockControl();
chrome.extension = {};
stubs_.set(goog.global, 'chrome', chrome);
}
function tearDown() {
mockControl_.$tearDown();
mockControl_ = null;
stubs_.reset();
}
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This file contains the element descriptive info
* generator and parser.
*
* @author phu@google.com (Po Hu)
*/
goog.provide('common.client.ElementDescriptor');
goog.require('Bite.Constants');
goog.require('common.dom.querySelector');
goog.require('goog.dom');
goog.require('goog.format.HtmlPrettyPrinter');
goog.require('goog.format.JsonPrettyPrinter');
goog.require('goog.json');
goog.require('goog.string');
/**
* A class for generating and parsing the descriptive info of an element.
* @constructor
* @export
*/
common.client.ElementDescriptor = function() {
/**
* The private console logger.
* @private
*/
this.console_ = goog.global.console;
};
/**
* Gets element based on the given method and value.
* @param {string} method The method to locate an element.
* @param {string} value The value to locate an element.
* @return {Element} The matching element.
* @export
*/
common.client.ElementDescriptor.getElemBy = function(method, value) {
var doc = goog.dom.getDocument();
try {
switch (method) {
case 'xpath':
return doc.evaluate(
value, doc, null, XPathResult.ANY_TYPE, null).iterateNext();
case 'id':
return goog.dom.getElement(value);
case 'linktext':
return doc.evaluate(
'//a[text()="' + value + '"]', doc,
null, XPathResult.ANY_TYPE, null).iterateNext();
case 'class':
return doc.querySelector('.' + value);
case 'name':
return doc.getElementsByName(value)[0];
case 'selector':
return doc.querySelector(value);
}
} catch (e) {
console.log('Error: ' + e.message);
return null;
}
};
/**
* Generates the css selector path of an element.
* @param {!Node} elem The element object.
* @return {string} The selector string.
* @export
*/
common.client.ElementDescriptor.prototype.generateSelectorPath = function(
elem) {
var selector = '';
try {
selector = common.dom.querySelector.getSelector(elem);
} catch (e) {
console.log('Failed to generate the selector path.');
}
return selector;
};
/**
* Generates the css selector of an element.
* @param {Element} elem The element object.
* @return {string} The selector string.
* @export
*/
common.client.ElementDescriptor.prototype.generateSelector = function(elem) {
var curElem = elem;
var selector = this.generateSelector_(curElem);
while (!this.isSelectorUnique_(elem, selector)) {
curElem = curElem.parentNode;
if (curElem == document || curElem.tagName.toLowerCase() == 'html') {
break;
}
selector = this.generateSelector_(curElem) + '>' + selector;
}
return selector;
};
/**
* Generates the xpath of an element based on user specified attribute array.
* @param {Element} elem The element object.
* @param {Object.<string, Object>} ancestorAttrs The key is the ancestor
* elements' attribute and the value is an object which contains the
* attribute's value and whether the value should be exact or contained.
* @param {Object.<string, Object>} elementAttrs Refers to the ancestorAttrs,
* the difference is that this object contains the selected element's
* attributes.
* @return {string} The xpath string.
* @export
*/
common.client.ElementDescriptor.prototype.generateXpath = function(
elem, ancestorAttrs, elementAttrs) {
var curElem = elem;
var doc = goog.dom.getDocument();
var xpath = this.generateXpath_(curElem, elementAttrs);
var notUnique = false;
// Loops to check if the xpath matches a unique element.
while (curElem.tagName.toLowerCase() != 'body' &&
(notUnique = !this.isXpathUnique_(elem, '//' + xpath))) {
curElem = curElem.parentNode;
xpath = this.generateXpath_(curElem, ancestorAttrs) + '/' + xpath;
}
if (notUnique) {
return 'Error (please check the developer console for xpath)';
} else {
return '//' + xpath;
}
};
/**
* Generates the xpath of an element based on user specified attribute array.
* @param {Node} elem The element object.
* @param {Object.<string, Object>} attrs Refers to the generateXpath's doc.
* @return {string} The xpath string.
* @private
*/
common.client.ElementDescriptor.prototype.generateXpath_ = function(
elem, attrs) {
var attrXpath = '';
for (var attr in attrs) {
var text = '';
var isExact = true;
if (!attrs[attr]) {
// Assume if the value is null, then it needs dynamically get the
// attribute value and assume it should be exact match.
text = attr == 'text' ?
goog.dom.getTextContent(/** @type {Node} */ (elem)) :
elem.getAttribute(attr);
} else {
text = attrs[attr]['value'];
isExact = attrs[attr]['isExact'];
}
if (attr == 'text') {
if (isExact) {
attrXpath += ('[text()="' + text + '"]');
} else {
attrXpath += ('[contains(text(),"' + text + '")]');
}
} else {
if (text) {
if (isExact) {
attrXpath += ('[@' + attr + '="' + text + '"]');
} else {
attrXpath += ('[contains(@' + attr + ',"' + text + '")]');
}
}
}
}
// If the xpath with attribute matches unique element, no need to
// append the node index info.
if (this.isXpathUnique_(
/** @type {Element} */ (elem), '//' + elem.tagName + attrXpath)) {
return elem.tagName + attrXpath;
}
var children = [];
var prefix = '';
if (elem.parentNode) {
children = goog.dom.getChildren(/** @type {Element} */ (elem.parentNode));
for (var i = 0, j = 0, len = children.length; i < len; ++i) {
if (children[i].tagName == elem.tagName) {
++j;
if (children[i].isSameNode(elem)) {
prefix = elem.tagName + '[' + j + ']';
}
}
}
}
return prefix + attrXpath;
};
/**
* The relatively stable attributes.
* @private
*/
common.client.ElementDescriptor.elemAttr_ = ['name', 'class', 'title'];
/**
* Generates the css selector of an element.
* @param {Node} elem The element object.
* @return {string} The selector string.
* @private
*/
common.client.ElementDescriptor.prototype.generateSelector_ = function(elem) {
var selector = '';
var children = [];
var attrSelector = '';
var attrs = common.client.ElementDescriptor.elemAttr_;
if (elem.getAttribute('id')) {
return elem.tagName + '#' + elem.getAttribute('id');
}
for (var i = 0, len = attrs.length; i < len; i++) {
var value = elem.getAttribute(attrs[i]);
if (value) {
attrSelector += ('[' + attrs[i] + '="' + value + '"]');
}
}
if (elem.parentNode) {
children = goog.dom.getChildren(/** @type {Element} */ (elem.parentNode));
var j = 0;
for (var i = 0, len = children.length; i < len; i++) {
if (children[i].tagName == elem.tagName) {
j += 1;
if (children[i].isSameNode(elem)) {
selector = elem.tagName + ':nth-of-type(' + j + ')';
}
}
}
}
return selector + attrSelector;
};
/**
* Tests if the selector is unique for the given elem.
* @param {Element} elem The element object.
* @param {string} selector The selector string.
* @return {boolean} Whether the selector is unique.
* @private
*/
common.client.ElementDescriptor.prototype.isSelectorUnique_ = function(
elem, selector) {
var elems = null;
try {
elems = goog.dom.getDocument().querySelectorAll(selector);
} catch (e) {
console.log('Failed to find elements through selector ' + selector);
return false;
}
return elems && elems.length == 1 && elem.isSameNode(elems[0]);
};
/**
* Tests if the xpath is unique for the given elem.
* @param {Element} elem The element object.
* @param {string} xpath The xpath string.
* @return {boolean} Whether the xpath is unique.
* @private
*/
common.client.ElementDescriptor.prototype.isXpathUnique_ = function(
elem, xpath) {
try {
var doc = goog.dom.getDocument();
var elems = null;
elems = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null);
var firstR = elems.iterateNext();
var secondR = elems.iterateNext();
return firstR && !secondR && elem.isSameNode(firstR);
} catch (e) {
throw new Error('Failed to find elements through xpath ' + xpath);
}
};
/**
* Gets all of the elements by a given xpath.
* @param {string} xpath The xpath string.
* @return {!Array.<Element>} The elements that match the given xpath.
* @private
*/
common.client.ElementDescriptor.prototype.getAllElementsByXpath_ = function(
xpath) {
var elements = [];
try {
var doc = goog.dom.getDocument();
var elems = null;
var temp = null;
elems = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null);
while (temp = elems.iterateNext()) {
elements.push(temp);
}
return elements;
} catch (e) {
console.log('Failed to find elements through xpath ' + xpath);
return [];
}
};
/**
* Generates the descriptor of an element.
* @param {Element} elem The element object.
* @param {number} propagateTimes The number of ancestors to collect.
* @param {boolean} opt_Optimized Whether use optimized alogrithm.
* @return {string} An string of the descriptive info of an element.
* @export
*/
common.client.ElementDescriptor.prototype.generateElementDescriptor =
function(elem, propagateTimes, opt_Optimized) {
var opt = true;
if (opt_Optimized == false) {
opt = false;
}
var descriptor = goog.json.serialize(this.generateElementDescriptor_(
elem, propagateTimes, opt));
var printer = new goog.format.JsonPrettyPrinter(null);
return printer.format(descriptor);
};
/**
* Generates an element descriptor including all necessary info.
* @param {Node} elem The HTML element.
* @param {number} propagateTimes The number of ancestors to collect.
* @param {boolean} opt Whether to use optimized algorithm.
* @return {Object} Element descriptor object.
* @private
*/
common.client.ElementDescriptor.prototype.generateElementDescriptor_ =
function(elem, propagateTimes, opt) {
if (!elem) {
return null;
}
var descriptor = {};
descriptor.tagName = elem.tagName;
descriptor.elementText = this.fixStr(this.getText(elem), opt);
this.addImplicitAttrs_(descriptor, /** @type {Element} */ (elem));
var attrs = elem.attributes;
var attrsLen = 0;
if (attrs) {
attrsLen = attrs.length;
}
if (attrsLen) {
descriptor.attributes = {};
}
for (var i = 0; i < attrsLen; i++) {
descriptor.attributes[attrs[i].name] = this.fixStr(attrs[i].value, opt);
}
descriptor.optimized = opt;
if (elem.parentNode && propagateTimes) {
descriptor.parentElem = this.generateElementDescriptor_(
elem.parentNode, propagateTimes - 1, opt);
} else {
descriptor.parentElem = null;
}
return descriptor;
};
/**
* Adds implicit attributes of the given element to descriptor.
* @param {Object} descriptor The descriptor object for the given element.
* @param {Element} elem The HTML element.
* @private
*/
common.client.ElementDescriptor.prototype.addImplicitAttrs_ =
function(descriptor, elem) {
if (!elem || !elem['tagName']) {
return;
}
var tagNameUpper = elem['tagName'].toUpperCase();
switch (tagNameUpper) {
case goog.dom.TagName.SELECT:
descriptor['selectedIndex'] = elem.selectedIndex + '';
break;
case goog.dom.TagName.INPUT:
if (elem['type']) {
var typeLower = elem['type'].toLowerCase();
if (typeLower == 'radio' || typeLower == 'checkbox') {
descriptor['checked'] = elem.checked + '';
} else if (typeLower == 'button' || typeLower == 'submit') {
descriptor['disabled'] = elem.disabled + '';
}
}
break;
case goog.dom.TagName.BUTTON:
descriptor['disabled'] = elem.disabled + '';
break;
}
};
/**
* Adds implicit attributes score.
* @param {Object} descriptor The descriptor object for the given element.
* @param {Element} elem The element to be compared.
* @return {number} The score.
* @private
*/
common.client.ElementDescriptor.prototype.addImplicitAttrsScore_ =
function(descriptor, elem) {
var score = 0;
if (descriptor['disabled']) {
score += this.getFieldScore_(descriptor['disabled'], elem.disabled + '');
}
if (descriptor['checked']) {
score += this.getFieldScore_(descriptor['checked'], elem.checked + '');
}
if (descriptor['selectedIndex']) {
score += this.getFieldScore_(descriptor['selectedIndex'],
elem.selectedIndex + '');
}
return score;
};
/**
* Parses the element descriptor and gets the potential element(s).
* @param {string} descriptorStr The descriptive info string of an element.
* @param {boolean=} opt_all Whether returns all of the results.
* @return {Object} Found element(s).
* @export
*/
common.client.ElementDescriptor.prototype.parseElementDescriptor =
function(descriptorStr, opt_all) {
var document_ = document;
var result = this.parseElementDescriptor_(descriptorStr, document_, opt_all);
return result['elems'] ? result :
{'elems': null, 'matchHtmls': 'Attribute validation failed.'};
};
/**
* Parses an element descriptor string and returns all the found elements.
* @param {string|Object} descriptorStrOrObj The descriptive info of an elem.
* @param {Object} document_ The document object (could be from a frame).
* @param {boolean=} opt_all Whether returns all of the results.
* @return {Object.<Element|Array,string|Array>}
* An element or a group of elements.
* @private
*/
common.client.ElementDescriptor.prototype.parseElementDescriptor_ =
function(descriptorStrOrObj, document_, opt_all) {
var descriptor = {};
if (typeof(descriptorStrOrObj) == 'string') {
descriptor = goog.json.parse(descriptorStrOrObj);
} else {
descriptor = descriptorStrOrObj;
}
var tag = descriptor['tagName'];
if (typeof(tag) != 'string') {
tag = tag['value'];
}
var elemsStart = document_.getElementsByTagName(tag);
var desc = descriptor;
var elems = elemsStart;
var matchHtmls = [];
var rtnObj = {};
var level = 0;
while (elems.length >= 1 && desc) {
rtnObj = this.parse_(
elems, /** @type {Object} */ (desc), level, matchHtmls);
elems = rtnObj['elems'];
matchHtmls = rtnObj['matchHtmls'];
if (desc['parentElem']) {
desc = desc['parentElem'];
} else {
desc = null;
}
level += 1;
}
if (elems.length == 0) {
return {'elems': null, 'matchHtmls': matchHtmls};
}
if (opt_all) {
return {'elems': elems, 'matchHtmls': matchHtmls};
} else {
return {'elems': elems[0], 'matchHtmls': matchHtmls[0]};
}
};
/**
* Deals with the back compatibility issue.
* @param {Object} descriptor The descriptor object.
* @param {boolean} opt Whether is optimized.
* @param {Element|Node} elem The element object.
* @return {number} The score got from back compat.
* @private
*/
common.client.ElementDescriptor.prototype.getBackCompat_ =
function(descriptor, opt, elem) {
var attrs = [];
var newKeyWords = {'tagName': 1, 'elementText': 1,
'parentElem': 1, 'optimized': 1,
'attributes': 1};
var score = 0;
var elemKey = '';
for (var key in descriptor) {
if (key in newKeyWords) {
continue;
}
elemKey = key;
if (key == 'class_') {
elemKey = 'class';
}
var attr = this.getAttr_(elem, elemKey);
if (attr) {
if (descriptor[key] == this.fixStr(attr['value'], opt)) {
score++;
}
}
}
return score;
};
/**
* Parses the element descriptor and return the possible elements.
* @param {Array} elems An array of elements.
* @param {Object} descriptor The descriptor object of an element.
* @param {number} level The level of ancestor.
* @param {Array} matchHtmls The matching htmls array.
* @return {Object} An object of found elements.
* @private
*/
common.client.ElementDescriptor.prototype.parse_ =
function(elems, descriptor, level, matchHtmls) {
var rtnArry = [];
var rtnMatchInfoArry = [];
var topScore = 0;
for (var i = 0; i < elems.length; i++) {
var elem = this.getAncestor_(elems[i], level);
var matchInfoHtml = '';
if (!elem) {
continue;
}
var scoreTotal = 0;
scoreTotal += this.getFieldScore_(descriptor['tagName'], elem.tagName);
matchInfoHtml += this.getColoredHtml_('<', 'green');
matchInfoHtml += this.getAttrHtml_(descriptor['tagName'], elem.tagName);
var opt = descriptor['optimized'];
scoreTotal += this.getFieldScore_(descriptor['elementText'],
this.fixStr(this.getText(elem), opt));
scoreTotal += this.addImplicitAttrsScore_(
descriptor, /** @type {Element} */ (elem));
var attrs = descriptor.attributes;
for (var key in attrs) {
var attr = elem.attributes.getNamedItem(key);
scoreTotal += this.getFieldScore_(
attrs[key], this.fixStr(attr ? attr.value : '', opt));
matchInfoHtml += this.getColoredHtml_(' ' + key + '="', 'green');
matchInfoHtml += this.getAttrHtml_(attrs[key],
this.fixStr(attr ? attr.value : '', opt));
matchInfoHtml += this.getColoredHtml_('"', 'green');
}
matchInfoHtml += this.getColoredHtml_('>', 'green');
if (!level) {
matchInfoHtml += '<br>' + this.getAttrHtml_(descriptor['elementText'],
this.fixStr(this.getText(elem), opt));
}
if (!attrs) {
var backCompatScore = this.getBackCompat_(descriptor, opt, elem);
scoreTotal += backCompatScore;
}
if (scoreTotal < 0) {
continue;
}
if (rtnArry[0]) {
if (topScore < scoreTotal) {
rtnArry = [];
rtnMatchInfoArry = [];
topScore = scoreTotal;
} else if (topScore > scoreTotal) {
continue;
}
} else {
topScore = scoreTotal;
}
rtnArry.push(elems[i]);
if (matchHtmls && matchHtmls.length > i) {
matchInfoHtml += '<br>' + matchHtmls[i];
}
rtnMatchInfoArry.push(matchInfoHtml);
}
return {'elems': rtnArry, 'matchHtmls': rtnMatchInfoArry};
};
/**
* Gets an attribute of an Element.
* @param {Object} elem The HTML object.
* @param {string} attrName The attribute name.
* @return {string} The specified attribute of the element.
* @private
*/
common.client.ElementDescriptor.prototype.getAttr_ = function(
elem, attrName) {
return elem.attributes.getNamedItem(attrName);
};
/**
* Trims a given string.
* @param {string} stringToTrim The string to be trimmed.
* @return {string} The trimmed string.
* @export
*/
common.client.ElementDescriptor.prototype.trim = function(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, '');
};
/**
* Checks if the given string has unicode in it.
* @param {string} str The string to be checked.
* @return {boolean} Whether the string contains unicode.
* @export
*/
common.client.ElementDescriptor.prototype.isUnicode = function(str) {
for (var i = 0; i < str.length; i++) {
if (str[i].charCodeAt() > 127) {
return true;
}
}
return false;
};
/**
* Gets text from an element.
* @param {Object} node The HTML element.
* @return {string} The displayed text.
* @export
*/
common.client.ElementDescriptor.prototype.getText = function(node) {
var rtnText = '';
// TODO(phu): Examine the use of test versions to determine how to process
// text nodes. Removed solution examined the browser version, but should
// use test related information.
rtnText = this.trim(goog.dom.getTextContent(/** @type {Node} */ (node)));
return rtnText;
};
/**
* Optimizes the way of collecting text.
* @param {string} text The given text.
* @param {boolean} opt Whether to use optimized algorithm.
* @return {string} The optimized text.
* @export
*/
common.client.ElementDescriptor.prototype.fixStr = function(text, opt) {
var isAsciiStr = true;
try {
isAsciiStr = !this.isUnicode(text);
} catch (e) {
console.log('Error occured in fixStr: ' + e.message);
}
if (opt && isAsciiStr) {
return this.getSimpleAscii(text);
} else {
return text;
}
};
/**
* Replaces the original string with a pure Ascii simple one.
* @param {string} text The given text.
* @return {string} A pure Ascii text.
* @export
*/
common.client.ElementDescriptor.prototype.getSimpleAscii = function(text) {
var maxLen = 20; //experiment with length
text = text.replace(/\W+/g, '');
var textStarts = text.length > maxLen ? text.length - maxLen : 0;
return text.substring(textStarts);
};
/**
* Gets the value and score of an element.
* @param {string|Object} value The value string or object.
* @return {Array} Value and score array.
* @private
*/
common.client.ElementDescriptor.prototype.getValueAndScore_ =
function(value) {
var rtnValue = '';
var rtnScore = 1;
if (typeof(value) == 'string') {
rtnValue = value;
} else {
rtnValue = value['value'];
if (value['score']) {
rtnScore = value['score'];
}
if (value['show'] == 'ignore') {
rtnValue = '';
rtnScore = 0;
}
}
return [rtnValue, rtnScore];
};
/**
* Gets the score.
* @param {string | Object} value The value string or object.
* @param {string} domValue The dom element's value string.
* @return {number} The corresponding score.
* @private
*/
common.client.ElementDescriptor.prototype.getFieldScore_ =
function(value, domValue) {
if (value) {
var result = this.getValueAndScore_(value);
var backCompatValue = this.getSimpleAscii(domValue);
if (result[0] == domValue || result[0] == backCompatValue) {
return result[1];
} else {
if (value['show'] && value['show'] == 'must') {
return -999; //As long as this could make the total score negative.
}
return 0;
}
}
return 0;
};
/**
* Gets the colored attribute.
* @param {string | Object} value The value string or object.
* @param {string} domValue The dom element's value string.
* @return {string} The corresponding html.
* @private
*/
common.client.ElementDescriptor.prototype.getAttrHtml_ =
function(value, domValue) {
if (value) {
var result = this.getValueAndScore_(value);
if (result[0] == domValue) {
return this.getColoredHtml_(result[0], 'green');
} else {
return this.getColoredHtml_(result[0], 'red') +
this.getColoredHtml_(' (' + domValue + ')', 'black');
}
}
return '';
};
/**
* Gets the ancestor at a given level.
* @param {Element} elem The element.
* @param {number} level The level of an ancestor.
* @return {Element|Node} The ancestor element.
* @private
*/
common.client.ElementDescriptor.prototype.getAncestor_ =
function(elem, level) {
if (!elem) {
return null;
}
var rtnElem = elem;
for (var i = 0; i < level; i++) {
rtnElem = rtnElem.parentNode;
if (!rtnElem) {
return null;
}
}
return rtnElem;
};
/**
* Returns a colored html string.
* @param {string} text The dom element's value string.
* @param {string} color The color string.
* @return {string} The colored html string.
* @private
*/
common.client.ElementDescriptor.prototype.getColoredHtml_ =
function(text, color) {
return '<span style="color:' + color + '">' + text + '</span>';
};
/**
* The element descriptor instance.
* @export
*/
var elemDescriptor = new common.client.ElementDescriptor();
/**
* Express function for parsing an element.
* @param {string} descriptor The descriptive info object of an element.
* @param {boolean=} opt_all Whether returns all of the results.
* @return {Element} The found element.
* @export
*/
function parseElementDescriptor(descriptor, opt_all) {
if (typeof descriptor == 'string') {
try {
goog.json.parse(descriptor);
} catch (e) {
return null;
}
}
var rtnObj = elemDescriptor.parseElementDescriptor(descriptor, opt_all);
var rtn = rtnObj['elems'];
var matchHtml = rtnObj['matchHtmls'];
chrome.extension.sendRequest(
{command: 'setLastMatchHtml', html: matchHtml});
return rtn;
}
/**
* Instance of the ElementDescriptor class.
* @type {common.client.ElementDescriptor}
* @export
*/
common.client.ElementDescriptor.instance =
new common.client.ElementDescriptor();
/**
* Parses the command and make it runnable.
* @param {Object} elemMap The element map.
* @param {string} method The method of getting the element.
* @return {Object} The element that was found and a log.
* @export
*/
common.client.ElementDescriptor.getElement = function(elemMap, method) {
// TODO(phu): Use all the data in elemMap like css selector to find the
// best match.
var xpath = elemMap['xpaths'][0];
var log = 'Cannot find the element whose xpath is ' + xpath +
' (Recommend to update it).';
if (method == 'xpath') {
console.log('Uses xpath to find element: ' + xpath);
return {'elem': common.client.ElementDescriptor.getElemBy(method, xpath),
'log': log};
}
return {'elem': parseElementDescriptor(elemMap['descriptor']),
'log': log};
};
/**
* @export
*/
common.client.ElementDescriptor.runnable = '';
/**
* Parses the command and make it runnable.
* @param {string} cmd The command string.
* @return {string} The runnable puppet code.
* @export
*/
common.client.ElementDescriptor.parseCommandToRunnable = function(cmd) {
if (goog.string.startsWith(cmd, 'run(')) {
var result = cmd.replace('run(', 'BiteRpfAction.');
return result.replace(', ', '(');
} else {
return 'BiteRpfAction.' + cmd;
}
};
/**
* Parses the element descriptor and return the possible elements.
* @param {string} description A string describing an element.
* @return {?Element} The found element(s).
* @export
*/
common.client.ElementDescriptor.parseElementDescriptor = function(
description) {
try {
var result = parseElementDescriptor(description);
if (typeof result == 'string') {
return null;
} else {
return result;
}
} catch (error) {
console.log('ERROR (common.client.ElementDescriptor.' +
'parseElementDescriptor): An exception was thrown for input ' +
'- ' + description + '. Returning null.');
}
};
/**
* Generates the descriptor of an element.
* @param {Element} elem The element object.
* @return {string} A string of the descriptive info of an element.
* @export
*/
common.client.ElementDescriptor.generateElementDescriptor = function(elem) {
return common.client.ElementDescriptor.instance.generateElementDescriptor(
elem, 0, true);
};
/**
* Generates the descriptor of an element, with specified number of ancestors.
* @param {Element} elem The element object.
* @param {number} ancestors The number of element ancestors to go up.
* @return {string} A string of the descriptive info of an element.
* @export
*/
common.client.ElementDescriptor.generateElementDescriptorNAncestors = function(
elem, ancestors) {
return common.client.ElementDescriptor.instance.generateElementDescriptor(
elem, ancestors, true);
};
/**
* Generates the outerHTML of selected element.
* @param {Element} elem The element object.
* @return {string} A string of the outerHTML of an element.
* @export
*/
common.client.ElementDescriptor.generateOuterHtml = function(elem) {
if (!elem) {
return '';
}
var outerHtmlString = goog.dom.getOuterHtml(elem);
outerHtmlString = goog.format.HtmlPrettyPrinter.format(outerHtmlString);
return outerHtmlString;
};
/**
* Gets all of the attributes of the given element.
* @param {Element} elem The element object.
* @return {Array} An array of the attributes.
* @export
*/
common.client.ElementDescriptor.getAttributeArray = function(elem) {
if (!elem) {
return [];
}
var attributes = [];
var temp = {};
temp['name'] = 'text';
temp['value'] = goog.dom.getTextContent(/** @type {Node} */ (elem));
attributes.push(temp);
var attrs = elem.attributes;
var attrsLen = attrs ? attrs.length : 0;
for (var i = 0; i < attrsLen; ++i) {
temp = {};
temp['name'] = attrs[i].name;
temp['value'] = attrs[i].value;
attributes.push(temp);
}
return attributes;
};
/**
* Puts the "must" attribute/value based on the given object.
* @param {string} key The attribute's name.
* @param {string|Object} value The attribute's value.
* @param {Object} result The result containing all the attribute name
* and value pairs.
* @param {Function=} opt_process The optional function to process the value.
* @export
*/
common.client.ElementDescriptor.getAttrValue = function(
key, value, result, opt_process) {
if (!value) {
return;
}
if (typeof(value) == 'object') {
if (value['show'] && value['show'] == 'must') {
var temp = value['value'];
if (opt_process) {
temp = opt_process(temp);
}
result[key] = temp;
}
}
};
/**
* Gets the "must" attributes/values as an object.
* @param {string|Object} descriptor The descriptor string or object.
* @param {Function=} opt_process The optional function to process the value.
* @return {Object} An object of the attributes/values need to verify.
* @export
*/
common.client.ElementDescriptor.getAttrsToVerify = function(
descriptor, opt_process) {
if (typeof(descriptor) == 'string') {
descriptor = goog.json.parse(descriptor);
}
var result = {};
var specialAttrs = ['tagName', 'elementText', 'checked', 'disabled',
'selectedIndex'];
for (var i = 0, len = specialAttrs.length; i < len; ++i) {
common.client.ElementDescriptor.getAttrValue(
specialAttrs[i], descriptor[specialAttrs[i]], result, opt_process);
}
var attributes = descriptor['attributes'];
for (var name in attributes) {
common.client.ElementDescriptor.getAttrValue(
name, attributes[name], result, opt_process);
}
return result;
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides functionality related to DOM elements.
*
* @author ralphj@google.com (Julie Ralph)
* @author jason.stredwick@gmail.com (Jason Stredwick)
*/
goog.provide('common.dom.element');
goog.require('goog.style');
/**
* Returns the position of the element.
* @param {!Element} element The element to access.
* @return {!{x: number, y: number}} The position of the element.
*/
common.dom.element.getPosition = function(element) {
return goog.style.getPosition(element);
};
/**
* Returns the size of the element.
* @param {!Element} element The element to access.
* @return {!{width: number, height: number}} The dimensions of the element.
*/
common.dom.element.getSize = function(element) {
return goog.style.getSize(element);
};
/**
* Set the position of the element.
* @param {!Element} element The element to access.
* @param {!{x: number, y: number}} position The new position.
*/
common.dom.element.setPosition = function(element, position) {
goog.style.setPosition(element, position.x, position.y);
};
/**
* Set the size of the element.
* @param {!Element} element The element to access.
* @param {!{width: number, height: number}} size The new size.
*/
common.dom.element.setSize = function(element, size) {
goog.style.setSize(element, size.width, size.height);
};
| JavaScript |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The Simple class defines a type of log class to store and
* retrieve units of information in string form. Each new entry is assigned a
* timestamp and stored in order. Internally a queue exists where new entries
* enter one side and old entries drop off the other, but only when the maximum
* is reach. The class also has a few different methods of retrieving log
* information from a iterator-like function to allowing listeners to register
* and be signalled whenever a new entry is logged.
*
* The purpose of the Simple log class is to provide a method of recording
* information without specifying an output source. Other JavaScript code can
* then tap into the log to retrieve information and output it to the
* appropriate location.
*
* Notice that all the public functions are not exported. That is left to the
* user to either export the properties or create an object that maps to the
* correct namespace.
*
* Public Interface:
* bite.common.log.Simple(opt_maxEntries) (constructor) - Constructs a Simple
* log object. See the file overview for more details.
*
* Public prototype functions for bite.common.log.Simple:
* add(string) - Add a new entry (string) to the log.
* clear() - Clear the log; removes all current log entries.
* getNewestEntry() - Returns the newest entry or null if there are no
* entries.
* getMaxEntries() - Returns the maximum number of entries the log can hold.
* setMaxEntries(newMaxEntries) - Changes the maximum number of entries the
* log can support.
*
* addListener(callback) - Add a new listener to the log that will be
* notified when new entries are added.
* hasListener(callback) - Returns whether or not the given callback is
* currently a listener on this log.
* removeListener(callback) - Removes the given callback as a listener on
* this log.
*
* getIterNewToOld() - Get a function that iterates over the log entries from
* newest to oldest.
* getIterOldToNew() - Get a function that iterates over the log entries from
* oldest to newest.
*
* Usage:
* var keyName = bite.common.log.Simple.KeyName;
* var callback = function(entry) { console.log(entry[keyName.VALUE]); }
*
* var log = new bite.common.log.Simple();
*
* log.addListener(callback);
* log.add('entry1'); // Console will display 'entry1' due to callback.
* log.add('entry2'); // Console will display 'entry2' due to callback.
*
* var entry = log.getNewestEntry();
* console.log(entry[keyName.VALUE]); // Console will display 'entry2'.
*
* var iter = log.getIterOldToNew();
* // Console will display 'entry1' then 'entry2'.
* while (entry = iter()) {
* console.log(entry[keyName.VALUE]);
* }
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.log.Simple');
goog.require('bite.common.signal.Simple');
goog.require('goog.date.Date');
/**
* Constructs a new Simple log object that can store strings with a timestamp.
* @param {number=} opt_maxEntries The number of entries the log can store
* before entries are dropped.
* @constructor
*/
bite.common.log.Simple = function(opt_maxEntries) {
/**
* The maximum number of entries the log can hold before it will start
* dropping old entries.
* @type {number}
* @private
*/
this.maxEntries_ = opt_maxEntries && opt_maxEntries > 0 ? opt_maxEntries :
bite.common.log.Simple.DEFAULT_MAX_ENTRIES;
/**
* An array of entries.
* @type {!Array.<!bite.common.log.Simple.Entry>}
* @private
*/
this.entries_ = [];
/**
* A signal object used to track those who want to listen to the log as it
* is created and signal when it has changed.
* @type {!bite.common.signal.Simple}
* @private
*/
this.signal_ = new bite.common.signal.Simple();
};
/**
* For each entry, the timestamp is an integer in milliseconds. Also, each
* entry will be explicit strings for uses external to this code.
* @typedef {{timestamp: number, value: string}}
*/
bite.common.log.Simple.Entry;
/**
* The default maximum number of entries the log can contain.
* @type {number}
*/
bite.common.log.Simple.DEFAULT_MAX_ENTRIES = 10000;
/**
* Key names for the entry object.
* @enum {string}
*/
bite.common.log.Simple.KeyName = {
TIMESTAMP: 'timestamp',
VALUE: 'value'
};
/**
* Add a new entry to the log. The entry will be timestamped using
* Date.getTime.
* @param {string} value The string to log.
*/
bite.common.log.Simple.prototype.add = function(value) {
var time;
try {
time = new goog.date.Date().getTime();
} catch (error) {
time = -1;
}
// Make sure there is room in the queue.
if (this.entries_.length + 1 > this.maxEntries_) {
this.entries_.shift();
}
// Preserve the key names for external use.
var entry = {};
entry[bite.common.log.Simple.KeyName.TIMESTAMP] = time;
entry[bite.common.log.Simple.KeyName.VALUE] = value;
this.entries_.push(entry);
// Let listeners know a new entry was logged.
this.signal_.fire(entry);
};
/**
* Adds a callback to the log's bite.common.signal.Simple object, which will be
* fired when a new entry is added.
* @param {function(!bite.common.log.Simple.Entry)} callback The callback to be
* fired.
*/
bite.common.log.Simple.prototype.addListener = function(callback) {
this.signal_.addListener(/** @type {function(...[*])} */ (callback));
};
/**
* Clear the log.
*/
bite.common.log.Simple.prototype.clear = function() {
this.entries_ = [];
};
/**
* Creates the iterator function used by getIterNew and getIterOld. The
* function returned will move through the array of entries and will return
* null when it has passed the Array boundary.
* @param {number} index The index to start with.
* @param {number} delta How many entries to move forward when the iterator is
* called.
* @return {function(): bite.common.log.Simple.Entry} A function that acts like
* an iterator over the log.
* @private
*/
bite.common.log.Simple.prototype.getIterFunc_ = function(index, delta) {
var iter = goog.partial(function(entries) {
if (index < 0 || index >= entries.length) {
index = -1;
return null;
}
var data = entries[index];
index += delta;
return data;
}, this.entries_);
return iter;
};
/**
* Returns a function that starts at the newest entry and when called will
* return the current entry and move to the next entry. When the last entry is
* reached the function will start returning null. If changes to the state of
* the log occur while this function exists then it can alter its behavior
* though it will never recover once the end of the list is reached.
* @return {function(): bite.common.log.Simple.Entry} A function that acts like
* an iterator over the log from newest to oldest.
*/
bite.common.log.Simple.prototype.getIterNewToOld = function() {
return this.getIterFunc_(this.entries_.length - 1, -1);
};
/**
* Returns a function that starts at the oldest entry and when called will
* return the current entry and move to the next entry. When the last entry is
* reached the function will start returning null. If changes to the state of
* the log occur while this function exists then it can alter its behavior
* though it will never recover once the end of the list is reached.
* @return {function(): bite.common.log.Simple.Entry} A function that acts like
* an iterator over the log from oldest to newest.
*/
bite.common.log.Simple.prototype.getIterOldToNew = function() {
return this.getIterFunc_(0, 1);
};
/**
* Returns the maximum number of entries that can be recorded.
* @return {number} The max number of entries.
*/
bite.common.log.Simple.prototype.getMaxEntries = function() {
return this.maxEntries_;
};
/**
* Returns the newest entry in the list or null if there are no entries.
* @return {?bite.common.log.Simple.Entry} The newest entry or null if there
* are no entries.
*/
bite.common.log.Simple.prototype.getNewestEntry = function() {
if (this.entries_.length == 0) {
return null;
}
return this.entries_[this.entries_.length - 1];
};
/**
* Determine if the given callback is listeneing.
* @param {function(!bite.common.log.Simple.Entry)} callback The callback to be
* fired.
* @return {boolean} Whether or not the callback is listening.
*/
bite.common.log.Simple.prototype.hasListener = function(callback) {
return this.signal_.hasListener(/** @type {function(...[*])} */ (callback));
};
/**
* Removes a callback from the log's bite.common.signal.Simple object.
* @param {function(!bite.common.log.Simple.Entry)} callback The callback to be
* fired.
*/
bite.common.log.Simple.prototype.removeListener = function(callback) {
this.signal_.removeListener(/** @type {function(...[*])} */ (callback));
};
/**
* Change the maximum number of entries that can be logged. newMax is ignored
* if it is less than or equal to zero, or is the same as the current max
* entries. If the new max entries is less than the current number of entries
* then the oldest entries will be removed to make the queue equal to the new
* maximum.
* @param {number} newMax The new maximum number of entries to allow.
*/
bite.common.log.Simple.prototype.setMaxEntries = function(newMax) {
if (newMax <= 0 || newMax == this.maxEntries_) {
return;
}
this.maxEntries_ = newMax;
var diff = this.entries_.length - this.maxEntries_;
if (diff > 0) {
this.entries_.splice(0, diff);
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for bite.common.log.Simple.
*
* Note that tests make use of the entryTest function for validating entry
* objects. This function requires an object containing expected values. If a
* key is present but the value is undefined in the expected values object then
* that key is considered a don't care. (This also assumes that the log does
* not add key/value pairs if the value is undefined) If the key is not
* present in the expected values object then a fail assertion occurs. The
* reason for this assertion is to ensure that changes to the entry object are
* noted by the unit tester and not overlooked.
*
* Test cases:
* testChangeMaxEntriesWithLessThenAddEntry
* testChangeMaxEntriesWithLess
* testChangeMaxEntriesWithEqual
* testChangeMaxExtriesWithMore
* testMaxEntries
* testClearWithMultipleEntries
* testClearWithOneEntry
* testReattachListener
* testSingleListener
* testEntryTimeOrder
* testAddMultipleEntries
* testAddOneEntry
* testNoEntries
* testConstructorInputs
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.require('bite.common.log.Simple');
/**
* The log created and destroyed for each test.
* @type {bite.common.log.Simple}
*/
var logToTest = null;
/**
* Alias to the key names for the log. Creating this alias will help general
* the testing done for the log so that future logs can refactor this code for
* a more general testing solution.
* @type {!Object}
*/
var LOG_KEY_NAME = bite.common.log.Simple.KeyName;
/**
* Sets up the environment for each unit test.
*/
function setUp() {
logToTest = new bite.common.log.Simple();
}
/**
* Cleans up the environment for each unit test.
*/
function tearDown() {
logToTest = null;
}
/**
* Called when the log fires a signal and is passed entry object. The function
* will loop over all known log keys and compare the expected value with the
* given value. If the values are not equal an assert will occur. An assert
* will also occur if a known key is missing.
* @param {string} msg A message to be displayed by the assert.
* @param {bite.common.log.Simple.Entry} expectedValues An entry object
* containing the expected values in the entry. All undefined but present
* keys are considered "don't cares".
* @param {?bite.common.log.Simple.Entry=} entry The log entry to validate.
*/
function entryTest(msg, expectedValues, entry) {
if (entry == null || entry == undefined) {
fail(msg + ' Entry not provided.');
}
for (var keyId in LOG_KEY_NAME) {
var key = LOG_KEY_NAME[keyId];
// Skip keys if they exist and have an undefined value.
if (key in expectedValues && expectedValues[key] == undefined) {
continue;
}
msg = msg + ' [' + key + '].';
if (!(key in expectedValues)) {
fail(msg + ' Missing expected value for comparison.');
}
msg = msg + ' : ' + expectedValues[key] + ' = ' + entry[key] + ' : ';
assertEquals(msg, expectedValues[key], entry[key]);
}
}
/**
* Generates an object containing all the known keys in a log entry set as
* don't cares. The object also contains a counter for tracking how many times
* the callback has fired.
* @return {!Object} An object containing don't care values for all known keys,
* and a counter.
*/
function getDefaultExpectedValues() {
var obj = {};
obj[LOG_KEY_NAME.TIMESTAMP] = undefined;
obj[LOG_KEY_NAME.VALUE] = undefined;
return obj;
}
/**
* Tests changing max entries for the log where the number of entries is less
* than the new maximum. Then make sure that adding a new entry gives the
* correct information.
*/
function testChangeMaxEntriesWithLessThenAddEntry() {
var testName = 'testChangeMaxEntriesWithLessThenAddEntry';
logToTest.add('entry1');
logToTest.add('entry2');
logToTest.add('entry3');
// Change max entries to two while there are currently three entries in the
// log. This should cut off the first entry, so the newest entry should be
// the only one left.
logToTest.setMaxEntries(2);
// Add a forth entry
logToTest.add('entry4');
// Check that only two entries are in the log, and are the correct entries.
var expectedValues = getDefaultExpectedValues();
iter = logToTest.getIterOldToNew();
entryObj = iter();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry3';
entryTest(testName, expectedValues, entryObj);
entryObj = iter();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry4';
entryTest(testName, expectedValues, entryObj);
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
}
/**
* Tests changing max entries for the log where the number of entries is less
* than the new maximum.
*/
function testChangeMaxEntriesWithLess() {
var testName = 'testChangeMaxEntriesWithLess';
logToTest.add('entry1');
logToTest.add('entry2');
var expectedValues = getDefaultExpectedValues();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry2';
// Check that only one entry is in the log, and it is the correct entry.
var iter = logToTest.getIterNewToOld();
var entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNotNull(iter());
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
// Change max entries to one while there are currently two entries in the
// log. This should cut off the first entry, so the newest entry should be
// the only one left.
logToTest.setMaxEntries(1);
// Check that only one entry is in the log, and it is the correct entry.
iter = logToTest.getIterNewToOld();
entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
}
/**
* Tests changing max entries for the log where the number of entries is equal
* to the new maximum.
*/
function testChangeMaxEntriesWithEqual() {
var testName = 'testChangeMaxEntriesWithEqual';
logToTest.add('entry1');
logToTest.add('entry2');
var expectedValues = getDefaultExpectedValues();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry2';
// Check that only one entry is in the log, and it is the correct entry.
var iter = logToTest.getIterNewToOld();
var entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNotNull(iter());
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
// Change max entries to two while there are currently two entries in the
// log.
logToTest.setMaxEntries(2);
// Check that only one entry is in the log, and it is the correct entry.
iter = logToTest.getIterNewToOld();
entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNotNull(iter());
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
}
/**
* Tests changing max entries for the log where the number of entries is still
* less than the new maximum.
*/
function testChangeMaxEntriesWithMore() {
var testName = 'testChangeMaxEntriesWithMore';
logToTest.add('entry1');
logToTest.add('entry2');
var expectedValues = getDefaultExpectedValues();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry2';
// Check that only one entry is in the log, and it is the correct entry.
var iter = logToTest.getIterNewToOld();
var entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNotNull(iter());
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
// Change max entries to three while there are currently two entries in the
// log.
logToTest.setMaxEntries(3);
// Check that only one entry is in the log, and it is the correct entry.
iter = logToTest.getIterNewToOld();
entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNotNull(iter());
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
}
/**
* Tests that max entries restricts the number of entries the log can hold.
*/
function testMaxEntries() {
var testName = 'testMaxEntries';
logToTest = new bite.common.log.Simple(1);
logToTest.add('entry1');
logToTest.add('entry2');
var expectedValues = getDefaultExpectedValues();
expectedValues[LOG_KEY_NAME.VALUE] = 'entry2';
// Check that only one entry is in the log, and it is the correct entry.
var iter = logToTest.getIterNewToOld();
var entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNull(iter());
// Test access to newest entry is correct.
entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
}
/**
* Tests that entry access returns null after clearing a log with multiple
* entries. Other tests ensure that access works properly.
*/
function testClearWithMultipleEntries() {
for (var i = 1; i <= 4; ++i) {
logToTest.add('entry' + i);
}
logToTest.clear();
// Accessing newest.
assertNull(logToTest.getNewestEntry());
// Accessing through new to old iterator.
iter = logToTest.getIterNewToOld();
assertNull(iter());
// Accessing through old to new iterator.
iter = logToTest.getIterOldToNew();
assertNull(iter());
}
/**
* Tests that entry access returns null after clearing a log with a single
* entry. Other tests ensure that access works properly.
*/
function testClearWithOneEntry() {
logToTest.add('entry');
logToTest.clear();
// Accessing newest.
assertNull(logToTest.getNewestEntry());
// Accessing through new to old iterator.
iter = logToTest.getIterNewToOld();
assertNull(iter());
// Accessing through old to new iterator.
iter = logToTest.getIterOldToNew();
assertNull(iter());
}
/**
* Tests reattaching the same listener between log entries. The test also
* ensures the listener is attached when entries are logged before adding
* listeners.
*/
function testReattachListener() {
var testName = 'testReattachListener';
var counter = 0;
var expectedValues = getDefaultExpectedValues();
var callback = function(entry) {
entryTest(testName, expectedValues, entry);
++counter;
};
logToTest.add('entry1');
logToTest.addListener(callback);
assertTrue(logToTest.hasListener(callback));
logToTest.add('entry2');
logToTest.removeListener(callback);
assertFalse(logToTest.hasListener(callback));
logToTest.add('entry3');
logToTest.addListener(callback);
assertTrue(logToTest.hasListener(callback));
logToTest.add('entry4');
logToTest.removeListener(callback);
assertFalse(logToTest.hasListener(callback));
logToTest.add('entry5');
assertEquals(2, counter);
}
/**
* Tests attaching a single listener to a log. The test ensures the listener
* is fired the correct number of times. The scenario adds three entries with
* the listener attached followed by another entry after the listener is
* removed.
*/
function testSingleListener() {
var testName = 'testSingleListener';
var counter = 0;
var expectedValues = getDefaultExpectedValues();
var callback = function(entry) {
entryTest(testName, expectedValues, entry);
++counter;
};
logToTest.addListener(callback);
var entry;
for (var i = 1; i <= 3; ++i) {
entry = 'entry' + i;
expectedValues[LOG_KEY_NAME.VALUE] = entry;
logToTest.add(entry);
}
logToTest.removeListener(callback);
logToTest.add('entry4');
// Ensure the callback was only fired three times as the listener was removed
// after the third log entry.
assertEquals(3, counter);
}
/**
* Tests that entry order are chronological based on timestamps. In
* testAddMultipleEntries, entry order was verified by the iterators relative
* to the order added. Thus, this test only needs to check that the order is
* chronological.
*/
function testEntryTimeOrder() {
var testName = 'testEntryOrder';
var t = -1;
var entry;
for (var i = 1; i <= 4; ++i) {
entry = 'entry' + i;
logToTest.add(entry);
// Test timestamp for the newest is greater than the previous entry.
var entryObj = logToTest.getNewestEntry();
assertTrue(testName, t <= entryObj[LOG_KEY_NAME.TIMESTAMP]);
t = entryObj[LOG_KEY_NAME.TIMESTAMP];
// Hope to get a small difference to appear in the timestamps, but not
// guaranteed. Do not want to use asynchronous timeout in the unit test.
// Doesn't invalidate test if a pause doesn't occur.
for (var pause = 0; pause < 100000; ++pause);
}
}
/**
* Tests the addition of multiple entries; four was arbitrarily chosen for
* this scenario. The test also examines entry access and order. Timestamps
* are checked in testEntryTimeOrder().
*/
function testAddMultipleEntries() {
var testName = 'testAddMultipleEntries';
var expectedValues = getDefaultExpectedValues();
// expectedValues will represent the last entry after the loop.
var entry;
for (var i = 1; i <= 4; ++i) {
entry = 'entry' + i;
expectedValues[LOG_KEY_NAME.VALUE] = entry;
logToTest.add(entry);
}
var finalEntryValue = entry;
// Test access to newest entry.
var entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
// Test Iterators.
var iter = logToTest.getIterNewToOld();
for (i = 4; i >= 1; --i) {
expectedValues[LOG_KEY_NAME.VALUE] = 'entry' + i;
entryObj = iter(); // entry[4-1]
entryTest(testName + i + 'NTO', expectedValues, entryObj);
// Test the value of the first entry accessed; entry4 expected.
if (i == 4) {
assertEquals('IterNewToOld - checking entry value.', finalEntryValue,
entryObj[LOG_KEY_NAME.VALUE]);
}
}
assertNull(iter());
iter = logToTest.getIterOldToNew();
for (i = 1; i <= 4; ++i) {
entryObj = iter(); // entry[1-4]
expectedValues[LOG_KEY_NAME.VALUE] = 'entry' + i;
entryTest(testName + i + 'OTN', expectedValues, entryObj);
// Test the value of the first entry accessed; entry4 expected.
if (i == 4) {
assertEquals('IterOldToNew - checking entry value.', finalEntryValue,
entryObj[LOG_KEY_NAME.VALUE]);
}
}
assertNull(iter());
}
/**
* Tests the addition of a single entry and access to that entry.
*/
function testAddOneEntry() {
var testName = 'testAddOneEntry';
var expectedValues = getDefaultExpectedValues();
var entry = 'entry1';
expectedValues[LOG_KEY_NAME.VALUE] = entry;
logToTest.add(entry);
// Test access to newest entry.
var entryObj = logToTest.getNewestEntry();
entryTest(testName, expectedValues, entryObj);
assertNotEquals(testName, '-1', entryObj[LOG_KEY_NAME.TIMESTAMP]);
// Test iterators; expect one entry object followed by a null result.
var iter = logToTest.getIterNewToOld();
entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNull(iter());
iter = logToTest.getIterOldToNew();
entryObj = iter();
entryTest(testName, expectedValues, entryObj);
assertNull(iter());
}
/**
* Tests an empty log that ensures basic functionality works properly and does
* not throw exceptions when the log is empty. Max entries does not need to be
* checked in this situation because it is tested in testConstructorInputs().
* Signals are checked int testListeners.
*/
function testNoEntries() {
var testName = 'testNoEntries';
var counter = 0;
var expectedValues = getDefaultExpectedValues();
var callback = function() {
++counter;
};
// Test entry access.
assertNull(logToTest.getNewestEntry());
// Test iterators; expect null result from empty log.
var iter = logToTest.getIterNewToOld();
assertNull(iter());
iter = logToTest.getIterOldToNew();
assertNull(iter());
// Test add/remove of listeners
assertFalse(logToTest.hasListener(callback));
logToTest.addListener(callback);
assertTrue(logToTest.hasListener(callback));
logToTest.removeListener(callback);
assertFalse(logToTest.hasListener(callback));
assertEquals(0, counter); // Ensure the listener was never fired.
// Test clear
logToTest.clear();
}
/**
* Tests constructor inputs to ensure the correct initial values are assigned
* internally.
*/
function testConstructorInputs() {
assertEquals(bite.common.log.Simple.DEFAULT_MAX_ENTRIES,
logToTest.getMaxEntries());
logToTest = new bite.common.log.Simple(0);
assertEquals(bite.common.log.Simple.DEFAULT_MAX_ENTRIES,
logToTest.getMaxEntries());
logToTest = new bite.common.log.Simple(-1);
assertEquals(bite.common.log.Simple.DEFAULT_MAX_ENTRIES,
logToTest.getMaxEntries());
logToTest = new bite.common.log.Simple(1);
assertEquals(1, logToTest.getMaxEntries());
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define useful soy related js_test functions.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.test_framework.SoyTests');
/**
* Used to execute tests.
* @constructor
*/
bite.common.test_framework.SoyTests = function() {};
goog.addSingletonGetter(bite.common.test_framework.SoyTests);
/**
* Examines all tag attribute values within the string generated by the soy
* template against an expected value. The test is an assert chosen by the
* user.
* @param {function(string, string)} assert The assert function used to
* test the attribute values against the expected value.
* @param {string} expectedValue The value to compare against.
* @param {string} tag The attribute tag to search for.
* @param {function(Object=):string} template The soy template function.
* @param {Object=} data The data to pass to the template.
*/
bite.common.test_framework.SoyTests.prototype.testAttributeValue =
function(assert, expectedValue, tag, template, data) {
var regexp = RegExp(tag + '=["]([^"]*)["]', 'gi');
var string = template(data || {});
// Keep executing the regular expression over the string to find the
// subsequent tags as RegExp only matches successfully one pattern at a time.
// When there are no more successful matches it will return null.
var matches = regexp.exec(string);
while (matches !== null) {
// matches[0] == entire match including tag
// matches[1] == only the portion of the match inside the ()
assert(matches[1], expectedValue);
matches = regexp.exec(string);
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Define useful dom related js_test functions.
*
* @author jasonstredwick@google.com (Jason Stredwick)
*/
goog.provide('bite.common.test_framework.DomTests');
goog.require('goog.dom');
goog.require('goog.dom.query');
/**
* Used to execute tests.
* @constructor
*/
bite.common.test_framework.DomTests = function() {};
goog.addSingletonGetter(bite.common.test_framework.DomTests);
/**
* Performs a boolean test on elements against their given boolean attribute
* versus expected values.
* @param {Object.<string,boolean>} inputs The ids for the elements
* mapped to their expected boolean value.
* @param {string} attribute The name of the element attribute to examine.
* @param {Element=} rootElement The element from which to do the queries.
*/
bite.common.test_framework.DomTests.prototype.testElementBooleanValue =
function(inputs, attribute, rootElement) {
rootElement = rootElement || goog.dom.getDocument();
for (var key in inputs) {
var query = goog.dom.query('[id="' + key + '"]', rootElement);
assertEquals(1, query.length);
if (inputs[key]) {
assertTrue(key, query[0][attribute]);
} else {
assertFalse(key, query[0][attribute]);
}
}
};
/**
* Performs an equality test on elements against their given attribute versus
* expected values.
* @param {Object.<string>} inputs The ids for the elements mapped to their
* expected boolean value.
* @param {string} attribute The name of the element attribute to examine.
* @param {Element=} rootElement The element from which to do the queries.
*/
bite.common.test_framework.DomTests.prototype.testElementEqualsValue =
function(inputs, attribute, rootElement) {
rootElement = rootElement || goog.dom.getDocument();
for (var key in inputs) {
var query = goog.dom.query('[id="' + key + '"]', rootElement);
assertEquals(key, 1, query.length);
assertEquals(key, inputs[key], query[0][attribute]);
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview The BITE container provides an interface for easily
* creating a new BITE console container on the screen. The console is
* automatically resizable and draggable, and can optionally store its location
* and position based on the consoleId. The root element of the container
* may be accessed by bite.client.Container.root().
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.provide('bite.ux.Container');
goog.require('Bite.Constants');
goog.require('bite.client.Templates.ux');
goog.require('bite.ux.Dragger');
goog.require('bite.ux.Resizer');
goog.require('common.dom.element');
goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.json');
goog.require('soy');
/**
* Sets up a new BITE console container. The container is set up to be
* resizable and draggable.
* @param {string} server The URL to the current BITE server.
* @param {string} consoleId A unique ID for the container element. This ID
* will be used as an element ID, so should be labeled with the BITE
* prefix such as 'bite-bugs-console-container'. The ID will also
* be used to store the location of the container in localStorage,
* if opt_savePosition is true.
* @param {string} headerText The title of the console container.
* @param {string=} opt_headerSubtext A subtitle for the console container.
* @param {boolean=} opt_savePosition Whether or not the console should save
* its last position in localStorage. If the position is not saved, a new
* container will always be positioned at the default location defined
* in background.js.
* @param {boolean=} opt_hideOnLoad Whether or not the console should begin
* as a hidden element.
* @param {string=} opt_tooltip The optional tooltip of this dialog.
* @param {string=} opt_link The optional link to a tutorial.
* @constructor
*/
bite.ux.Container = function(server, consoleId, headerText,
opt_headerSubtext, opt_savePosition,
opt_hideOnLoad, opt_tooltip, opt_link) {
/**
* The id of the current console element.
* @type {string}
* @private
*/
this.consoleId_ = consoleId;
/**
* Manages browser events created by the container.
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
/**
* A function to call when the container is closed.
* @type {function()}
* @private
*/
this.closeCallback_ = goog.nullFunction;
var headerSubtext = opt_headerSubtext || '';
var tooltip = opt_tooltip || '';
var link = opt_link || '';
var rootFolder = chrome.extension.getURL('');
var container = soy.renderAsElement(
bite.client.Templates.ux.consoleContainer,
{rootFolder: rootFolder,
serverUrl: server,
consoleId: this.consoleId_,
headerText: headerText,
headerSubtext: headerSubtext,
tooltip: tooltip,
link: link});
/**
* The root element of the bugs console.
* @type {!Element}
* @private
*/
this.root_ = container;
var content = goog.dom.getElementByClass(
bite.ux.Container.Classes_.CONTENT, this.root_);
if (!content) {
throw Error(
'The element ' + bite.ux.Container.Classes_.CONTENT +
' could not be found');
}
/**
* The div holding the content.
* @type {!Element}
* @private
*/
this.content_ = content;
var infobar = goog.dom.getElementByClass(
bite.ux.Container.Classes_.INFOBAR, this.root_);
if (!infobar) {
throw Error(
'The element ' + bite.ux.Container.Classes_.INFOBAR +
' could not be found');
}
/**
* The infobar element.
* @type {!Element}
* @private
*/
this.infobar_ = infobar;
goog.dom.appendChild(goog.dom.getDocument().body, this.root_);
/**
* A counter to keep track of the number of messages in the infobar.
* @type {number}
* @private
*/
this.messageCounter_ = 0;
var savePositionCallback = function() {};
if (opt_savePosition) {
savePositionCallback = goog.bind(this.setLastSizeAndPosition_, this);
}
/**
* Resizer for the container.
* @type {!bite.ux.Resizer}
* @private
*/
this.resizer_ = new bite.ux.Resizer(this.root_, savePositionCallback);
// Used as the drag element for the container.
var header = goog.dom.getElementByClass(bite.ux.Container.Classes_.HEADER,
this.root_);
var updateResizer = goog.bind(this.resizer_.recalculate, this.resizer_);
var dragCallback = function() {
updateResizer();
savePositionCallback();
};
/**
* Dragger for the container.
* @type {!bite.ux.Dragger}
* @private
*/
this.dragger_ = new bite.ux.Dragger(this.root_,
/** @type {!Element} */ (header), dragCallback);
this.getSavedConsoleLocation_();
if (!opt_hideOnLoad) {
this.show();
}
var closeButton = goog.dom.getElementByClass(
bite.ux.Container.Classes_.CLOSE_BUTTON, this.root_);
this.eventHandler_.listen(
closeButton, goog.events.EventType.CLICK, this.closeHandler_);
};
/**
* Location information for the console.
*
* @typedef {{position: {x: number, y: number},
* size: {height: number, width: number}}}
*/
bite.ux.Container.Location;
/**
* Key prefixs used to keep persistent information in local storage.
* The console locationkey used for each console will have the consoleId
* as its suffix. The key used for each message will have the messageId as its
* suffix.
* @enum {string}
* @private
*/
bite.ux.Container.Keys_ = {
CONSOLE_LOCATION: 'bite-client-background-console-location-',
SHOWN_MESSAGES: 'bite-client-background-shown-messages-'
};
/**
* Default location for a new console window.
* @type {bite.ux.Container.Location}
* @private
*/
bite.ux.Container.DEFAULT_CONSOLE_LOCATION_ =
{position: {x: 10, y: 10},
size: {height: 400, width: 450}};
/**
* CSS class names used by the BITE container.
* @enum {string}
* @private
*/
bite.ux.Container.Classes_ = {
CLOSE_BUTTON: 'bite-close-button',
CONTENT: 'bite-console-content',
HEADER: 'bite-header',
HIDDEN: 'bite-hidden',
INFOBAR: 'bite-console-infobar'
};
/**
* Makes the console visible.
*/
bite.ux.Container.prototype.show = function() {
goog.style.setStyle(this.root_, 'visibility', 'visible');
};
/**
* Hides the console.
*/
bite.ux.Container.prototype.hide = function() {
goog.style.setStyle(this.root_, 'visibility', 'hidden');
};
/**
* Returns whether or not the console is currently visible.
* @return {boolean} True if the console is visible.
*/
bite.ux.Container.prototype.isVisible = function() {
return goog.style.getStyle(this.root_, 'visibility') == 'visible';
};
/**
* Destroys the current console.
*/
bite.ux.Container.prototype.remove = function() {
this.eventHandler_.removeAll();
goog.dom.getDocument().body.removeChild(this.root_);
};
/**
* Sets the content of the container.
* @param {string} innerHtml The HTML string describing the content.
*/
bite.ux.Container.prototype.setContentFromHtml = function(innerHtml) {
this.content_.innerHTML = innerHtml;
};
/**
* Gets the content of the container.
* @return {Element} The content element of the container.
*/
bite.ux.Container.prototype.getContentElement = function() {
return this.content_;
};
/**
* Sets the content of the container from an element.
* @param {Element} element The element to set as the content.
*/
bite.ux.Container.prototype.setContentFromElement = function(element) {
this.setContentFromHtml(element.innerHTML);
};
/**
* Sets a callback to call when the close button is clicked. If this is called
* more than once, earlier callbacks are ignored.
* @param {function()} callback The callback.
*/
bite.ux.Container.prototype.setCloseCallback = function(callback) {
this.closeCallback_ = callback;
};
/**
* Displays a message in the infobar. When the user closes the message,
* the Id will be stored in localStorage and any future calls to
* showInfoMessageOnce will NOT display that message.
* @param {string} id A unique string identifying the message.
* @param {string} message The text of the message.
*/
bite.ux.Container.prototype.showInfoMessageOnce = function(id, message) {
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE,
'key': bite.ux.Container.Keys_.SHOWN_MESSAGES + id},
goog.bind(this.showInfoMessageCallback_, this, message, id));
};
/**
* Displays a message in the infobar. The message will persist until
* the user closes it.
* @param {string} message The text of the message.
* @param {number=} opt_autoHideInterval The interval in seconds that the
* message should automatically go away.
* @export
*/
bite.ux.Container.prototype.showInfoMessage = function(
message, opt_autoHideInterval) {
this.addInfobarMessage_(message, null, opt_autoHideInterval);
};
/**
* Returns the root element of the container
* @return {Element} The root element.
*/
bite.ux.Container.prototype.getRoot = function() {
return this.root_;
};
/**
* Hides the infobar.
* @private
*/
bite.ux.Container.prototype.hideInfobar_ = function() {
goog.dom.classes.add(this.infobar_, bite.ux.Container.Classes_.HIDDEN);
};
/**
* Displays the infobar.
* @private
*/
bite.ux.Container.prototype.showInfobar_ = function() {
goog.dom.classes.remove(this.infobar_, bite.ux.Container.Classes_.HIDDEN);
};
/**
* If a message has been shown, does nothing. Otherwise, displays it in
* the infobar.
* @param {string} message The text of the message.
* @param {string} messageId The unique id for the message.
* @param {?string} shown Null if the message has not been shown.
* @private
*/
bite.ux.Container.prototype.showInfoMessageCallback_ = function(message,
messageId,
shown) {
if (!shown) {
this.addInfobarMessage_(message, messageId);
}
};
/**
* Adds a message to the list of currently displayed messages on the infobar.
* @param {string} message The message to display.
* @param {?string} messageId The id for this message.
* @param {number=} opt_autoHideInterval The interval in seconds that the
* message should automatically go away.
* @private
*/
bite.ux.Container.prototype.addInfobarMessage_ =
function(message, messageId, opt_autoHideInterval) {
if (this.messageCounter_ == 0) {
this.showInfobar_();
}
++this.messageCounter_;
var messageElement = goog.dom.createDom(goog.dom.TagName.SPAN);
messageElement.innerHTML = message;
this.infobar_.appendChild(messageElement);
var boundOnRemoveMessage = goog.bind(
this.removeMessage_, this, messageElement, messageId);
this.eventHandler_.listen(
messageElement, goog.events.EventType.CLICK,
boundOnRemoveMessage);
if (opt_autoHideInterval) {
goog.Timer.callOnce(
boundOnRemoveMessage, opt_autoHideInterval * 1000);
}
};
/**
* Removes a specific infobar message from view. If the message has an id,
* sets a value of 't' for that message in localStorage so it will not be
* displayed again.
*
* @param {Element} messageElement The message to remove.
* @param {?string} messageId The id of the message to remove.
* @private
*/
bite.ux.Container.prototype.removeMessage_ =
function(messageElement, messageId) {
if (!goog.dom.contains(this.infobar_, messageElement)) {
return;
}
goog.dom.removeNode(messageElement);
--this.messageCounter_;
if (this.messageCounter_ == 0) {
this.hideInfobar_();
}
if (messageId) {
chrome.extension.sendRequest(
{'action': Bite.Constants.HUD_ACTION.SET_LOCAL_STORAGE,
'key': bite.ux.Container.Keys_.SHOWN_MESSAGES + messageId,
'value': 't'});
}
};
/**
* Saves the size and position of the console. The location information
* is stored in the background so that the console position is constant
* across URLs and across tabs. When a new BITE container with the same
* ID as this is opened, it will use the last saved size and position.
* @private
*/
bite.ux.Container.prototype.setLastSizeAndPosition_ = function() {
var consoleLocation = {
position: common.dom.element.getPosition(this.root_),
size: common.dom.element.getSize(this.root_)
};
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.SET_LOCAL_STORAGE,
key: bite.ux.Container.Keys_.CONSOLE_LOCATION + this.consoleId_,
value: goog.json.serialize(consoleLocation)});
};
/**
* Requests the location information for a newly opened console.
* @private
*/
bite.ux.Container.prototype.getSavedConsoleLocation_ = function() {
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE,
key: bite.ux.Container.Keys_.CONSOLE_LOCATION + this.consoleId_},
goog.bind(this.handleGetSavedConsoleLocation_, this));
};
/**
* Updates the location information for a newly opened console. The location
* is expected to be an object of the form:
* {position: {x: number, y: number},
* size: {height: number, width: number}}
* @param {?string} rawLocation The raw string of the location from
* localStorage, or null if there is no stored location.
* @private
*/
bite.ux.Container.prototype.handleGetSavedConsoleLocation_ =
function(rawLocation) {
var location = bite.ux.Container.DEFAULT_CONSOLE_LOCATION_;
if (rawLocation) {
try {
location = /** @type {!bite.ux.Container.Location} */
(goog.json.parse(rawLocation));
} catch (error) {
chrome.extension.sendRequest(
{action: Bite.Constants.HUD_ACTION.REMOVE_LOCAL_STORAGE,
key: bite.ux.Container.Keys_.CONSOLE_LOCATION +
this.consoleId_});
}
}
this.updateConsolePosition(location);
};
/**
* Updates the console to the size and location given in the parameter.
* @param {!bite.ux.Container.Location} location The location info.
*/
bite.ux.Container.prototype.updateConsolePosition = function(location) {
common.dom.element.setPosition(this.root_, location.position);
common.dom.element.setSize(this.root_, location.size);
this.resizer_.recalculate();
this.dragger_.recalculate();
};
/**
* Handles the event when the user clicks on the close button.
* @private
*/
bite.ux.Container.prototype.closeHandler_ = function() {
this.closeCallback_();
};
/**
* Handles the event when the user closes the infobar.
* @private
*/
bite.ux.Container.prototype.closeInfobarHandler_ = function() {
this.hideInfobar_();
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the BITE dragger.
*
* TODO (jason.stredwick): Add in revised unit test.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.require('bite.ux.Resizer');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
var stubs_ = new goog.testing.PropertyReplacer();
var sandbox;
var container;
/*
function getViewportSize() {
return new goog.math.Size(1000, 1000);
}
function setUp() {
stubs_.set(goog.dom, 'getViewportSize', getViewportSize);
sandbox = goog.dom.createDom('div', {
'id': 'sandbox',
'style': 'position:fixed;top:0px;left:0px;width:1000px;height:1000px'});
goog.dom.appendChild(document.body, sandbox);
container = goog.dom.createDom('div', {
'id': 'target',
'style': 'position:fixed;top:100px;left:101px;width:300px;height:301px'});
sandbox.appendChild(container);
}
function tearDown() {
goog.dom.removeNode(container);
container = null;
sandbox = null;
stubs_.reset();
goog.events.removeAll();
}
function testUpdate() {
var resizer = new bite.ux.Resizer(container, container);
assertEquals(300, resizer.getSize().width);
assertEquals(301, resizer.getSize().height);
assertEquals(101, resizer.getPosition().x);
assertEquals(100, resizer.getPosition().y);
resizer.updateSize({width: 400, height: 500});
resizer.updatePosition({x: 11, y: 12});
assertEquals(400, resizer.getSize().width);
assertEquals(500, resizer.getSize().height);
assertEquals(11, resizer.getPosition().x);
assertEquals(12, resizer.getPosition().y);
assertEquals('400px', container.style.width);
assertEquals('500px', container.style.height);
assertEquals('11px', container.style.left);
assertEquals('12px', container.style.top);
}
function testDrag() {
var resizer = new bite.ux.Resizer(container, container);
goog.testing.events.fireMouseDownEvent(
container,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 450, y: 450});
assertEquals('100px', container.style.top);
assertEquals('101px', container.style.left);
goog.testing.events.fireMouseMoveEvent(
container,
{x: 460, y: 470});
assertEquals('120px', container.style.top);
assertEquals('111px', container.style.left);
goog.testing.events.fireMouseUpEvent(
container,
{x: 460, y: 470});
assertEquals('120px', container.style.top);
assertEquals('111px', container.style.left);
}
function testSEResize() {
var resizer = new bite.ux.Resizer(container, container);
var seCorner = goog.dom.getElementByClass('se-resizer');
goog.testing.events.fireMouseDownEvent(
seCorner,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 800, y: 800});
goog.testing.events.fireMouseMoveEvent(
seCorner,
{x: 810, y: 820});
goog.testing.events.fireMouseUpEvent(
seCorner,
{x: 810, y: 820});
assertEquals('100px', container.style.top);
assertEquals('101px', container.style.left);
assertEquals('310px', container.style.width);
assertEquals('321px', container.style.height);
}
function testNWResize() {
var resizer = new bite.ux.Resizer(container, container);
var nwCorner = goog.dom.getElementByClass('nw-resizer');
goog.testing.events.fireMouseDownEvent(
nwCorner,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 800, y: 800});
goog.testing.events.fireMouseMoveEvent(
nwCorner,
{x: 790, y: 780});
goog.testing.events.fireMouseUpEvent(
nwCorner,
{x: 790, y: 780});
assertEquals('80px', container.style.top);
assertEquals('91px', container.style.left);
assertEquals('310px', container.style.width);
assertEquals('321px', container.style.height);
}
*/
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides utilities for resizing a container. The resizer
* creates it's own resizing elements that follow the element to resize. This
* has an issue where the element is resized or moved external to this code.
*
* Assumption: The element referenced by this class are not modified while
* the resizing action is underway. Likewise, only one resizer can be used at
* a time.
*
* TODO(jason.stredwick): For now it will be on the user to ensure the resizers
* are updated if the element changes externally. In the future it may be
* possible to add floating resizer elements to the element itself as children
* with relative positions.
* TODO(jason.stredwick): Consider making the callback a signal.
*
* @author ralphj@google.com (Julie Ralph)
* @author jason.stredwick@gmail.com (Jason Stredwick)
*/
goog.provide('bite.ux.Resizer');
goog.require('common.dom.element');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
/**
* Provides a class for managing resizing an element.
* @param {!Element} element The element to add the ability to resize.
* @param {function()=} opt_resizedCallback A callback fired when the element
* has been resized.
* @constructor
*/
bite.ux.Resizer = function(element, opt_resizedCallback) {
/**
* The element to resize.
* @type {!Element}
* @private
*/
this.element_ = element;
/**
* Callback on resize release.
* @type {function()}
* @private
*/
this.resizedCallback_ = opt_resizedCallback || function() {};
/**
* Whether or not currently resizing.
* @type {boolean}
* @private
*/
this.isResizing_ = false;
/**
* The last mouse position.
* @type {!{x: number, y: number}}
* @private
*/
this.prevMousePos_ = {x: 0, y: 0};
/**
* An object containing the resizer elements, keyed by their cardinal
* direction.
* @type {!{n: !Element, ne: !Element, e: !Element, se: !Element,
* s: !Element, sw: !Element, w: !Element, nw: !Element}}
* @private
*/
this.resizers_ = bite.ux.Resizer.createResizers_();
/**
* The resizer div that contains all the resizer elements.
* @type {Element}
* @private
*/
this.resizerDom_ = null;
/**
* An array of listener keys for resizing.
* @type {!Array.<number>}
* @private
*/
this.resizeListenerKeys_ = [];
/**
* Handles the event listeners.
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
this.resizersAdd_();
this.updateResizerPosition_();
};
/**
* The minimum width of the container element.
* @type {number}
* @private
*/
bite.ux.Resizer.MIN_WIDTH_ = 200;
/**
* The minimum height of the container element.
* @type {number}
* @private
*/
bite.ux.Resizer.MIN_HEIGHT_ = 150;
/**
* Resize Modes
* @enum {string}
* @private
*/
bite.ux.Resizer.Mode_ = {
NONE: 'none',
E: 'east',
SE: 'southeast',
S: 'south',
SW: 'southwest',
W: 'west',
NW: 'northwest',
N: 'north',
NE: 'northeast'
};
/**
* Destroy the object by cleaning up its allocated items.
*/
bite.ux.Resizer.prototype.destroy = function() {
// Remove callback before calling onMouseUp so an event is not fired.
this.resizedCallback_ = function() {};
this.onMouseUp_();
this.resizersRemove_();
this.element_ = /** @type {!Element} */ (null);
};
/**
* Recalculates if the managed element is updated externally.
*/
bite.ux.Resizer.prototype.recalculate = function() {
this.updateResizerPosition_();
};
/**
* Handles the user initiating a resize by clicking and dragging.
* @param {bite.ux.Resizer.Mode_} mode The resizing mode to be in.
* @param {Element} resizer The resizer to use.
* @param {goog.events.BrowserEvent} e A mouseEvent object from the object
* being dragged.
* @private
*/
bite.ux.Resizer.prototype.onMouseDown_ = function(mode, resizer, e) {
// Do not begin resizing if already resizing or on right click.
if (!resizer || this.isResizing_ || !e.isMouseActionButton()) {
return;
}
this.isResizing_ = true;
this.prevMousePos_ = {x: e.clientX, y: e.clientY};
// Setup resizer to listen for mouse move and up events.
this.resizeListenerKeys_.push(goog.events.listen(
goog.dom.getDocument(), goog.events.EventType.MOUSEMOVE,
goog.bind(this.onMouseMove_, this, mode, resizer)));
this.resizeListenerKeys_.push(goog.events.listen(
goog.dom.getDocument(), goog.events.EventType.MOUSEUP,
goog.bind(this.onMouseUp_, this)));
// Prevent text from being selected while resizing.
e.preventDefault();
};
/**
* Handles dragging motion while the container is being resized.
* @param {bite.ux.Resizer.Mode_} mode The resizing mode to be in.
* @param {Element} resizer The resizer to use.
* @param {Object} e A mouseEvent object from the object being dragged.
* @private
*/
bite.ux.Resizer.prototype.onMouseMove_ = function(mode, resizer, e) {
// Find position of the wrapped element's upper left and lower right corners.
var elemDim = common.dom.element.getSize(this.element_);
var elemP0 = common.dom.element.getPosition(this.element_);
var elemP1 = {x: elemP0.x + elemDim.width - 1,
y: elemP0.y + elemDim.height - 1};
// Compute the movement delta based on the new mouse position.
var mousePos = {x: e.clientX, y: e.clientY};
var delta = bite.ux.Resizer.computeDelta_(this.prevMousePos_, mousePos);
this.prevMousePos_ = mousePos;
// Calculate the new position of the element.
bite.ux.Resizer.updateElementPositions_(elemP0, elemP1, delta, mousePos,
mode);
bite.ux.Resizer.constrainElement_(elemP0, elemP1, mode);
// Update the position and size of the resizable element then update the
// resizer positions.
common.dom.element.setPosition(this.element_, elemP0);
common.dom.element.setSize(this.element_, {width: elemP1.x - elemP0.x - 1,
height: elemP1.y - elemP0.y - 1});
this.updateResizerPosition_();
};
/**
* Handles a mouse up event releasing the container when it's being resized.
* @param {Object=} opt_e A mouseEvent object from the object being dragged.
* @private
*/
bite.ux.Resizer.prototype.onMouseUp_ = function(opt_e) {
while (this.resizeListenerKeys_.length > 0) {
goog.events.unlistenByKey(this.resizeListenerKeys_.pop());
}
this.isResizing_ = false;
this.resizedCallback_();
};
/**
* An object containing the resizer elements, keyed by their cardinal
* direction.
* @return {!{n: !Element, ne: !Element, e: !Element, se: !Element,
* s: !Element, sw: !Element, w: !Element, nw: !Element}} The new
* resizer elements.
* @private
*/
bite.ux.Resizer.createResizers_ = function() {
var n = goog.dom.createDom('div', 'n-resizer');
var ne = goog.dom.createDom('div', 'ne-resizer');
var e = goog.dom.createDom('div', 'e-resizer');
var se = goog.dom.createDom('div', 'se-resizer');
var s = goog.dom.createDom('div', 's-resizer');
var sw = goog.dom.createDom('div', 'sw-resizer');
var w = goog.dom.createDom('div', 'w-resizer');
var nw = goog.dom.createDom('div', 'nw-resizer');
if (!(n && ne && e && se && s && sw && w && nw)) {
throw 'Failed to create resizers needed to implement Resizer ' +
'functinality.';
}
return {
n: /** @type {!Element} */ (n),
ne: /** @type {!Element} */ (ne),
e: /** @type {!Element} */ (e),
se: /** @type {!Element} */ (se),
s: /** @type {!Element} */ (s),
sw: /** @type {!Element} */ (sw),
w: /** @type {!Element} */ (w),
nw: /** @type {!Element} */ (nw)
};
};
/**
* Adds edge and corner resizers to the container.
* @private
*/
bite.ux.Resizer.prototype.resizersAdd_ = function() {
this.resizerDom_ = goog.dom.createDom('div', 'bite-resizers',
this.resizers_.n, this.resizers_.ne,
this.resizers_.e, this.resizers_.se,
this.resizers_.s, this.resizers_.sw,
this.resizers_.w, this.resizers_.nw);
this.resizers_.n.style.cssText =
'z-index: 70001; height: 7px; cursor: n-resize';
this.resizers_.ne.style.cssText =
'z-index: 70003; width: 15px; height: 15px; cursor: ne-resize';
this.resizers_.e.style.cssText =
'z-index: 70002; width: 7px; cursor: e-resize';
this.resizers_.se.style.cssText =
'z-index: 70003; width: 15px; height: 15px; cursor: se-resize';
this.resizers_.s.style.cssText =
'z-index: 70001; height: 7px; cursor: s-resize';
this.resizers_.sw.style.cssText =
'z-index: 70003; width: 15px; height: 15px; cursor: sw-resize';
this.resizers_.w.style.cssText =
'z-index: 70002; width: 7px; cursor: w-resize';
this.resizers_.nw.style.cssText =
'z-index: 70003; width: 15px; height: 15px; cursor: nw-resize';
var direction;
for (direction in this.resizers_) {
this.resizers_[direction].style.position = 'fixed';
}
this.resizerDom_.style.position = 'fixed';
goog.dom.appendChild(this.element_, this.resizerDom_);
this.setHandlers_();
};
/**
* Removes edge and corner resizers to the container.
* @private
*/
bite.ux.Resizer.prototype.resizersRemove_ = function() {
this.eventHandler_.removeAll();
if (this.resizerDom_) {
goog.dom.removeNode(this.resizerDom_);
}
};
/**
* Sets the handlers for the resizers and the dragging target.
* @private
*/
bite.ux.Resizer.prototype.setHandlers_ = function() {
// Add handlers for the corner and edge resizers.
this.eventHandler_.listen(this.resizers_.e, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.E,
this.resizers_.e));
this.eventHandler_.listen(this.resizers_.se, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.SE,
this.resizers_.se));
this.eventHandler_.listen(this.resizers_.s, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.S,
this.resizers_.s));
this.eventHandler_.listen(this.resizers_.sw, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.SW,
this.resizers_.sw));
this.eventHandler_.listen(this.resizers_.w, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.W,
this.resizers_.w));
this.eventHandler_.listen(this.resizers_.n, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.N,
this.resizers_.n));
this.eventHandler_.listen(this.resizers_.nw, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.NW,
this.resizers_.nw));
this.eventHandler_.listen(this.resizers_.ne, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this,
bite.ux.Resizer.Mode_.NE,
this.resizers_.ne));
};
/**
* Updates the resizers to fit the current container size and position.
* @private
*/
bite.ux.Resizer.prototype.updateResizerPosition_ = function() {
// Determinte the x, y coordinates of the container.
var pos = common.dom.element.getPosition(this.element_);
var dim = common.dom.element.getSize(this.element_);
var winX = pos.x;
var winY = pos.y;
var winH = dim.height;
var winW = dim.width;
// Move and resize the south resizer.
dim = common.dom.element.getSize(this.resizers_.s);
var newPos = {x: winX, y: winY + winH - 2};
var newDim = {width: winW, height: dim.height};
common.dom.element.setPosition(this.resizers_.s, newPos);
common.dom.element.setSize(this.resizers_.s, newDim);
// Move and resize the east resizer.
dim = common.dom.element.getSize(this.resizers_.e);
newPos = {x: winX + winW - 10, y: winY};
newDim = {width: dim.width, height: winH};
common.dom.element.setPosition(this.resizers_.e, newPos);
common.dom.element.setSize(this.resizers_.e, newDim);
// Move the south-east resizer.
newPos = {x: winX + winW - 10, y: winY + winH - 10};
common.dom.element.setPosition(this.resizers_.se, newPos);
// Move and resize the west resizer.
dim = common.dom.element.getSize(this.resizers_.w);
newPos = {x: winX - 2, y: winY};
newDim = {width: dim.width, height: winH};
common.dom.element.setPosition(this.resizers_.w, newPos);
common.dom.element.setSize(this.resizers_.w, newDim);
// Move the south-west resizer.
newPos = {x: winX, y: winY + winH - 15};
common.dom.element.setPosition(this.resizers_.sw, newPos);
// Move and resize the north resizer.
dim = common.dom.element.getSize(this.resizers_.n);
newPos = {x: winX, y: winY - 2};
newDim = {width: winW, height: dim.height};
common.dom.element.setPosition(this.resizers_.n, newPos);
common.dom.element.setSize(this.resizers_.n, newDim);
// Move the north-west resizer.
newPos = {x: winX - 2, y: winY - 5};
common.dom.element.setPosition(this.resizers_.nw, newPos);
// Move the north-east resizer.
newPos = {x: winX + winW, y: winY};
common.dom.element.setPosition(this.resizers_.ne, newPos);
};
/**
* Compute the movement delta based on the new mouse position. If the mouse
* has a component outside the viewport that component is zeroed in the
* movement vector. Give flexibility to the constraints of 10 pixels in order
* to prevent issues where the mouse is able to get ahead of the edge being
* dragged.
* @param {!{x: number, y: number}} p0 The previous mouse position.
* @param {!{x: number, y: number}} p1 The current mouse position.
* @return {!{x: number, y: number}} The movement vector of the mouse.
* @private
*/
bite.ux.Resizer.computeDelta_ = function(p0, p1) {
var viewportDim = goog.dom.getViewportSize();
var delta = {x: p1.x - p0.x, y: p1.y - p0.y};
if (p1.x < -10 || p1.x > viewportDim.width + 10) {
delta.x = 0;
}
if (p1.y < -10 || p1.y > viewportDim.height + 10) {
delta.y = 0;
}
return delta;
};
/**
* Updates the given element positions to their new values based on the mouse
* movement vector. The positions are passed by reference, so nothing is
* returned.
* @param {!{x: number, y: number}} p0 The upper left corner.
* @param {!{x: number, y: number}} p1 The lower right corner.
* @param {!{x: number, y: number}} delta The movement vector of the mouse.
* @param {!{x: number, y: number}} mousePos The position of the mouse.
* @param {bite.ux.Resizer.Mode_} mode Id for the resizer that was moved.
* @private
*/
bite.ux.Resizer.updateElementPositions_ = function(p0, p1, delta, mousePos,
mode) {
var width = p1.x - p0.x - 1;
var height = p1.y - p0.y - 1;
// Update element x positions
switch (mode) {
case bite.ux.Resizer.Mode_.NW:
case bite.ux.Resizer.Mode_.SW:
case bite.ux.Resizer.Mode_.W:
if (width > bite.ux.Resizer.MIN_WIDTH_ || mousePos.x <= p0.x) {
p0.x += delta.x;
}
break;
case bite.ux.Resizer.Mode_.E:
case bite.ux.Resizer.Mode_.NE:
case bite.ux.Resizer.Mode_.SE:
if (width > bite.ux.Resizer.MIN_WIDTH_ || mousePos.x >= p1.x) {
p1.x += delta.x;
}
break;
}
// Update element y positions
switch (mode) {
case bite.ux.Resizer.Mode_.N:
case bite.ux.Resizer.Mode_.NE:
case bite.ux.Resizer.Mode_.NW:
if (height > bite.ux.Resizer.MIN_HEIGHT_ || mousePos.y <= p0.y) {
p0.y += delta.y;
}
break;
case bite.ux.Resizer.Mode_.S:
case bite.ux.Resizer.Mode_.SE:
case bite.ux.Resizer.Mode_.SW:
if (height > bite.ux.Resizer.MIN_HEIGHT_ || mousePos.y >= p1.y) {
p1.y += delta.y;
}
break;
}
};
/**
* Constrains the element positions to within the viewport and maintain minimum
* dimensions.
* @param {!{x: number, y: number}} p0 The upper left corener.
* @param {!{x: number, y: number}} p1 The lower right corner.
* @param {bite.ux.Resizer.Mode_} mode Id for the resizer that moved.
* @private
*/
bite.ux.Resizer.constrainElement_ = function(p0, p1, mode) {
// Compute the screen size.
var viewportDim = goog.dom.getViewportSize();
// Constrain positions.
if (p0.x < 0) {
p0.x = 0;
}
if (p1.x > viewportDim.width) {
p1.x = viewportDim.width - 1; // Compensate for pixels starting at 0.
}
if (p0.y < 0) {
p0.y = 0;
}
if (p1.y > viewportDim.height) {
p1.y = viewportDim.height - 1; // Compensate for pixels starting at 0.
}
// Constrain dimensions
var dim = {width: p1.x - p0.x - 1, height: p1.y - p0.y - 1};
// By checking the mode, I can guarantee the change in size will not
// invalidate the positions of the corners relative to the viewport. This
// assumes the element is properly positioned and sized to begin with.
if (dim.width < bite.ux.Resizer.MIN_WIDTH_) {
switch (mode) {
case bite.ux.Resizer.Mode_.NW:
case bite.ux.Resizer.Mode_.SW:
case bite.ux.Resizer.Mode_.W:
p0.x = p1.x - bite.ux.Resizer.MIN_WIDTH_ + 1;
break;
case bite.ux.Resizer.Mode_.E:
case bite.ux.Resizer.Mode_.NE:
case bite.ux.Resizer.Mode_.SE:
p1.x = p0.x + bite.ux.Resizer.MIN_WIDTH_ - 1;
break;
}
}
if (dim.height < bite.ux.Resizer.MIN_HEIGHT_) {
switch (mode) {
case bite.ux.Resizer.Mode_.N:
case bite.ux.Resizer.Mode_.NE:
case bite.ux.Resizer.Mode_.NW:
p0.y = p1.y - bite.ux.Resizer.MIN_HEIGHT_ + 1;
break;
case bite.ux.Resizer.Mode_.S:
case bite.ux.Resizer.Mode_.SE:
case bite.ux.Resizer.Mode_.SW:
p1.y = p0.y + bite.ux.Resizer.MIN_HEIGHT_ - 1;
break;
}
}
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Provides utilities for dragging a container and allowing an
* element to dock with the viewport.
*
* Assumption: The elements referenced by this class are not modified while
* the dragging action is underway.
*
* TODO(jason.stredwick): Consider making callback a signal.
* TODO(jason.stredwick): Consider making the callback fire onMove rather than
* onRelease.
*
* @author ralphj@google.com (Julie Ralph)
* @author jason.stredwick@gmail.com (Jason Stredwick)
*/
goog.provide('bite.ux.Dragger');
goog.require('common.dom.element');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventHandler');
/**
* Provides a class for managing element dragging.
* @param {!Element} relativeElement An element to move relative to the
* dragTarget. This is commonly a container that has the dragTarget as a
* child element. Give the dragTarget if it is the element to move.
* @param {!Element} dragTarget The "draggable" element. Often this is a
* header for a container.
* @param {function()=} opt_draggedCallback A callback function fired upon
* completion of a dragging action.
* @constructor
*/
bite.ux.Dragger = function(relativeElement, dragTarget, opt_draggedCallback) {
/**
* An element to move relative to the dragTarget. This is commonly a
* container that has the dragTarget as a child element. Give the dragTarget
* if it is the element to move.
* @type {!Element}
* @private
*/
this.relativeElement_ = relativeElement;
/**
* The "draggable" element. Often this is a header for a container.
* @type {!Element}
* @private
*/
this.dragTarget_ = dragTarget;
/**
* Callback on drag release.
* @type {function()}
* @private
*/
this.draggedCallback_ = opt_draggedCallback || function() {};
/**
* The current side that the container is docked onto.
* @type {bite.ux.Dragger.Side_}
* @private
*/
this.dockSide_ = bite.ux.Dragger.Side_.NONE;
/**
* Whether or not currently dragging.
* @type {boolean}
* @private
*/
this.isDragging_ = false;
/**
* When the user first clicks the drag target, dragOffset_ is the vector from
* mouse to the container's upper left corner. This vector is used to keep
* the same relative position between the mouse and the container. When the
* mouse moves too close to the border, this vector is not updated in order
* preserve original offset when the mouse in back within a valid range.
* @type {!{x: number, y: number}}
* @private
*/
this.dragOffset_ = {x: 0, y: 0};
/**
* An array of listener keys for dragging.
* @type {!Array.<number>}
* @private
*/
this.dragListenerKeys_ = [];
/**
* Handles the event listeners.
* @type {!goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler();
this.eventHandler_.listen(this.dragTarget_, goog.events.EventType.MOUSEDOWN,
goog.bind(this.onMouseDown_, this));
};
/**
* Sides of the screen that the console can dock onto.
* @enum {string}
* @private
*/
bite.ux.Dragger.Side_ = {
BOTTOM: 'bottom',
LEFT: 'left',
RIGHT: 'right',
TOP: 'top',
NONE: 'none'
};
/**
* Destroy the object by cleaning up its allocated items.
*/
bite.ux.Dragger.prototype.destroy = function() {
this.draggedCallback = function() {};
this.onMouseUp_();
this.eventHandler_.removeAll();
this.relativeElement_ = /** @type {!Element} */ (null);
this.dragElement_ = /** @type {!Element} */ (null);
};
/**
* Recalculates if the managed element is updated externally.
*/
bite.ux.Dragger.prototype.recalculate = function() {
};
/**
* Changes the style of the container when it is docked to one side of the
* screen.
* @private
*/
bite.ux.Dragger.prototype.dock_ = function() {
var pos = common.dom.element.getPosition(this.relativeElement_);
var dim = common.dom.element.getSize(this.relativeElement_);
var viewportDim = goog.dom.getViewportSize();
var maxTop = viewportDim.height - dim.height;
var maxLeft = viewportDim.width - dim.width;
// Remove all docking styles from the element.
goog.dom.classes.remove(this.relativeElement_,
'bite-container-top-dock',
'bite-container-bottom-dock',
'bite-container-left-dock',
'bite-container-right-dock');
// Add appropriate docking style for element.
if (pos.x <= 0) {
this.dockSide_ = bite.ux.Dragger.Side_.LEFT;
goog.dom.classes.add(this.relativeElement_, 'bite-container-left-dock');
} else if (pos.y <= 0) {
this.dockSide_ = bite.ux.Dragger.Side_.TOP;
goog.dom.classes.add(this.relativeElement_, 'bite-container-top-dock');
} else if (pos.x >= maxLeft) {
this.dockSide_ = bite.ux.Dragger.Side_.RIGHT;
goog.dom.classes.add(this.relativeElement_, 'bite-container-right-dock');
} else if (pos.y >= maxTop) {
this.dockSide_ = bite.ux.Dragger.Side_.BOTTOM;
goog.dom.classes.add(this.relativeElement_, 'bite-container-bottom-dock');
} else {
this.dockSide_ = bite.ux.Dragger.Side_.NONE;
}
};
/**
* Handles mouse down event on the drag target; i.e. select the associated
* container for dragging.
* @param {!goog.events.BrowserEvent} e A mouse event from the drag target
* being clicked.
* @private
*/
bite.ux.Dragger.prototype.onMouseDown_ = function(e) {
// Do not begin dragging if already resizing or on right click.
if (this.isDragging_ || !e.isMouseActionButton()) {
return;
}
this.isDragging_ = true;
/**
* When the user first clicks the drag target, dragOffset_ is the vector from
* mouse to the container's upper left corner. This vector is used to keep
* the same relative position between the mouse and the container. When the
* mouse moves too close to the border, this vector is not updated in order
* preserve original offset when the mouse in back within a valid range.
*/
var pos = common.dom.element.getPosition(this.relativeElement_);
this.dragOffset_ = {x: pos.x - e.clientX,
y: pos.y - e.clientY};
// Set handlers for moving and releasing the mouse while the mouse button
// is down.
this.dragListenerKeys_.push(goog.events.listen(
goog.dom.getDocument(), goog.events.EventType.MOUSEMOVE,
goog.bind(this.onMouseMove_, this)));
this.dragListenerKeys_.push(goog.events.listen(
goog.dom.getDocument(), goog.events.EventType.MOUSEUP,
goog.bind(this.onMouseUp_, this, e.clientX, e.clientY)));
// Prevent text from being selected while dragging.
e.preventDefault();
};
/**
* Handles the container being dragged.
* @param {!Event} e A mouse event from the drag target.
* @private
*/
bite.ux.Dragger.prototype.onMouseMove_ = function(e) {
// Compute the new position of the container.
var targetX = e.clientX + this.dragOffset_.x;
var targetY = e.clientY + this.dragOffset_.y;
// Keep the container bounded within the browser viewport.
var dim = common.dom.element.getSize(this.relativeElement_);
var viewportDim = goog.dom.getViewportSize();
var maxTop = viewportDim.height - dim.height;
var maxLeft = viewportDim.width - dim.width;
if (targetX < 0) {
targetX = 0;
} else if (targetX > maxLeft) {
targetX = maxLeft;
}
if (targetY < 0) {
targetY = 0;
} else if (targetY > maxTop) {
targetY = maxTop;
}
// Update the target's position.
common.dom.element.setPosition(this.relativeElement_,
{x: targetX, y: targetY});
// Dock/undock container if appropriate.
this.dock_();
};
/**
* Handles a mouse up event releasing the container when it's being dragged.
* @private
*/
bite.ux.Dragger.prototype.onMouseUp_ = function() {
while (this.dragListenerKeys_.length > 0) {
goog.events.unlistenByKey(this.dragListenerKeys_.pop());
}
this.isDragging_ = false;
this.draggedCallback_(); // Call user-specified release callback.
};
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the BITE container.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.require('Bite.Constants');
goog.require('bite.ux.Container');
goog.require('goog.dom');
goog.require('goog.json');
goog.require('goog.testing.PropertyReplacer');
var stubs = new goog.testing.PropertyReplacer();
var container = null;
/**
* Mocks the background script's GET_LOCAL_STORAGE.
* @param {Object} data Used to determine the action being requested.
* @param {Function} callback The callback.
*/
var mockSendRequest = function(data, callback) {
if (data['action'] == Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE) {
if (data['key'] ==
bite.ux.Container.Keys_.CONSOLE_LOCATION + 'test_console') {
var positionData = goog.json.serialize(
{position: {x: 20, y: 20},
size: {height: 450, width: 350}});
callback(positionData);
} else if (data['key'] == bite.ux.Container.Keys_.SHOWN_MESSAGES +
'shown_message') {
callback('t');
} else {
callback(null);
}
}
};
function setUp() {
initChrome();
stubs.set(chrome.extension, 'sendRequest', mockSendRequest);
}
function tearDown() {
if (container) {
container.remove();
container = null;
}
stubs.reset();
}
function testSetContentFromHtml() {
container = new bite.ux.Container('dev.biteserver.prom.google.com',
'test_console',
'Header',
'Subheader',
false);
assertEquals('test_console', container.getRoot().id);
container.setContentFromHtml('Test Paragraph');
assertEquals(
'Test Paragraph',
goog.dom.getElementByClass('bite-console-content').innerHTML);
container.remove();
assertNull(goog.dom.getElement('test_console'));
container = null;
}
function testSetContentFromElement() {
container = new bite.ux.Container('dev.biteserver.prom.google.com',
'test_console',
'Header',
'Subheader',
false);
var element = goog.dom.createDom('p', null, 'Test Paragraph');
container.setContentFromElement(element);
assertEquals(
'Test Paragraph',
goog.dom.getElementByClass('bite-console-content').innerHTML);
}
function testConsoleWithSavedLocation() {
var mockUpdatePosition = function(position) {
assertEquals(20, position.x);
assertEquals(20, position.y);
};
stubs.set(bite.client.Resizer, 'updatePosition', mockUpdatePosition);
container = new bite.ux.Container('dev.biteserver.prom.google.com',
'test_console',
'Header',
'Subheader',
true);
assertEquals(450, container.getRoot().clientHeight);
assertEquals(350, container.getRoot().clientWidth);
}
function testShowInfoMessage() {
container = new bite.ux.Container('dev.biteserver.prom.google.com',
'test_console',
'Header',
'Subheader',
false);
container.showInfoMessage('Message a');
container.showInfoMessage('Message b');
infobarInnerHTML =
goog.dom.getElementByClass('bite-console-infobar').innerHTML;
assertNotNull(infobarInnerHTML.match(/Message a/));
assertNotNull(infobarInnerHTML.match(/Message b/));
}
function testShowInfoMessageOnce() {
container = new bite.ux.Container('dev.biteserver.prom.google.com',
'test_console',
'Header',
'Subheader',
false);
container.showInfoMessageOnce('shown_message', 'Shown before');
container.showInfoMessageOnce('new_message', 'Never shown before');
infobarInnerHTML =
goog.dom.getElementByClass('bite-console-infobar').innerHTML;
assertNull(infobarInnerHTML.match(/Shown before/));
assertNotNull(infobarInnerHTML.match(/Never shown before/));
}
| JavaScript |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Tests for the BITE resizer.
*
* TODO (jason.stredwick): Add in revised unit test.
*
* @author ralphj@google.com (Julie Ralph)
*/
goog.require('bite.ux.Resizer');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
var stubs_ = new goog.testing.PropertyReplacer();
var sandbox;
var container;
/*
function getViewportSize() {
return new goog.math.Size(1000, 1000);
}
function setUp() {
stubs_.set(goog.dom, 'getViewportSize', getViewportSize);
sandbox = goog.dom.createDom('div', {
'id': 'sandbox',
'style': 'position:fixed;top:0px;left:0px;width:1000px;height:1000px'});
goog.dom.appendChild(document.body, sandbox);
container = goog.dom.createDom('div', {
'id': 'target',
'style': 'position:fixed;top:100px;left:101px;width:300px;height:301px'});
sandbox.appendChild(container);
}
function tearDown() {
goog.dom.removeNode(container);
container = null;
sandbox = null;
stubs_.reset();
goog.events.removeAll();
}
function testUpdate() {
var resizer = new bite.ux.Resizer(container, container);
assertEquals(300, resizer.getSize().width);
assertEquals(301, resizer.getSize().height);
assertEquals(101, resizer.getPosition().x);
assertEquals(100, resizer.getPosition().y);
resizer.updateSize({width: 400, height: 500});
resizer.updatePosition({x: 11, y: 12});
assertEquals(400, resizer.getSize().width);
assertEquals(500, resizer.getSize().height);
assertEquals(11, resizer.getPosition().x);
assertEquals(12, resizer.getPosition().y);
assertEquals('400px', container.style.width);
assertEquals('500px', container.style.height);
assertEquals('11px', container.style.left);
assertEquals('12px', container.style.top);
}
function testDrag() {
var resizer = new bite.ux.Resizer(container, container);
goog.testing.events.fireMouseDownEvent(
container,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 450, y: 450});
assertEquals('100px', container.style.top);
assertEquals('101px', container.style.left);
goog.testing.events.fireMouseMoveEvent(
container,
{x: 460, y: 470});
assertEquals('120px', container.style.top);
assertEquals('111px', container.style.left);
goog.testing.events.fireMouseUpEvent(
container,
{x: 460, y: 470});
assertEquals('120px', container.style.top);
assertEquals('111px', container.style.left);
}
function testSEResize() {
var resizer = new bite.ux.Resizer(container, container);
var seCorner = goog.dom.getElementByClass('se-resizer');
goog.testing.events.fireMouseDownEvent(
seCorner,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 800, y: 800});
goog.testing.events.fireMouseMoveEvent(
seCorner,
{x: 810, y: 820});
goog.testing.events.fireMouseUpEvent(
seCorner,
{x: 810, y: 820});
assertEquals('100px', container.style.top);
assertEquals('101px', container.style.left);
assertEquals('310px', container.style.width);
assertEquals('321px', container.style.height);
}
function testNWResize() {
var resizer = new bite.ux.Resizer(container, container);
var nwCorner = goog.dom.getElementByClass('nw-resizer');
goog.testing.events.fireMouseDownEvent(
nwCorner,
goog.events.BrowserEvent.MouseButton.LEFT,
{x: 800, y: 800});
goog.testing.events.fireMouseMoveEvent(
nwCorner,
{x: 790, y: 780});
goog.testing.events.fireMouseUpEvent(
nwCorner,
{x: 790, y: 780});
assertEquals('80px', container.style.top);
assertEquals('91px', container.style.left);
assertEquals('310px', container.style.width);
assertEquals('321px', container.style.height);
}
*/
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Declaration of external namespaces that must not be removed
* from compiled sources.
* @externs
* @author jmwaura@google.com (Jesse Mwaura)
*/
/**
* The google namespace for the maps api and loader.
* @suppress {duplicate}
* @noalias
*/
var google = {};
/** @type {!Object} */
google.loader;
/** @type {!Object} */
google.loader.ClientLocation;
/** @type {!Object} */
google.loader.ClientLocation.address;
/** @type {string} */
google.loader.ClientLocation.address.region;
/** @type {string} */
google.loader.ClientLocation.address.country_code;
/** @type {!Object} */
google.maps = {};
/** @typedef {{text: string, value: number}} */
google.maps.Distance;
/**
* Enumeration of DistanceMatrixElement Status codes.
* @enum {string}
*/
google.maps.DistanceMatrixElementStatus = {};
google.maps.DistanceMatrixElementStatus.NOT_FOUND;
google.maps.DistanceMatrixElementStatus.OK;
google.maps.DistanceMatrixElementStatus.ZERO_RESULTS;
/**
* Type definition for DistanceMatrixResponseElement.
* @typedef {{
* distance: google.maps.Distance,
* duration: google.maps.Duration,
* status: google.maps.DistanceMatrixElementStatus
* }}
*/
google.maps.DistanceMatrixResponseElement;
/**
* Constructs DistanceMatrixService instance.
* @constructor
*/
google.maps.DistanceMatrixService = function() {};
/**
* Retrieves autocomplete predictions based on the request object.
* @param {!Object} request The request object.
* @param {!function(!Object, google.maps.DistanceMatrixStatus)}
* callback The function to call when the request completes.
*/
google.maps.DistanceMatrixService.prototype.getDistanceMatrix =
function(request, callback) {};
/**
* Enumeration of DistanceMatrix Status codes.
* @enum {string}
*/
google.maps.DistanceMatrixStatus = {};
google.maps.DistanceMatrixStatus.INVALID_REQUEST;
google.maps.DistanceMatrixStatus.MAX_DIMENSIONS_EXCEEDED;
google.maps.DistanceMatrixStatus.MAX_ELEMENTS_EXCEEDED;
google.maps.DistanceMatrixStatus.OK;
google.maps.DistanceMatrixStatus.OVER_QUERY_LIMIT;
google.maps.DistanceMatrixStatus.REQUEST_DENIED;
google.maps.DistanceMatrixStatus.UNKNOWN_ERROR;
/** @typedef {{text: string, value: number}} */
google.maps.Duration;
/**
* Define the event namespace.
*/
google.maps.event;
/**
* Adds the given listener function to the given event name for the given
* object instance. Returns an identifier for this listener that can be used
* with removeListener().
* @param {Object} instance
* @param {string} eventName
* @param {Function} handler
* @return {google.maps.MapsEventListener}
*/
google.maps.event.addListener = function(instance, eventName, handler) {};
/**
* Removes all listeners for all events for the given instance.
* @param {Object} instance
*/
google.maps.event.clearInstanceListeners = function(instance) {};
/**
* Type definition for opaque MapsEventListener.
* @typedef {Object}
*/
google.maps.MapsEventListener;
/**
* Constructs a Geocoder instance.
* @constructor
*/
google.maps.Geocoder = function() {};
/**
* Geocode a request.
* @param {google.maps.GeocoderRequest} request
* @param {function(Array.<google.maps.GeocoderResult>,
* google.maps.GeocoderStatus)}
* callback
*/
google.maps.Geocoder.prototype.geocode = function(request, callback) {};
/**
* Type definition for a GeocoderRequest.
* @typedef {{
* address: string
* }}
*/
google.maps.GeocoderRequest;
/**
* Enumeration for GeocoderStatus.
* @enum {string}
*/
google.maps.GeocoderStatus = {};
google.maps.GeocoderStatus.ERROR;
google.maps.GeocoderStatus.INVALID_REQUEST;
google.maps.GeocoderStatus.OK;
google.maps.GeocoderStatus.OVER_QUERY_LIMIT;
google.maps.GeocoderStatus.REQUEST_DENIED;
google.maps.GeocoderStatus.UNKNOWN_ERROR;
google.maps.GeocoderStatus.ZERO_RESULTS;
/**
* Type definition for a GeocoderResult.
* @typedef {{
* address_components: Array.<google.maps.GeocoderAddressComponent>,
* formatted_address: string,
* geometry: google.maps.GeocoderGeometry,
* types: Array.<string>
* }}
*/
google.maps.GeocoderResult;
/**
* Type definition for GeocoderAddressComponent.
* @typedef {{
* long_name: string,
* short_name: string,
* types: Array.<string>
* }}
*/
google.maps.GeocoderAddressComponent;
/**
* Type definition for GeocoderGeometry.
* @typedef {{
* bounds: google.maps.LatLngBounds,
* location: google.maps.LatLng,
* location_type: google.maps.GeocoderLocationType,
* viewport: google.maps.LatLngBounds
* }}
*/
google.maps.GeocoderGeometry;
/**
* Enumeration of the types of locations returned from a geocode.
* @enum {string}
*/
google.maps.GeocoderLocationType = {};
google.maps.GeocoderLocationType.APPROXIMATE;
google.maps.GeocoderLocationType.GEOMETRIC_CENTER;
google.maps.GeocoderLocationType.RANGE_INTERPOLATED;
google.maps.GeocoderLocationType.ROOFTOP;
/**
* Constructs LatLng instance.
* @constructor
*/
google.maps.InfoWindow = function() {};
/**
* @param {google.maps.Map=} map
* @param {google.maps.Marker=} anchor
*/
google.maps.InfoWindow.prototype.open = function(map, anchor) {};
/**
* @param {string|Node} content
*/
google.maps.InfoWindow.prototype.setContent = function(content) {};
/**
* Closes the info window.
*/
google.maps.InfoWindow.prototype.close = function() {};
/**
* Constructs LatLng instance.
* @param {number} lat Latitude.
* @param {number} lng Longitude.
* @param {boolean=} noWrap Whether or not to disable wrapping.
* @constructor
*/
google.maps.LatLng = function(lat, lng, noWrap) {};
/**
* Compares two LatLng objects.
* @param {google.maps.LatLng} other LatLng to compare to.
* @return {boolean} Whether or not the LatLngs are equal.
*/
google.maps.LatLng.prototype.equals = function(other) {};
/**
* Returns the latitude in degrees.
* @return {number} The latitude.
*/
google.maps.LatLng.prototype.lat = function() {};
/**
* Returns the longitude in degrees.
* @return {number} The longitude.
*/
google.maps.LatLng.prototype.lng = function() {};
/**
* Converts to string representation.
* @return {string} The string representation.
*/
google.maps.LatLng.prototype.toString = function() {};
/**
* Returns a string of the form "lat,lng" for this LatLng.
* @param {number=} precision Number of decimal places to round to.
* @return {string} The string representation.
*/
google.maps.LatLng.prototype.toUrlValue = function(precision) {};
/**
* Constructs a LatLngBounds instance.
* @param {google.maps.LatLng=} sw The SW corner of the bounds.
* @param {google.maps.LatLng=} ne The NE corner of the bounds.
* @constructor
*/
google.maps.LatLngBounds = function(sw, ne) {};
/**
* Extends this bounds to contain the given point.
* @param {google.maps.LatLng} point Point to include in the bounds.
*/
google.maps.LatLngBounds.prototype.extend = function(point) {};
/**
* Constructs a Map instance.
* @param {Node} mapDiv The container element.
* @param {google.maps.MapOptions=} opts Initialization options.
* @constructor
*/
google.maps.Map = function(mapDiv, opts) {};
/**
* Type definition for MapOptions
* @typedef {{
* center: google.maps.LatLng,
* mapTypeId: google.maps.MapTypeId,
* maxZoom: number,
* zoom: number
* }}
*/
google.maps.MapOptions;
/**
* Sets the viewport to contain the given bounds.
* @param {google.maps.LatLngBounds} bounds The bounds to which to fit the
* the viewport.
*/
google.maps.Map.prototype.fitBounds = function(bounds) {};
/**
* Constructs a Marker instance.
* @param {google.maps.MarkerOptions=} opts Initialization options.
* @constructor
*/
google.maps.Marker = function(opts) {};
/**
* Renders the marker on the specified map or panorama.
* If map is set to null, the marker will be removed.
* @param {google.maps.Map} map The map on which to render the marker.
*/
google.maps.Marker.prototype.setMap = function(map) {};
/**
* Sets the marker options.
* @param {google.maps.MarkerOptions} opts The options to set.
*/
google.maps.Marker.prototype.setOptions = function(opts) {};
/**
* Sets the marker icon.
* @param {google.maps.MarkerImage} icon
*/
google.maps.Marker.prototype.setIcon = function(icon) {};
/**
* Type definition for MarkerOptions
* @typedef {{
* clickable: boolean,
* draggable: boolean,
* icon: (google.maps.MarkerImage|string),
* map: google.maps.Map,
* position: google.maps.LatLng,
* raiseOnDrag: boolean,
* shadow: (google.maps.MarkerImage|string),
* title: string,
* visible: boolean
* }}
*/
google.maps.MarkerOptions;
/**
* Constructs a MarkerImage instance.
* @param {string} url Icon URL
* @param {google.maps.Size=} size Icon size.
* @param {google.maps.Point=} origin Origin within sprite.
* @param {google.maps.Point=} anchor Point at which to anchor to map location.
* @param {google.maps.Point=} scaledSize Size of entire sprite after scaling.
* @constructor
*/
google.maps.MarkerImage = function(url, size, origin, anchor, scaledSize) {};
/**
* @type {string}
*/
google.maps.MarkerImage.prototype.url;
/**
* @type {google.maps.Point}
*/
google.maps.MarkerImage.prototype.origin;
/**
* @type {google.maps.Point}
*/
google.maps.MarkerImage.prototype.anchor;
/**
* @type {google.maps.Point}
*/
google.maps.MarkerImage.prototype.scaledSize;
/**
* @type {google.maps.Size}
*/
google.maps.MarkerImage.prototype.size;
/**
* Enumeration of MapTypeIds.
* @enum {string}
*/
google.maps.MapTypeId = {};
google.maps.MapTypeId.HYBRID;
google.maps.MapTypeId.ROADMAP;
google.maps.MapTypeId.SATELLITE;
google.maps.MapTypeId.TERRAIN;
/**
* Constructs a Size object.
* @param {number} width The width along the x-axis, in pixels.
* @param {number} height The height along the y-axis, in pixels.
* @constructor
*/
google.maps.Size = function(width, height) {};
/**
* @type {number}
*/
google.maps.Size.prototype.width;
/**
* @type {number}
*/
google.maps.Size.prototype.height;
/**
* Constructs a Point object.
* @param {number} x The X coordinate.
* @param {number} y The Y coordinate.
* @constructor
*/
google.maps.Point = function(x, y) {};
/**
* @type {number}
*/
google.maps.Point.prototype.x;
/**
* @type {number}
*/
google.maps.Point.prototype.y;
/** @type {!Object} */
google.maps.places;
/**
* Constructs AutocompleteService instance.
* @constructor
*/
google.maps.places.AutocompleteService = function() {};
/**
* Retrieves autocomplete predictions based on the request object.
* @param {!Object} request The request object.
* @param {!function(Array.<!Object>, google.maps.places.PlacesServiceStatus)}
* callback The function to call when the request completes.
*/
google.maps.places.AutocompleteService.prototype.getPlacePredictions =
function(request, callback) {};
/**
* Enumeration of PlacesService Status codes.
* @enum {string}
*/
google.maps.places.PlacesServiceStatus = {};
google.maps.places.PlacesServiceStatus.OK;
google.maps.places.PlacesServiceStatus.ZERO_RESULTS;
google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT;
google.maps.places.PlacesServiceStatus.REQUEST_DENIED;
google.maps.places.PlacesServiceStatus.INVALID_REQUEST;
/**
* Enumeration of TravelModes.
* @enum {string}
*/
google.maps.TravelMode = {};
google.maps.TravelMode.BICYCLING;
google.maps.TravelMode.DRIVING;
google.maps.TravelMode.TRANSIT;
google.maps.TravelMode.WALKING;
/**
* Enumeration of UnitSystems.
* @enum {string}
*/
google.maps.UnitSystem = {};
google.maps.UnitSystem.IMPERIAL;
google.maps.UnitSystem.METRIC;
/**
* The main namespace for the Google API client.
* @suppress {duplicate}
* @noalias
*/
var gapi = {};
/** @type {!Object} */
gapi.client;
/**
* @param {Object} args An object encapsulating arguments to this method.
* @return {!gapi.client.HttpRequest|undefined} Return the request object if
* no callback is supplied in the args.
*/
gapi.client.request = function(args) {};
/**
* @param {string} key The api key to append to requests.
*/
gapi.client.setApiKey = function(key) {};
/**
* @constructor
*/
gapi.client.HttpRequest = function() {};
/**
* Executes the request and calls the given callback when done.
* @param {!function((!Object|boolean), string)} callback The function to
* execute when the request returns.
*/
gapi.client.HttpRequest.prototype.execute = function(callback) {};
/**
* Asynchronous version of the Google Analytics tracker.
*/
var _gaq;
/**
* Enqueue an analytics command.
* @param {...(function()|Array.<Object>)} command The command function or args.
*/
_gaq.push = function(command) {};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generally useful utility methods.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.util');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.object');
goog.require('goog.string');
/**
* Selectively changes text to title-case. Will not modify mixed case strings.
* Words in exception list are uppercased.
* @param {string} str String value.
* @param {Array.<string>=} opt_except Substring words to avoid replacing.
* @return {string} Title-case string.
*/
vit.util.selectiveTitleCase = function(str, opt_except) {
if (!(str == str.toUpperCase() || str == str.toLowerCase())) {
// String is mixed case. Bail.
return str;
}
str = goog.string.toTitleCase(str.toLowerCase());
if (!opt_except) {
return str;
}
var exceptions = goog.array.map(opt_except, function(val) {
return goog.string.regExpEscape(val);
});
var re = new RegExp('(^|\\s)(' + exceptions.join('|') + ')($|\\s)', 'gi');
return str.replace(re, function(all, before, exception, after) {
return before + exception.toUpperCase() + after;
});
};
/**
* Generates a random string suitable for use as an identifier.
* @return {string} Random string.
*/
vit.util.generateIdentifier = function() {
return 'i' + Math.random().toString(36).substring(2);
};
/**
* Loads dependency javascript files in parallel.
* @param {Array.<{uri: goog.Uri, callbackParam: string}>} uriList The list of
* URIs to load and the parameter to use to specify the callback.
* @param {Function} callback The method to call when all files are loaded.
* TODO(jmwaura): Handle errors and support URIs that don't take callbacks.
*/
vit.util.load = function(uriList, callback) {
var uriMap = {};
for (var i = 0; i < uriList.length; i++) {
var uri = uriList[i].uri;
var callbackParam = uriList[i].callbackParam || 'callback';
var identifier = vit.util.generateIdentifier();
while (uriMap[identifier] || window[identifier]) {
identifier = vit.util.generateIdentifier();
}
uri.setParameterValue(callbackParam, identifier);
uriMap[identifier] = uri;
}
var fn = function(uriMap, identifier, callback) {
delete uriMap[identifier];
try {
delete window[identifier];
} catch (e) {
// Window properties can not be deleted in IE8.
window[identifier] = undefined;
}
if (goog.object.isEmpty(uriMap)) {
callback();
}
};
goog.object.forEach(uriMap, function(uri, identifier) {
// Add callback to global scope.
window[identifier] = goog.partial(fn, uriMap, identifier, callback);
// Add script tag to head.
var script = goog.dom.createElement(goog.dom.TagName.SCRIPT);
goog.dom.setProperties(script, {
'type': 'text/javascript',
'charset': 'UTF-8',
'src': uri.toString()
});
var headEls = document.getElementsByTagName(goog.dom.TagName.HEAD);
var head = null;
if (!headEls || goog.array.isEmpty(headEls)) {
head = document.documentElement;
} else {
head = headEls[0];
}
head.appendChild(script);
});
};
/**
* Adds 'disabled' and 'enabled' css classes to elements.
* @param {Element} el Element to add classes to.
* @param {boolean} enabled Whether element should be enabled.
*/
vit.util.setCssEnabled = function(el, enabled) {
if (enabled) {
goog.dom.classes.addRemove(el, goog.getCssName('disabled'),
goog.getCssName('enabled'));
} else {
goog.dom.classes.addRemove(el, goog.getCssName('enabled'),
goog.getCssName('disabled'));
}
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview A client wrapper for Google Analytics.
* @author jasonbrooks@google.com (Jason Brooks)
*/
goog.provide('vit.analytics.Analytics');
/**
* A thin client wrapper for Google Analytics.
* @constructor
*/
vit.analytics.Analytics = function() {
/**
* The analytics command queue in the global scope.
*/
_gaq = goog.global['_gaq'] || [];
_gaq.push(['_setAccount', vit.analytics.Analytics.KEY]);
};
goog.addSingletonGetter(vit.analytics.Analytics);
/**
* The analytics account key.
* @define {string} Analytics account key.
*/
vit.analytics.Analytics.KEY = '';
/**
* Tracks a page view.
*/
vit.analytics.Analytics.prototype.trackPageview = function() {
_gaq.push(['_trackPageview']);
};
/**
* Tracks an event.
* @param {string} category The general event category (e.g. "Videos").
* @param {string} action The action for the event (e.g. "Play").
* @param {string} opt_label An optional descriptor for the event.
* @param {number} opt_value An optional integer value associated with the
* event.
* @param {boolean} opt_noninteraction Default value is false. By default, the
* event hit sent by trackEvent will impact a visitor's bounce rate. By
* setting this param to true, this event hit will not be used in bounce
* rate calculations.
*/
vit.analytics.Analytics.prototype.trackEvent = function(
category, action, opt_label, opt_value, opt_noninteraction) {
_gaq.push(['_trackEvent',
category, action, opt_label, opt_value, opt_noninteraction]);
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Class that adds the Voter Information tool to an element
* on the page and manages configuration and sizing.
*
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.Loader');
goog.require('goog.Disposable');
goog.require('goog.Uri');
goog.require('goog.string');
goog.require('goog.style');
goog.require('vit.agent.Xpc');
/**
* Constructs the Voter Information Tool loader class.
* @constructor
*/
vit.Loader = function() {
/**
* The xpc agent that handles communication between this page and the
* VIT frame.
* @type {vit.agent.Xpc}
* @private
*/
this.xpc_;
/**
* The element inwhich to draw the tool.
* @type {Element}
* @private
*/
this.el_;
};
/**
* The base url which to load the Voter Information Tool
* @define {string} Voter Information Tool URL.
*/
vit.Loader.TOOL_URL = 'https://voter-info-tool.appspot.com/';
/**
* Load the Voter Information Tool in the provided element.
* @param {string} url The url of the page to load.
* @param {!Object} config The configuration object to pass to the tool.
* @param {!Element} el The element in which to draw the tool.
*/
vit.Loader.prototype.load = function(url, config, el) {
if (!url) {
throw new Error('No URL configured for Voter Information Tool');
}
if (!el || !(el instanceof Element)) {
throw new Error('Invalid container element or none specified.');
}
if (!goog.string.endsWith(url, '/')) {
url = url + '/';
}
url += 'vit';
config['locale'] = config['locale'] || 'en';
url += '_' + config['locale'];
url += config['suppress_header'] ? '_noheader' : '';
url += '.html';
var div = goog.dom.createElement('div');
div.style.border = 'none';
div.style.height = '450px';
div.style.margin = '0';
div.style.overflow = 'hidden';
div.style.padding = '0';
goog.dom.removeChildren(el);
goog.dom.appendChild(el, div);
this.el_ = div;
this.xpc_ = new vit.agent.Xpc();
this.xpc_.initOuter(url, this.el_, function(iframe) {
iframe.setAttribute('scrolling', 'no');
iframe.style.border = 'none';
iframe.style.height = '100%';
iframe.style.overflow = 'hidden';
iframe.style.width = '100%';
});
this.xpc_.registerService(vit.agent.Xpc.Service.RESIZE,
goog.bind(this.handleResize_, this));
this.xpc_.connect(goog.bind(function(config) {
this.xpc_.send(vit.agent.Xpc.Service.CONFIG, goog.json.serialize(config));
}, this, config));
};
/**
* Handle resize messages triggered by height changes in the tool.
* @param {(!Object | string)} height New client height of the tool in pixels.
* @private
*/
vit.Loader.prototype.handleResize_ = function(height) {
if (! goog.isString(height)) {
throw new Error('Height must be a string.');
}
if (goog.string.isNumeric(height)) {
height = height + 'px';
}
goog.style.setHeight(this.el_, /** @type {string} */ (height));
};
/**
* Main entry point for VIT Loader.
* @param {Object=} opt_config Configuration object.
* @param {Element|string=} opt_el Element in which to render the tool.
* @return {vit.Loader} Loader instance.
* @private
*/
vit.load_ = function(opt_config, opt_el) {
var loader = new vit.Loader();
var vitConfig = opt_config || {};
var vitEl = /** @type {!Element} */ opt_el && goog.dom.getElement(opt_el) ||
goog.dom.getElement('_vit');
var vitUrl = vit.Loader.TOOL_URL;
if (vitConfig['url']) {
vitUrl = vitConfig['url'];
delete vitConfig['url'];
}
vitConfig['referrer'] = window.location.href;
loader.load(vitUrl, vitConfig, vitEl);
return loader;
};
goog.exportSymbol('vit.load', vit.load_);
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Agent for cross-page communication.
*
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.agent.Xpc');
goog.require('goog.Disposable');
goog.require('goog.Uri');
goog.require('goog.debug.Logger');
goog.require('goog.json');
goog.require('goog.net.xpc.CrossPageChannel');
/**
* Constructs an xpc agent.
* @constructor
* @extends goog.Disposable
*/
vit.agent.Xpc = function() {
goog.base(this);
/**
* The xpc channel.
* @type {goog.net.xpc.CrossPageChannel}
* @private
*/
this.channel_;
};
goog.inherits(vit.agent.Xpc, goog.Disposable);
/**
* Services for communication between outer and inner.
* @enum {string}
*/
vit.agent.Xpc.Service = {
CONFIG: 'config',
RESIZE: 'resize'
};
/**
* Set up the channel as the outer frame.
* @param {!string} peerUri URI to connect to as peer.
* @param {!Element} containerEl Container element in which to create a frame.
* @param {function(Element)=} opt_iframeCb Callback to set iframe properties.
*/
vit.agent.Xpc.prototype.initOuter =
function(peerUri, containerEl, opt_iframeCb) {
var cfg = {};
cfg[goog.net.xpc.CfgFields.TRANSPORT] =
goog.net.xpc.TransportTypes.NATIVE_MESSAGING;
cfg[goog.net.xpc.CfgFields.PEER_URI] = peerUri;
this.channel_ = new goog.net.xpc.CrossPageChannel(cfg);
this.channel_.createPeerIframe(containerEl, opt_iframeCb);
};
/**
* Set up the channel as an inner frame.
* @return {boolean} Whether or not the channel was successfully set up.
*/
vit.agent.Xpc.prototype.initInner = function() {
// Get the channel configuration from the url parameters.
var xpc = (new goog.Uri(window.location.href)).getParameterValue('xpc');
if (!xpc) {
return false;
}
var cfg = goog.json.parse(xpc);
this.channel_ = new goog.net.xpc.CrossPageChannel(cfg);
return true;
};
/**
* Make an xpc connection.
* @param {function(!Object)=} opt_callback Function to call when connected.
*/
vit.agent.Xpc.prototype.connect = function(opt_callback) {
if (this.channel_) {
this.channel_.connect(opt_callback);
}
};
/**
* Register an xpc service.
* @param {vit.agent.Xpc.Service} service Service to register.
* @param {function((!Object | string))} handler Handler function for this
* service.
*/
vit.agent.Xpc.prototype.registerService = function(service, handler) {
if (this.channel_) {
this.channel_.registerService(service, handler);
}
};
/**
* Send a payload to an xpc service.
* @param {vit.agent.Xpc.Service} service Service to register.
* @param {(!Object | string)} payload Payload to send to service.
*/
vit.agent.Xpc.prototype.send = function(service, payload) {
if (this.channel_) {
this.channel_.send(service, payload);
}
};
/**
* @override
*/
vit.agent.Xpc.prototype.disposeInternal = function() {
if (this.channel_) {
this.channel_.dispose();
}
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Agent to interface the Civic Info API with the VIT PubSub
* infrastructure.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.agent.CivicInfo');
goog.require('goog.Disposable');
goog.require('vit.api.CivicInfo');
goog.require('vit.api.CivicInfo.Status');
goog.require('vit.context.Context');
goog.require('vit.context.NoticeType');
goog.require('vit.templates.errors.addressUnparseable');
goog.require('vit.templates.errors.electionOver');
goog.require('vit.templates.errors.electionUnknown');
goog.require('vit.templates.errors.genericFailure');
goog.require('vit.templates.errors.multipleSegments');
goog.require('vit.templates.errors.noStreetSegment');
goog.require('vit.templates.errors.suggestOfficial');
goog.require('vit.templates.errors.testElection');
/**
* Construct Civic Info agent.
* @param {vit.context.Context} context The application context.
* @constructor
* @extends {goog.Disposable}
*/
vit.agent.CivicInfo = function(context) {
goog.base(this);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The Civic Info API.
* @type {vit.api.CivicInfo}
* @private
*/
this.api_ = new vit.api.CivicInfo(context);
this.registerDisposable(this.api_);
/**
* Subscription ID for address change notifications.
* @type {?number}
* @private
*/
this.addressSubscription_;
/**
* Subscription ID for region change notifications.
* @type {?number}
* @private
*/
this.regionSubscription_;
};
goog.inherits(vit.agent.CivicInfo, goog.Disposable);
/**
* Initialize this agent.
* @return {vit.agent.CivicInfo} return this agent.
*/
vit.agent.CivicInfo.prototype.init = function() {
var addressChangeHandler =
goog.bind(this.handleAddressChange_, this, vit.context.ADDRESS);
var regionChangeHandler =
goog.bind(this.handleAddressChange_, this, vit.context.REGION);
/**
* Subscription ID for address change notifications.
* @type {number}
* @private
*/
this.addressSubscription_ =
this.context_.subscribe(vit.context.ADDRESS, addressChangeHandler);
/**
* Subscription ID for region change notifications.
* @type {number}
* @private
*/
this.regionSubscription_ =
this.context_.subscribe(vit.context.REGION, regionChangeHandler);
return this;
};
/**
* Handle a change in the address.
* @param {string} trigger Trigger that caused a lookup.
* @param {?string} newAddress New address.
* @param {?string} oldAddress Old address.
* @private
*/
vit.agent.CivicInfo.prototype.handleAddressChange_ =
function(trigger, newAddress, oldAddress) {
newAddress = /** @type {string} */ (newAddress) || '';
if (newAddress) {
this.api_.lookup(newAddress,
goog.bind(this.handleApiResponse_, this, trigger)
);
}
};
/**
* Handle a response from the api in the address.
* @param {string} trigger Trigger that caused a lookup.
* @param {!vit.api.CivicInfo.Response|boolean} result Result object.
* @param {string} rawResponse Raw JSON formatted response.
* @private
*/
vit.agent.CivicInfo.prototype.handleApiResponse_ =
function(trigger, result, rawResponse) {
if (!result) {
this.context_.set(vit.context.NOTICE,
vit.agent.CivicInfo
.noticeMap[vit.api.CivicInfo.Status.REQUEST_FAILURE](result));
this.context_.set(vit.context.CIVIC_INFO, null);
return;
}
var resultStatus = result.status;
var notice = null;
if (resultStatus != vit.api.CivicInfo.Status.SUCCESS) {
if (!(resultStatus == vit.api.CivicInfo.Status.ADDRESS_UNPARSEABLE &&
trigger == vit.context.REGION)) {
if (goog.object.containsKey(vit.agent.CivicInfo.noticeMap,
resultStatus)) {
notice = vit.agent.CivicInfo.noticeMap[resultStatus](result);
} else {
notice = vit.agent.CivicInfo.generateMsgGenericFailure(result);
}
}
}
if (result.election.name.search(/(^| )test( |$)/i) >= 0) {
notice = vit.agent.CivicInfo.generateMsgTestElection(result);
}
this.context_.set(vit.context.NOTICE, notice);
// Set the request trigger on the response.
result.requestTrigger = trigger;
this.context_.set(vit.context.CIVIC_INFO, result);
};
/**
* @override
*/
vit.agent.CivicInfo.prototype.disposeInternal = function() {
if (goog.isDefAndNotNull(this.addressSubscription_)) {
this.context_.unsubscribeById(this.addressSubscription_);
}
if (goog.isDefAndNotNull(this.regionSubscription_)) {
this.context_.unsubscribeById(this.regionSubscription_);
}
this.context_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Generates a message that suggests where the user may be able to find
* more information.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {string} The official website suggestion.
*/
vit.agent.CivicInfo.suggestOfficialWebsite = function(response) {
var params = {};
if (response && response.state && response.state[0] &&
response.state[0].electionAdministrationBody &&
response.state[0].electionAdministrationBody.name &&
response.state[0].electionAdministrationBody.votingLocationFinderUrl) {
params = {
url: response.state[0].electionAdministrationBody.votingLocationFinderUrl,
electionOfficial: response.state[0].electionAdministrationBody.name
};
}
return vit.templates.errors.suggestOfficial(params);
};
/**
* Generates an notice given a type, message text, and a response object.
* @param {vit.context.NoticeType} type Type of message to generate.
* @param {string} text Message text.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsg = function(type, text, response) {
return {
type: type,
title: text,
desc: vit.agent.CivicInfo.suggestOfficialWebsite(response)
};
};
/**
* Generates a generic error message.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgGenericFailure = function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.ERROR,
vit.templates.errors.genericFailure(), response);
};
/**
* Generates a message for the case where no street segment is found.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgNoStreetSegmentFound = function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.INFO,
vit.templates.errors.noStreetSegment(), response);
};
/**
* Generates a message for the case where the address could not be parsed.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgAddressUnparseable = function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.ERROR,
vit.templates.errors.addressUnparseable(), response);
};
/**
* Generates a message for the case where there is more than one matching street
* segment.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgMultipleStreetSegmentsFound =
function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.ERROR,
vit.templates.errors.multipleSegments(), response);
};
/**
* Generates a message for the case where the election has ended.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgElectionOver = function(response) {
var params = {};
if (response && response.election && response.election.name &&
response.election.electionDay) {
params = {
name: response.election.name,
date: response.election.electionDay
};
}
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.INFO,
vit.templates.errors.electionOver(params), response);
};
/**
* Generates a message for the case where there is no matching election.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgElectionUnknown = function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.WARNING,
vit.templates.errors.electionUnknown(), response);
};
/**
* Generates a message for when the api returns a test election.
* @param {boolean | vit.api.CivicInfo.Response} response The api response.
* @return {vit.context.Notice} The notice.
*/
vit.agent.CivicInfo.generateMsgTestElection = function(response) {
return vit.agent.CivicInfo.generateMsg(vit.context.NoticeType.WARNING,
vit.templates.errors.testElection(), response);
};
/**
* Map of expected notices to their message generator functions.
* @type {Object.<vit.api.CivicInfo.Status,
* function((boolean | vit.api.CivicInfo.Response))>}
*/
vit.agent.CivicInfo.noticeMap = function() {
var map = {};
var status = vit.api.CivicInfo.Status;
map[vit.api.CivicInfo.Status.NO_STREET_SEGMENT_FOUND] =
vit.agent.CivicInfo.generateMsgNoStreetSegmentFound;
map[vit.api.CivicInfo.Status.ADDRESS_UNPARSEABLE] =
vit.agent.CivicInfo.generateMsgAddressUnparseable;
map[vit.api.CivicInfo.Status.NO_ADDRESS_PARAMETER] =
vit.agent.CivicInfo.generateMsgGenericFailure;
map[vit.api.CivicInfo.Status.MULTIPLE_STREET_SEGMENTS_FOUND] =
vit.agent.CivicInfo.generateMsgMultipleStreetSegmentsFound;
map[vit.api.CivicInfo.Status.ELECTION_OVER] =
vit.agent.CivicInfo.generateMsgElectionOver;
map[vit.api.CivicInfo.Status.ELECTION_UNKNOWN] =
vit.agent.CivicInfo.generateMsgElectionUnknown;
map[vit.api.CivicInfo.Status.INTERNAL_LOOKUP_FAILURE] =
vit.agent.CivicInfo.generateMsgGenericFailure;
map[vit.api.CivicInfo.Status.REQUEST_FAILURE] =
vit.agent.CivicInfo.generateMsgGenericFailure;
return map;
}();
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Agent to interface the Places Autocomplete API with the VIT
* PubSub infrastructure.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.agent.Autocomplete');
goog.require('goog.Disposable');
goog.require('vit.api.Autocomplete');
goog.require('vit.context.Context');
/**
* Construct Autocomplete agent.
* @param {vit.context.Context} context The application context.
* @constructor
* @extends {goog.Disposable}
*/
vit.agent.Autocomplete = function(context) {
goog.base(this);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The Autocomplete API.
* @type {vit.api.Autocomplete
}
* @private
*/
this.api_ = new vit.api.Autocomplete(context);
this.registerDisposable(this.api_);
/**
* Subscription ID for textbox change notifications.
* @type {?number}
* @private
*/
this.addressEntrySubscription_;
/**
* Suggestions from the api.
* @type {Array.<string>}
* @private
*/
this.suggestions_ = [];
/**
* Lower case suggestions from the api. Stored in this form so that they're
* not converted each time.
* @type {Array.<string>}
* @private
*/
this.suggestionsLower_ = [];
/**
* Last failed prefix. If no suggestions were made for this prefix,
* no api requests will be made for entries for which this is a prefix.
* @type {?string}
* @private
*/
this.failedPrefix_;
};
goog.inherits(vit.agent.Autocomplete, goog.Disposable);
/**
* Initialize this agent.
* @return {vit.agent.Autocomplete
} return this agent.
*/
vit.agent.Autocomplete.prototype.init = function() {
var addressEntryChangeHandler =
goog.bind(this.handleAddressEntryChange_, this);
this.addressEntrySubscription_ = this.context_.subscribe(
vit.context.ADDRESS_ENTRY, addressEntryChangeHandler);
return this;
};
/**
* Handle a change in the address.
* @param {?string} partialAddress New address. Expected to be a string.
* @param {?string} oldAddress Old address. Expected to be a string.
* @private
*/
vit.agent.Autocomplete.prototype.handleAddressEntryChange_ =
function(partialAddress, oldAddress) {
partialAddress = /** @type {string} */ (partialAddress) || '';
oldAddress = /** @type {string} */ (oldAddress) || '';
if (partialAddress == oldAddress ||
(partialAddress && oldAddress.lastIndexOf(partialAddress, 0) == 0)) {
return;
}
this.makeSuggestion_(partialAddress);
};
/**
* Attempt to match address to available suggestions or get new ones.
* @param {string} partialAddress Partial address for which to make suggestions.
* @private
* TODO(jmwaura): Consider moving some of this logic into the component to avoid
* the PubSub overhead.
*/
vit.agent.Autocomplete.prototype.makeSuggestion_ = function(partialAddress) {
if (!partialAddress ||
partialAddress.length < vit.agent.Autocomplete.MIN_CHARS) {
this.context_.set(vit.context.ADDRESS_SUGGESTION, '');
return;
}
var partialAddressLower = partialAddress.toLowerCase();
var suggestionsLower = this.suggestionsLower_;
var suggestionLength = suggestionsLower.length;
for (var i = 0; i < suggestionLength; i++) {
// not sure compiler will inline goog.string.startsWith
if (suggestionsLower[i].lastIndexOf(partialAddressLower, 0) == 0) {
var match = partialAddress +
this.suggestions_[i].substring(partialAddress.length);
this.context_.set(vit.context.ADDRESS_SUGGESTION, match);
return;
}
}
// Clear the suggestion.
this.context_.set(vit.context.ADDRESS_SUGGESTION, '');
if (partialAddressLower.lastIndexOf(this.failedPrefix_, 0) == 0) {
return;
}
this.api_.autocomplete(partialAddress,
goog.bind(this.handleApiResponse_, this, partialAddress));
};
/**
* Make another attempt to match address to newly available suggestions.
* @private
*/
vit.agent.Autocomplete.prototype.retrySuggestion_ = function() {
var currentPartialAddress = /** @type {string} */
(this.context_.get(vit.context.ADDRESS_ENTRY));
this.makeSuggestion_(currentPartialAddress);
};
/**
* Handle a response from the api in the address.
* @param {string} partialAddress Partial address that triggered the request.
* @param {Array.<?vit.api.Autocomplete.Prediction>} predictions Result object.
* @param {google.maps.places.PlacesServiceStatus} status Response status.
* @private
*/
vit.agent.Autocomplete.prototype.handleApiResponse_ =
function(partialAddress, predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
this.failedPrefix_ = partialAddress;
return; // Fail quietly.
} else {
var predictionList = [];
var predictionListLower = [];
var predictionLength = predictions.length;
for (var i = 0; i < predictionLength; i++) {
if (!(predictions[i] && predictions[i].description)) {
continue;
}
var description = predictions[i].description;
predictionList[i] = description;
predictionListLower[i] = description.toLowerCase();
}
this.suggestions_ = predictionList;
this.suggestionsLower_ = predictionListLower;
this.retrySuggestion_();
}
};
/**
* @override
*/
vit.agent.Autocomplete.prototype.disposeInternal = function() {
if (goog.isDefAndNotNull(this.addressEntrySubscription_)) {
this.context_.unsubscribeById(this.addressEntrySubscription_);
}
this.suggestions_ = null;
this.suggestionsLower_ = null;
this.context_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Minimum number of characters to call the API with.
* @const
*/
vit.agent.Autocomplete.MIN_CHARS = 7;
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Wrapper for the Google Civic Information Api.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.api.CivicInfo');
goog.provide('vit.api.CivicInfo.Status');
goog.require('goog.array');
goog.require('goog.string.path');
goog.require('vit.api.Api');
goog.require('vit.api.Distance');
/**
* Create a wrapper for the Civic Information API.
* @param {vit.context.Context} context The application context.
* @constructor
* @extends {vit.api.Api}
*/
vit.api.CivicInfo = function(context) {
goog.base(this);
/**
* The application context context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The election id to use for this instance.
* @type {string}
* @private
*/
this.electionId_ = '';
/**
* Whether or not to request only official data.
* @type {boolean}
* @private
*/
this.officialOnly_ = false;
var config = this.context_.get(vit.context.CONFIG);
if (goog.isDefAndNotNull(config)) {
this.electionId_ = config[vit.context.ConfigName.ELECTION_ID];
this.officialOnly_ = config[vit.context.ConfigName.OFFICIAL_ONLY];
} else {
throw Error('vit.api.CivicInfo instantiated before election_id ' +
'is configured.');
}
/**
* The api path to use for Civic Info requests.
* @type {string}
* @private
*/
this.apiPath_ = goog.string.path.join(
vit.api.CivicInfo.API_PATH,
this.electionId_,
'lookup');
};
goog.inherits(vit.api.CivicInfo, vit.api.Api);
/**
* Look up polling location information.
* @param {!string} address The address for which to fetch voter info.
* @param {function((!vit.api.CivicInfo.Response|boolean), string)} callback
* The function to call when the request completes.
*/
vit.api.CivicInfo.prototype.lookup = function(address, callback) {
var params = {'officialOnly': this.officialOnly_ ? 'true' : 'false'};
var body = {'address': address};
var responseTransformer = goog.bind(function(callback, response, raw) {
callback(response ? this.transformResponse(response) : response, raw);
}, this, callback);
var distanceAppender = goog.bind(this.appendDistance,
this, responseTransformer);
this.request(this.apiPath_, vit.api.POST, params, body, distanceAppender);
};
/**
* Transform raw object into Election.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Election} Transformed object.
*/
vit.api.CivicInfo.prototype.transformElection = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Election} */ (obj);
}
var out = {};
out.id = obj['id'];
out.name = obj['name'];
out.electionDay = obj['electionDay'];
return /** @type {vit.api.CivicInfo.Election} */ (out);
};
/**
* Transform raw object into District.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.District} Transformed object.
*/
vit.api.CivicInfo.prototype.transformDistrict = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.District} */ (obj);
}
var out = {};
out.name = obj['name'];
out.scope = obj['scope'];
out.id = obj['id'];
return /** @type {vit.api.CivicInfo.District} */ (out);
};
/**
* Transform raw object into Address.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Address} Transformed object.
*/
vit.api.CivicInfo.prototype.transformAddress = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Address} */ (obj);
}
var out = {};
out.locationName = obj['locationName'];
out.line1 = obj['line1'];
out.line2 = obj['line2'];
out.line3 = obj['line3'];
out.city = obj['city'];
out.state = obj['state'];
out.zip = obj['zip'];
return /** @type {vit.api.CivicInfo.Address} */ (out);
};
/**
* Transform raw object into ElectionOfficial.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.ElectionOfficial} Transformed object.
*/
vit.api.CivicInfo.prototype.transformElectionOfficial = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.ElectionOfficial} */ (obj);
}
var out = {};
out.name = obj['name'];
out.title = obj['title'];
out.officePhoneNumber = obj['officePhoneNumber'];
out.faxNumber = obj['faxNumber'];
out.emailAddress = obj['emailAddress'];
return /** @type {vit.api.CivicInfo.ElectionOfficial} */ (out);
};
/**
* Transform raw object into Contest.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Contest} Transformed object.
*/
vit.api.CivicInfo.prototype.transformContest = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Contest} */ (obj);
}
var out = {};
out.type = obj['type'];
out.primaryParty = obj['primaryParty'];
out.electorateSpecifications = obj['electorateSpecifications'];
out.special = obj['special'];
out.office = obj['office'];
out.level = obj['level'];
out.district = this.transformDistrict(obj['district']);
out.numberElected = obj['numberElected'];
out.numberVotingFor = obj['numberVotingFor'];
out.ballotPlacement = obj['ballotPlacement'];
if (goog.isDefAndNotNull(obj['candidates'])) {
var len = obj['candidates'].length;
/** @type {Array.<vit.api.CivicInfo.Candidate>} */
var candidatesArray = [];
for (var i = 0; i < len; i++) {
candidatesArray[i] = this.transformCandidate(obj['candidates'][i]);
}
out.candidates = candidatesArray;
}
if (goog.isDefAndNotNull(obj['sources'])) {
len = obj['sources'].length;
/** @type {Array.<vit.api.CivicInfo.Source>} */
var sourcesArray = [];
for (var i = 0; i < len; i++) {
sourcesArray[i] = this.transformSource(obj['sources'][i]);
}
out.sources = sourcesArray;
}
return /** @type {vit.api.CivicInfo.Contest} */ (out);
};
/**
* Transform raw object into Channel.
* @param {Array.<Object>} channels Raw object to transform.
* @return {vit.api.CivicInfo.Channels} Transformed object.
*/
vit.api.CivicInfo.prototype.transformChannels = function(channels) {
if (!goog.isDefAndNotNull(channels)) {
return /** @type {vit.api.CivicInfo.Channels} */ (channels);
}
var out = {};
var len = channels.length;
for (var i = 0; i < len; i++) {
var channelType = channels[i]['type'].toLowerCase();
var channelId = channels[i]['id'];
if (channelType == 'googleplus') {
out.googleplus = channelId;
} else if (channelType == 'youtube') {
out.youtube = channelId;
} else if (channelType == 'facebook') {
out.facebook = channelId;
} else if (channelType == 'twitter') {
out.twitter = channelId;
}
}
return /** @type {vit.api.CivicInfo.Channels} */ (out);
};
/**
* Transform raw object into PollingLocation.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.PollingLocation} Transformed object.
*/
vit.api.CivicInfo.prototype.transformPollingLocation = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.PollingLocation} */ (obj);
}
var out = {};
out.address = this.transformAddress(obj['address']);
// TODO(jmwaura): This is a hack to get rid of " - " polling hours.
// The number 5 is mostly arbitrary, but anything less than 5 chars is almost
// definitely wrong. Prefer false negatives. Fix this.
out.pollingHours = (obj['pollingHours'] && obj['pollingHours'].length > 5) ?
obj['pollingHours'] : null;
out.name = obj['name'];
out.notes = obj['notes'];
out.voterServices = obj['voterServices'];
out.startDate = obj['startDate'];
out.endDate = obj['endDate'];
out.distance = obj['distance'];
out.duration = obj['duration'];
if (goog.isDefAndNotNull(obj['sources'])) {
var len = obj['sources'].length;
/** @type {Array.<vit.api.CivicInfo.Source>} */
var sourcesArray = [];
for (var i = 0; i < len; i++) {
sourcesArray[i] = this.transformSource(obj['sources'][i]);
}
out.sources = sourcesArray;
}
return /** @type {vit.api.CivicInfo.PollingLocation} */ (out);
};
/**
* Transform raw object into Candidate.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Candidate} Transformed object.
*/
vit.api.CivicInfo.prototype.transformCandidate = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Candidate} */ (obj);
}
var out = {};
out.name = obj['name'];
out.party = obj['party'];
out.candidateUrl = obj['candidateUrl'];
out.phone = obj['phone'];
out.photoUrl = obj['photoUrl'];
out.email = obj['email'];
out.orderOnBallot = obj['orderOnBallot'];
out.channels = this.transformChannels(obj['channels']);
return /** @type {vit.api.CivicInfo.Candidate} */ (out);
};
/**
* Transform raw object into AdministrationRegion.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.AdministrationRegion} Transformed object.
*/
vit.api.CivicInfo.prototype.transformAdministrationRegion = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.AdministrationRegion} */ (obj);
}
var out = {};
out.name = obj['name'];
out.electionAdministrationBody = this.transformElectionAdministrationBody(
obj['electionAdministrationBody']);
out.local_jurisdiction = this.transformAdministrationRegion(
obj['local_jurisdiction']);
if (goog.isDefAndNotNull(obj['sources'])) {
var len = obj['sources'].length;
/** @type {Array.<vit.api.CivicInfo.Source>} */
var sourcesArray = [];
for (var i = 0; i < len; i++) {
sourcesArray[i] = this.transformSource(obj['sources'][i]);
}
out.sources = sourcesArray;
}
return /** @type {vit.api.CivicInfo.AdministrationRegion} */ (out);
};
/**
* Transform raw object into ElectionAdministrationBody.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.ElectionAdministrationBody} Transformed object.
*/
vit.api.CivicInfo.prototype.transformElectionAdministrationBody =
function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.ElectionAdministrationBody} */ (obj);
}
var out = {};
out.name = obj['name'];
out.electionInfoUrl = obj['electionInfoUrl'];
out.electionRegistrationUrl = obj['electionRegistrationUrl'];
out.electionRegistrationConfirmationUrl =
obj['electionRegistrationConfirmationUrl'];
out.absenteeVotingInfoUrl = obj['absenteeVotingInfoUrl'];
out.votingLocationFinderUrl = obj['votingLocationFinderUrl'];
out.ballotInfoUrl = obj['ballotInfoUrl'];
out.electionRulesUrl = obj['electionRulesUrl'];
out.voter_services = obj['voter_services'];
out.hoursOfOperation = obj['hoursOfOperation'];
out.correspondenceAddress = this.transformAddress(
obj['correspondenceAddress']);
out.physicalAddress = this.transformAddress(obj['physicalAddress']);
if (goog.isDefAndNotNull(obj['electionOfficials'])) {
var len = obj['electionOfficials'].length;
/** @type {Array.<vit.api.CivicInfo.ElectionOfficial>} */
var electionOfficialsArray = [];
for (var i = 0; i < len; i++) {
electionOfficialsArray[i] = this.transformElectionOfficial(
obj['electionOfficials'][i]);
}
out.electionOfficials = electionOfficialsArray;
}
if (goog.isDefAndNotNull(obj['sources'])) {
len = obj['sources'].length;
/** @type {Array.<vit.api.CivicInfo.Source>} */
var sourcesArray = [];
for (var i = 0; i < len; i++) {
sourcesArray[i] = this.transformSource(obj['sources'][i]);
}
out.sources = sourcesArray;
}
return /** @type {vit.api.CivicInfo.ElectionAdministrationBody} */ (out);
};
/**
* Transform raw object into Source.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Source} Transformed object.
*/
vit.api.CivicInfo.prototype.transformSource = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Source} */ (obj);
}
var out = {};
out.name = obj['name'];
out.official = obj['official'];
return /** @type {vit.api.CivicInfo.Source} */ (out);
};
/**
* Transform raw object into Response.
* @param {Object} obj Raw object to transform.
* @return {vit.api.CivicInfo.Response} Transformed object.
*/
vit.api.CivicInfo.prototype.transformResponse = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return /** @type {vit.api.CivicInfo.Response} */ (obj);
}
var out = {};
// TODO(jmwaura): No transform method for status. Treating as literal.
out.status = obj['status'];
out.election = this.transformElection(obj['election']);
out.normalizedInput = this.transformAddress(obj['normalizedInput']);
var len;
if (goog.isDefAndNotNull(obj['pollingLocations'])) {
len = obj['pollingLocations'].length;
/** @type {Array.<vit.api.CivicInfo.PollingLocation>} */
var pollingLocationsArray = [];
for (var i = 0; i < len; i++) {
pollingLocationsArray[i] = this.transformPollingLocation(
obj['pollingLocations'][i]);
}
out.pollingLocations = pollingLocationsArray.sort(
vit.api.CivicInfo.comparePollingLocations);
}
if (goog.isDefAndNotNull(obj['earlyVoteSites'])) {
len = obj['earlyVoteSites'].length;
/** @type {Array.<vit.api.CivicInfo.PollingLocation>} */
var earlyVoteSitesArray = [];
for (var i = 0; i < len; i++) {
earlyVoteSitesArray[i] = this.transformPollingLocation(
obj['earlyVoteSites'][i]);
}
out.earlyVoteSites = earlyVoteSitesArray.sort(
vit.api.CivicInfo.comparePollingLocations);
}
if (goog.isDefAndNotNull(obj['contests'])) {
len = obj['contests'].length;
/** @type {Array.<vit.api.CivicInfo.Contest>} */
var contestsArray = [];
for (var i = 0; i < len; i++) {
contestsArray[i] = this.transformContest(obj['contests'][i]);
}
contestsArray = goog.array.filter(contestsArray, function(contest) {
return (contest.candidates && contest.candidates.length) ? true : false;
});
out.contests = contestsArray.sort(function(a, b) {
// Sort by level.
var comparison = (a && a.level &&
vit.api.CivicInfo.LEVEL_ORDER[a.level] ||
Number.MAX_VALUE) - (b && b.level &&
vit.api.CivicInfo.LEVEL_ORDER[b.level] || Number.MAX_VALUE);
if (comparison != 0) {
return comparison;
}
// Then by scope.
comparison = (a && a.district && a.district.scope &&
vit.api.CivicInfo.SCOPE_ORDER[a.district.scope] ||
Number.MAX_VALUE) - (b && b.district && b.district.scope &&
vit.api.CivicInfo.SCOPE_ORDER[b.district.scope] ||
Number.MAX_VALUE);
if (comparison != 0) {
return comparison;
}
// then by ballot placement.
comparison = (a && a.ballotPlacement || Number.MAX_VALUE) -
(b && b.ballotPlacement || Number.MAX_VALUE);
if (comparison != 0) {
return comparison;
}
// TODO(jmwaura): The rest of these are a hack and need to be cleaned up.
// President
if (a && a.office && a.office.toLowerCase().indexOf('president') >= 0) {
return -1;
} else if (b && b.office &&
b.office.toLowerCase().indexOf('president') >= 0) {
return 1;
}
// Governor
if (a && a.office && a.office.toLowerCase().indexOf('governor') >= 0) {
return -1;
} else if (b && b.office &&
b.office.toLowerCase().indexOf('governor') >= 0) {
return 1;
}
// Senator
if (a && a.office && a.office.toLowerCase().indexOf('senat') >= 0) {
return -1;
} else if (b && b.office &&
b.office.toLowerCase().indexOf('senat') >= 0) {
return 1;
}
// Representative
if (a && a.office && a.office.toLowerCase().indexOf('represent') >= 0) {
return -1;
} else if (b && b.office &&
b.office.toLowerCase().indexOf('represent') >= 0) {
return 1;
}
// Representative
if (a && a.office && a.office.toLowerCase().indexOf('chair') >= 0) {
return -1;
} else if (b && b.office &&
b.office.toLowerCase().indexOf('chair') >= 0) {
return 1;
}
return 0;
});
}
if (goog.isDefAndNotNull(obj['state'])) {
len = obj['state'].length;
/** @type {Array.<vit.api.CivicInfo.AdministrationRegion>} */
var stateArray = [];
for (var i = 0; i < len; i++) {
stateArray[i] = this.transformAdministrationRegion(obj['state'][i]);
}
out.state = stateArray;
}
return /** @type {vit.api.CivicInfo.Response} */ (out);
};
/**
* Sort polling locations and early vote sites by distance.
* This method will also append the distance data to the Polling Locations.
* @param {function((!Object|boolean), string)} callback The function to call
* when the sorting completes.
* @param {!Object|boolean} civicInfo The response object
* whose locations to sort.
* @param {string} raw The raw API response to pass through to the callback.
*/
vit.api.CivicInfo.prototype.appendDistance =
function(callback, civicInfo, raw) {
if ((civicInfo['pollingLocations'] && civicInfo['pollingLocations'].length) ||
(civicInfo['earlyVoteSites'] && civicInfo['earlyVoteSites'].length)) {
// Add polling locations and early vote sites to an array.
var locationArray = [];
var addressArray = [];
if (civicInfo['pollingLocations'] && civicInfo['pollingLocations'].length) {
goog.array.extend(locationArray, civicInfo['pollingLocations']);
}
if (civicInfo['earlyVoteSites'] && civicInfo['earlyVoteSites'].length) {
goog.array.extend(locationArray, civicInfo['earlyVoteSites']);
}
for (var i = 0; i < locationArray.length; i++) {
if (locationArray[i].address) {
addressArray.push(vit.api.CivicInfo.addressToString(
locationArray[i].address, true, true));
} else {
// Abort.
callback(civicInfo, raw);
}
}
var origin = vit.api.CivicInfo.addressToString(
civicInfo['normalizedInput']);
var distanceService = vit.api.Distance.getInstance();
distanceService.getDistances(origin, addressArray, function(distances) {
if (!distances || !distances.length) {
// There was an issue getting distances. Abort.
callback(civicInfo, raw);
} else {
for (var i = 0; i < distances.length; i++) {
locationArray[i]['distance'] = distances[i]['distance'];
locationArray[i]['duration'] = distances[i]['duration'];
}
callback(civicInfo, raw);
}
});
} else {
callback(civicInfo, raw);
}
};
/**
* @override
*/
vit.api.CivicInfo.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Formats an address object as a string.
* @param {vit.api.CivicInfo.Address} address Address to format.
* @param {boolean=} opt_ignoreLocationName Whether to ignore the location name.
* @param {boolean=} opt_ignoreZip Whether to ignore the zip code.
* @return {string} The string representation of the address.
*/
vit.api.CivicInfo.addressToString = function(address, opt_ignoreLocationName,
opt_ignoreZip) {
var addressStr = '';
if (!address) {
return addressStr;
}
if (!opt_ignoreLocationName) {
addressStr += address.locationName ? address.locationName + ', ' : '';
}
addressStr += address.line1 ? address.line1 + ', ' : '';
addressStr += address.line2 ? address.line2 + ', ' : '';
addressStr += address.line3 ? address.line3 + ', ' : '';
addressStr += address.city ? address.city + ', ' : '';
addressStr += address.state ? address.state + ' ' : '';
if (!opt_ignoreZip) {
addressStr += address.zip ? address.zip : '';
}
// Remove trailing characters.
addressStr = goog.string.trim(addressStr);
if (addressStr.charAt(addressStr.length - 1) == ',') {
addressStr = addressStr.substring(0, addressStr.length - 1);
}
return addressStr;
};
/**
* Compares two polling locations for sorting.
* @param {vit.api.CivicInfo.PollingLocation} a First polling location.
* @param {vit.api.CivicInfo.PollingLocation} b Second polling location.
* @return {number} a - b.
*/
vit.api.CivicInfo.comparePollingLocations = function(a, b) {
return (a && a.distance && a.distance.value || Number.MAX_VALUE) -
(b && b.distance && b.distance.value || Number.MAX_VALUE);
};
/**
* The order by which to sort office levels in contests.
* @type {Object.<string, number>}
* @const
*/
vit.api.CivicInfo.LEVEL_ORDER = {
'federal': 1,
'state': 2,
'county': 3,
'city': 4,
'other': 5
};
/**
* The order by which to sort scoped contests.
* @type {Object.<string, number>}
* @const
*/
vit.api.CivicInfo.SCOPE_ORDER = {
'statewide': 1,
'congressional': 2,
'stateUpper': 3,
'stateLower': 4,
'countywide': 5,
'judicial': 6,
'schoolBoard': 7,
'cityWide': 8,
'special': 9
};
/**
* The default API path.
* @type {string}
* @const
* TODO(jmwaura): make api version configurable.
*/
vit.api.CivicInfo.API_PATH = '/civicinfo/us_v1/voterinfo';
/**
* Enum of the potential values for status.
* @enum {string}
*/
vit.api.CivicInfo.Status = {
SUCCESS: 'success',
NO_STREET_SEGMENT_FOUND: 'noStreetSegmentFound',
ADDRESS_UNPARSEABLE: 'addressUnparseable',
NO_ADDRESS_PARAMETER: 'noAddressParameter',
MULTIPLE_STREET_SEGMENTS_FOUND: 'multipleStreetSegmentsFound',
ELECTION_OVER: 'electionOver',
ELECTION_UNKNOWN: 'electionUnknown',
INTERNAL_LOOKUP_FAILURE: 'internalLookupFailure',
REQUEST_FAILURE: 'REQUEST_FAILURE'
};
/**
* Type definition of Civic Info response.
* @typedef {{
* requestTrigger: string,
* status: vit.api.CivicInfo.Status,
* election: vit.api.CivicInfo.Election,
* normalizedInput: vit.api.CivicInfo.Address,
* pollingLocations: Array.<vit.api.CivicInfo.PollingLocation>,
* earlyVoteSites: Array.<vit.api.CivicInfo.PollingLocation>,
* contests: Array.<vit.api.CivicInfo.Contest>,
* state: Array.<vit.api.CivicInfo.AdministrationRegion>
* }}
*/
vit.api.CivicInfo.Response;
/**
* Type definition of Election.
* @typedef {{
* id: number,
* name: string,
* electionDay: string
* }}
*/
vit.api.CivicInfo.Election;
/**
* Type definition of Address.
* @typedef {{
* locationName: string,
* line1: string,
* line2: string,
* line3: string,
* city: string,
* state: string,
* zip: string
* }}
*/
vit.api.CivicInfo.Address;
/**
* Type definition of PollingLocation.
* @typedef {{
* address: vit.api.CivicInfo.Address,
* notes: string,
* pollingHours: string,
* name: string,
* voterServices: string,
* startDate: string,
* endDate: string,
* sources: Array.<vit.api.CivicInfo.Source>,
* distance: google.maps.Distance,
* duration: google.maps.Duration
* }}
*/
vit.api.CivicInfo.PollingLocation;
/**
* Type definition of Contest.
* @typedef {{
* type: string,
* primaryParty: string,
* electorateSpecifications: string,
* special: string,
* office: string,
* level: string,
* district: vit.api.CivicInfo.District,
* numberElected: number,
* numberVotingFor: number,
* ballotPlacement: number,
* candidates: Array.<vit.api.CivicInfo.Candidate>,
* sources: Array.<vit.api.CivicInfo.Source>
* }}
*/
vit.api.CivicInfo.Contest;
/**
* Type definition of District.
* @typedef {{
* name: string,
* scope: string,
* id: string
* }}
*/
vit.api.CivicInfo.District;
/**
* Type definition of Candidate.
* @typedef {{
* name: string,
* party: string,
* candidateUrl: string,
* phone: string,
* photoUrl: string,
* email: string,
* orderOnBallot: number,
* channels: vit.api.CivicInfo.Channels
* }}
*/
vit.api.CivicInfo.Candidate;
/**
* Type definition of Channel.
* @typedef {{
* googleplus: string,
* youtube: string,
* facebook: string,
* twitter: string
* }}
*/
vit.api.CivicInfo.Channels;
/**
* Type definition of Source.
* @typedef {{
* name: string,
* official: boolean
* }}
*/
vit.api.CivicInfo.Source;
/**
* Type definition of AdministrationRegion.
* @typedef {{
* name: string,
* electionAdministrationBody: vit.api.CivicInfo.ElectionAdministrationBody,
* local_jurisdiction: vit.api.CivicInfo.AdministrationRegion,
* sources: Array.<vit.api.CivicInfo.Source>
* }}
*/
vit.api.CivicInfo.AdministrationRegion;
/**
* Type definition of ElectionAdministrationBody.
* @typedef {{
* name: string,
* electionInfoUrl: string,
* electionRegistrationUrl: string,
* electionRegistrationConfirmationUrl: string,
* absenteeVotingInfoUrl: string,
* votingLocationFinderUrl: string,
* ballotInfoUrl: string,
* electionRulesUrl: string,
* voter_services: Array.<string>,
* hoursOfOperation: string,
* correspondenceAddress: vit.api.CivicInfo.Address,
* physicalAddress: vit.api.CivicInfo.Address,
* electionOfficials: Array.<vit.api.CivicInfo.ElectionOfficial>,
* sources: Array.<vit.api.CivicInfo.Source>
* }}
*/
vit.api.CivicInfo.ElectionAdministrationBody;
/**
* Type definition of ElectionOfficial.
* @typedef {{
* name: string,
* title: string,
* officePhoneNumber: string,
* faxNumber: string,
* emailAddress: string
* }}
*/
vit.api.CivicInfo.ElectionOfficial;
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Simplified interface for Distance Matrix service.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.api.Distance');
/**
* Create a wrapper DistanceMatrix Service.
* @constructor
*/
vit.api.Distance = function() {
/**
* An instance of the DistanceMatrixService class.
* @type {google.maps.DistanceMatrixService}
* @private
*/
this.service_ = new google.maps.DistanceMatrixService();
};
goog.addSingletonGetter(vit.api.Distance);
/**
* Get distances from an origin to a set of addresses.
* @param {string|google.maps.LatLng} origin Origin from which to get distances.
* @param {Array.<string>|Array.<google.maps.LatLng>} destinations The
* destinations to which to get distances.
* @param {function(Array.<google.maps.DistanceMatrixResponseElement>)}
* callback The function to call with the distances.
*/
vit.api.Distance.prototype.getDistances = function(origin, destinations,
callback) {
var responseArray = [];
var requestArray = [];
// Slice the destinations into MAX_DESTINATIONS size arrays.
for (var i = 0; i < destinations.length;
i += vit.api.Distance.MAX_DESTINATIONS) {
var start = i;
var end = Math.min(destinations.length,
i + vit.api.Distance.MAX_DESTINATIONS);
requestArray.push(destinations.slice(start, end));
}
var numRequests = requestArray.length;
var responseCount = 0;
for (var i = 0; i < numRequests; i++) {
var request = {
'origins': [origin],
'destinations': requestArray[i],
'travelMode': google.maps.TravelMode.DRIVING,
'unitSystem': google.maps.UnitSystem.IMPERIAL,
'avoidHighways': false,
'avoidTolls': false
};
this.service_.getDistanceMatrix(request, goog.bind(
function(i, response) {
responseCount++;
responseArray[i] = response;
if (responseCount >= numRequests) {
callback(this.processResponses_(responseArray));
}
}, this, i));
}
};
/**
* Extracts the distance data from a list of responses.
* @param {Array.<Object>} responseArray List of responses from the service.
* @return {Array.<google.maps.DistanceMatrixResponseElement>} List of response
* elements from all responses.
* @private
*/
vit.api.Distance.prototype.processResponses_ = function(responseArray) {
var responseElements = [];
for (var i = 0; i < responseArray.length; i++) {
var response = responseArray[i];
if (!response || !response['rows'] || !response['rows'].length) {
return null;
}
var elements = response['rows'][0]['elements'];
if (goog.isArray(elements)) {
goog.array.extend(responseElements, elements);
} else {
return null;
}
}
return responseElements;
};
/**
* The maximum number of destinations to pass to the DistanceMatrix service.
* @const
*/
vit.api.Distance.MAX_DESTINATIONS = 25;
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Utility for simple generation of static maps urls.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.api.StaticMap');
goog.require('goog.Uri');
goog.require('vit.api');
/**
* Static map api URL.
* @type {string}
* @const
*/
vit.api.StaticMap.URL = 'https://maps.googleapis.com/maps/api/staticmap';
/**
* Generate a static maps URL.
* @param {string} center Map center.
* @param {boolean=} opt_addMarker Whether or not to add a marker at the center.
* @param {string=} opt_size Size of the map image, e.g. '240x240'.
* @return {string} The map URL.
*/
vit.api.StaticMap.generateMapUrl = function(center, opt_addMarker, opt_size) {
var options = {
'center': center,
'size': opt_size || '384x216',
'sensor': 'false',
'key': vit.api.API_KEY
};
if (opt_addMarker) {
options['markers'] = 'color:green|' + center;
options['zoom'] = '14';
}
return new goog.Uri(vit.api.StaticMap.URL).setQueryData(
goog.Uri.QueryData.createFromMap(options)).toString();
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Wrapper for the Google Civic Information Api.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.api.Autocomplete');
goog.require('goog.string.path');
goog.require('vit.api.Api');
/**
* Create a wrapper for the Places AutoCompletion API.
* @param {vit.context.Context} context The application context.
* @constructor
* @extends {vit.api.Api}
*/
vit.api.Autocomplete = function(context) {
goog.base(this);
/**
* The application context context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The application context context.
* @type {boolean}
* @private
*/
this.canMakeRequest_ = true;
/**
* The application context context.
* @type {google.maps.places.AutocompleteService}
* @private
*/
this.autocompleteService_ = new google.maps.places.AutocompleteService();
};
goog.inherits(vit.api.Autocomplete, vit.api.Api);
/**
* Look up address suggestions. This method throttles requests and
* should therefore not be expected to always call the callback function.
* @param {!string} address The address for which to fetch voter info.
* @param {function(Array.<?vit.api.Autocomplete.Prediction>,
* google.maps.places.PlacesServiceStatus)} callback
* The function to call when the request completes.
*/
vit.api.Autocomplete.prototype.autocomplete = function(address, callback) {
if (! this.canMakeRequest_) {
// Simply drop request if last one was too recent.
return;
}
this.canMakeRequest_ = false;
setTimeout(goog.bind(function() {
this.canMakeRequest_ = true;
}, this), vit.api.Autocomplete.REQUEST_INTERVAL);
// TODO(jmwaura): The api doesn't seem to do a great job of biasing these
// based on client location. Add bounds param.
var params = {
'input': address,
'types': ['geocode'],
'componentRestrictions': {'country': 'us'}
};
var responseTransformer = goog.bind(function(callback, predictions, status) {
callback(this.transformResponse_(predictions), status);
}, this, callback);
this.autocompleteService_.getPlacePredictions(params, responseTransformer);
};
/**
* Transform raw object into Response.
* @param {Array.<Object>} predictions Raw object to transform.
* @return {Array.<vit.api.Autocomplete.Prediction>} Transformed object.
* @private
*/
vit.api.Autocomplete.prototype.transformResponse_ = function(predictions) {
if (!goog.isDefAndNotNull(predictions)) {
return null;
}
var len = predictions.length;
/** @type {Array.<?vit.api.Autocomplete.Prediction>} */
var predictionsArray = [];
for (var i = 0; i < len; i++) {
predictionsArray[i] = this.transformPrediction_(
predictions[i]);
}
return predictionsArray;
};
/**
* Transform raw object into Prediction.
* @param {Object} obj Raw object to transform.
* @return {?vit.api.Autocomplete.Prediction} Transformed object.
* @private
*/
vit.api.Autocomplete.prototype.transformPrediction_ = function(obj) {
if (!goog.isDefAndNotNull(obj)) {
return null;
}
var out = {description: obj['description']};
return /** @type {vit.api.Autocomplete.Prediction} */ (out);
};
/**
* Type definition for Autocomplete Prediction.
* @typedef {{
* description: string
* }}
*/
vit.api.Autocomplete.Prediction;
/**
* The minimum interval in ms between queries to the autocomplete API.
* @type {number}
*/
vit.api.Autocomplete.REQUEST_INTERVAL = 100;
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Simplified interface for Google API Javascript Client.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.api');
goog.provide('vit.api.Api');
goog.require('goog.Disposable');
goog.require('goog.math.ExponentialBackoff');
/**
* Construct wrapper for Google API client.
* @constructor
* @extends {goog.Disposable}
*/
vit.api.Api = function() {
goog.base(this);
if (vit.api.API_KEY) {
gapi.client.setApiKey(vit.api.API_KEY);
} else {
throw Error('No Google API Key configured.');
}
};
goog.inherits(vit.api.Api, goog.Disposable);
/**
* Build request arguments and initiate a request. If the request fails, it
* will be retried vit.api.NUM_RETRIES times.
* @param {string} path API path.
* @param {string} method HTTP request method.
* @param {Object.<string, string>} params API request parameters.
* @param {Object.<string, string>} body API request body.
* @param {function((!Object|boolean), string)} callback Callback function. Must
* already be bound to the appropriate scope, otherwise it will be executed
* in the global scope.
*/
vit.api.Api.prototype.request = function(path, method, params, body,
callback) {
var args = {
'path': path,
'method': method,
'params': params
};
if (method == vit.api.POST || method == vit.api.PUT) {
args['body'] = body;
}
this.request_(args, callback);
};
/**
* Build and execute a request.
* @param {!Object} args Request arguments.
* @param {function((!Object|boolean), string)} callback Callback function.
* @param {goog.math.ExponentialBackoff=} opt_backoff Backoff counter.
* @private
*/
vit.api.Api.prototype.request_ = function(args, callback, opt_backoff) {
/** @type {!gapi.client.HttpRequest|undefined} */
var req = gapi.client.request(args);
if (req) {
req.execute(
goog.bind(this.handleResponses_, this, args, callback, opt_backoff));
} else {
throw Error('gapi did not return a proper request object.');
}
};
/**
* Handle responses. Retry and back off when errors are encountered.
* @param {!Object} args Request arguments.
* @param {function((!Object|boolean), string)} callback The callback for this
* request. Must already be bound to its scope.
* @param {goog.math.ExponentialBackoff} backoff Backoff counter.
* @param {!Object|boolean} jsonResp The parsed JSON response from the api.
* @param {string} rawResp Raw HTTP response in a JSON encoded string.
* @see https://code.google.com/p/google-api-javascript-client/wiki/ReferenceDocs#gapi.client._RpcRequest
* @private
*/
vit.api.Api.prototype.handleResponses_ = function(args, callback,
backoff, jsonResp, rawResp) {
if (!jsonResp) {
// TODO(jmwaura): Parse raw response and only retry on transient errors.
if (!goog.isDefAndNotNull(backoff)) {
backoff = new goog.math.ExponentialBackoff(vit.api.MIN_RETRY_DELAY,
vit.api.MAX_RETRY_DELAY);
} else {
backoff.backoff();
}
if (backoff.getBackoffCount() > vit.api.NUM_RETRIES) {
callback(jsonResp, rawResp);
} else {
setTimeout(goog.bind(this.request_, this, args, callback, backoff),
backoff.getValue());
}
} else {
callback(jsonResp, rawResp);
}
};
/**
* POST request type.
* @type {string}
* @const
*/
vit.api.POST = 'POST';
/**
* GET request type.
* @type {string}
* @const
*/
vit.api.GET = 'GET';
/**
* PUT request type.
* @type {string}
* @const
*/
vit.api.PUT = 'PUT';
/**
* Number of times to retry a failed request.
* @type {number}
* @const
*/
vit.api.NUM_RETRIES = 5;
/**
* Minimum delay in ms between retry attempts.
* @type {number}
* @const
*/
vit.api.MIN_RETRY_DELAY = 100;
/**
* Maximum delay in ms between retry attempts.
* @type {number}
* @const
*/
vit.api.MAX_RETRY_DELAY = 3200;
/**
* An API Key is required to access Google Maps and Civic Information APIs.
* @define {string} Google API Key.
*/
vit.api.API_KEY = '';
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Zippy component that uses css transitions for animation.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.CssZippy');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.ui.Zippy');
goog.require('goog.ui.ZippyEvent');
/**
* Zippy component that relies on CSS transitions for animation.
*
* @param {Element|string} zippy The zippy element or id.
*
* @extends {goog.ui.Zippy}
* @constructor
*/
vit.component.CssZippy = function(zippy) {
// Wrap the content element.
var contentWrapperEl = goog.dom.createDom('div',
{'style': 'overflow:hidden; display:none;'});
var zippyEl = goog.dom.getElement(zippy);
var isExpanded = goog.dom.classes.has(zippyEl, goog.getCssName('expanded'));
var contentEl = goog.dom.getElementByClass(
goog.getCssName('zippy-content'), zippyEl);
zippyEl.replaceChild(contentWrapperEl, contentEl);
contentWrapperEl.appendChild(contentEl);
var headerEl = goog.dom.getElementByClass(
goog.getCssName('zippy-header'), zippyEl);
goog.base(this, headerEl, contentEl, isExpanded);
/**
* The zippy element.
* @type {Element}
* @private
*/
this.zippyEl_ = zippyEl;
/**
* The header.
* @type {Element}
* @private
*/
this.headerEl_ = headerEl;
/**
* The content wrapper.
* @type {Element}
* @private
*/
this.contentWrapperEl_ = contentWrapperEl;
/**
* The timeout to fire at the end of transition animations.
* @type {?number}
* @private
*/
this.transitionEndTimeout_ = null;
this.init_(isExpanded);
};
goog.inherits(vit.component.CssZippy, goog.ui.Zippy);
/**
* Animation duration in ms.
* @const {number}
*/
vit.component.CssZippy.ANIMATION_DURATION = 200;
/**
* Animation delay in ms.
* @const {number}
*/
vit.component.CssZippy.ANIMATION_DELAY = 50;
/**
* Initialize the zippy.
* @param {boolean} expanded Whether to start out expanded.
* @private
*/
vit.component.CssZippy.prototype.init_ = function(expanded) {
// Display the element if necessary.
if (expanded) {
this.contentWrapperEl_.style.display = '';
}
// Wait for the element to render, then measure the content height and
// explicitly set the size. This will allow the first animation to
// happen smoothly. Also set the transition properties.
setTimeout(goog.bind(function() {
var height = this.getContentElement().offsetHeight;
var contentWrapperEl = this.contentWrapperEl_;
contentWrapperEl.style.height = height + 'px';
// TODO(jmwaura): Move these to a css class.
var transition = 'height ' + vit.component.CssZippy.ANIMATION_DURATION +
'ms';
contentWrapperEl.style.transition = transition;
contentWrapperEl.style.WebkitTransition = transition;
contentWrapperEl.style.MozTransition = transition;
contentWrapperEl.style.OTransition = transition;
}, this), vit.component.CssZippy.ANIMATION_DELAY);
};
/** @override */
vit.component.CssZippy.prototype.setExpanded = function(expanded) {
// This effectively disables the initial run by the superclass constructor.
if (this.isExpanded() == expanded) {
return;
}
// Clear active timeout if any.
clearTimeout(this.transitionEndTimeout_);
var contentWrapperEl = this.contentWrapperEl_;
// Display the element.
if (expanded) {
contentWrapperEl.style.display = '';
}
setTimeout(goog.bind(function() {
if (expanded) {
var contentHeight = this.getContentElement().offsetHeight;
// In case the height can't be determined, just clear the 0px height.
contentWrapperEl.style.height = contentHeight ? contentHeight + 'px' : '';
} else {
contentWrapperEl.style.height = '0px';
// Wait for transition to end before setting the display property to none.
this.transitionEndTimeout_ = setTimeout(goog.bind(function() {
this.contentWrapperEl_.style.display = 'none';
}, this), vit.component.CssZippy.ANIMATION_DURATION);
}
}, this), vit.component.CssZippy.ANIMATION_DELAY);
goog.dom.classes.enable(this.zippyEl_, goog.getCssName('expanded'),
expanded);
this.setExpandedInternal(expanded);
this.dispatchEvent(new goog.ui.ZippyEvent(goog.ui.Zippy.Events.TOGGLE,
this, expanded));
};
/** @override */
vit.component.CssZippy.prototype.disposeInternal = function() {
delete this.contentWrapperEl_;
delete this.zippyEl_;
delete this.headerEl_;
clearTimeout(this.transitionEndTimeout_);
this.transitionEndTimeout_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Returns the DOM element associated with this zippy.
* @return {Element} The DOM element associated with this zippy.
*/
vit.component.CssZippy.prototype.getElement = function() {
return this.zippyEl_;
};
/**
* Sets the enabled state of the zippy. A disabled zippy will not handle user
* input but will otherwise behave as expected.
* @param {boolean} enabled Whether or not the zippy should be enabled.
*/
vit.component.CssZippy.prototype.setEnabled = function(enabled) {
this.setHandleMouseEvents(enabled);
this.setHandleKeyboardEvents(enabled);
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Top level component that acts as parent to all other VIT
* components.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Page');
goog.require('vit.component.Alert');
goog.require('vit.component.Component');
goog.require('vit.component.Contest');
goog.require('vit.component.Leo');
goog.require('vit.component.Polling');
/**
* Component that acts as a parent to all page components.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Page = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
};
goog.inherits(vit.component.Page, vit.component.Component);
/** @override */
vit.component.Page.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
var pollingPane = new vit.component.Polling(this.context_);
this.addChild(pollingPane);
pollingPane.decorate(
goog.dom.getElementByClass(goog.getCssName('polling-pane')));
var contestPane = new vit.component.Contest(this.context_);
this.addChild(contestPane);
contestPane.decorate(
goog.dom.getElementByClass(goog.getCssName('contest-pane')));
var alert = new vit.component.Alert(this.context_);
this.addChild(alert);
alert.decorate(
goog.dom.getElementByClass(goog.getCssName('alert-container')));
var leo = new vit.component.Leo(this.context_);
this.addChild(leo);
leo.decorate(
goog.dom.getElementByClass(goog.getCssName('leo-info-container')));
};
/** @override */
vit.component.Page.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that manages the contest pane.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Contest');
goog.require('goog.soy');
goog.require('vit.component.Component');
goog.require('vit.component.ContestInfo');
/**
* Create component that manages the contest pane.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Contest = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* Component that handles rendering of contest info.
* @type {vit.component.ContestInfo}
* @private
*/
this.contestInfo_;
};
goog.inherits(vit.component.Contest, vit.component.Component);
/** @override */
vit.component.Contest.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
this.renderContestInfo_();
var callback = goog.bind(this.handleCivicInfoChange_, this);
this.context_.subscribe(vit.context.CIVIC_INFO, callback);
};
/**
* Handle a civic info change.
* @param {vit.api.CivicInfo.Response} civicInfo New civic info response.
* @param {vit.api.CivicInfo.Response} oldCivicInfo Old civic info response.
* @private
*/
vit.component.Contest.prototype.handleCivicInfoChange_ =
function(civicInfo, oldCivicInfo) {
if (civicInfo == oldCivicInfo) {
return;
}
this.renderContestInfo_();
};
/**
* Render the contest info pane.
* @private
*/
vit.component.Contest.prototype.renderContestInfo_ = function() {
if (this.contestInfo_) {
this.removeChildren(true);
this.contestInfo_.dispose();
}
this.contestInfo_ = new vit.component.ContestInfo(this.context_);
this.registerDisposable(this.contestInfo_);
this.addChild(this.contestInfo_, true);
};
/** @override */
vit.component.Contest.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that renders contest info and handles interaction.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.ContestInfo');
goog.require('goog.soy');
goog.require('goog.ui.AdvancedTooltip');
goog.require('goog.ui.Component.EventType');
goog.require('vit.api.CivicInfo');
goog.require('vit.component.Component');
goog.require('vit.component.ScrollingTabBar');
goog.require('vit.context.Context');
goog.require('vit.templates.candidates');
goog.require('vit.templates.contestInfo');
goog.require('vit.util');
/**
* Create contest info component.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.ContestInfo = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The set of contests displayed by this component.
* @type {Array.<vit.api.CivicInfo.Contest>}
* @private
*/
this.contests_;
/**
* The region for the current result set.
* @type {?string}
* @private
*/
this.region_;
/**
* Content element
* @type {Element}
* @private
*/
this.tabContentElement_;
/**
* Tab Bar component.
* @type {vit.component.ScrollingTabBar}
* @private
*/
this.tabBar_;
/**
* Hover Card.
* @type {goog.ui.AdvancedTooltip}
* @private
*/
this.hoverCard_;
};
goog.inherits(vit.component.ContestInfo, vit.component.Component);
/** @override */
vit.component.ContestInfo.prototype.createDom = function() {
var civicInfo = /** @type vit.api.CivicInfo.Response */
(this.context_.get(vit.context.CIVIC_INFO));
this.region_ = civicInfo && civicInfo.normalizedInput &&
civicInfo.normalizedInput.state || null;
this.contests_ = /** @type {Array.<vit.api.CivicInfo.Contest>} */
(civicInfo && civicInfo.contests || null);
var data = this.formatData_(civicInfo);
var element = goog.soy.renderAsElement(vit.templates.contestInfo, data);
this.setElementInternal(element);
var tabs = this.getElementByClass(
goog.getCssName('scrolling-tab-bar-container'));
this.tabContentElement_ = this.getElementByClass(
goog.getCssName('contest-tab-content'));
if (tabs) {
var tabBar = new vit.component.ScrollingTabBar();
this.addChild(tabBar);
tabBar.decorate(tabs);
this.tabBar_ = tabBar;
var hoverCard = new goog.ui.AdvancedTooltip();
hoverCard.setCursorTracking(true);
this.registerDisposable(hoverCard);
this.hoverCard_ = hoverCard;
}
};
/**
* Formats API data for use in the template.
* @param {vit.api.CivicInfo.Response} civicInfo The civic info data.
* @return {Object.<string, *>} Object containing info to render.
* @private
*/
vit.component.ContestInfo.prototype.formatData_ = function(civicInfo) {
return {
addressWasEntered: civicInfo &&
civicInfo.requestTrigger == vit.context.ADDRESS,
contests: this.formatContests_(this.contests_)
};
};
/**
* Formats contest data for use in the template.
* @param {Array.<vit.api.CivicInfo.Contest>} contests Contests to format.
* @return {Array.<vit.api.CivicInfo.Contest>} Formatted Contests.
* @private
*/
vit.component.ContestInfo.prototype.formatContests_ = function(contests) {
/** @type {Array.<Object.<string, *>>} */
var formattedContests = contests ? [] : null;
var titleCaseExceptions = ['US'];
if (this.region_) {
titleCaseExceptions.push(this.region_);
}
if (contests) {
for (var i = 0; i < contests.length; i++) {
var formattedContest = {};
var contest = contests[i];
goog.object.extend(formattedContest, contest, {
office: vit.util.selectiveTitleCase(contest.office, titleCaseExceptions)
});
formattedContests[i] = formattedContest;
}
}
return formattedContests;
};
/**
* Handles tab selection events.
* @param {goog.events.Event} e The event object.
* @private
*/
vit.component.ContestInfo.prototype.handleTabSelection_ = function(e) {
var selectedTab = e.target;
goog.dom.removeChildren(this.tabContentElement_);
// TODO(jmwaura): Surely there's a better way to do this.
var tabIndex = this.tabBar_.getSelectedTabIndex();
var data = {candidates: this.contests_[tabIndex].candidates,
region: (this.contests_[tabIndex].level == 'federal') ?
null : this.region_
};
goog.dom.appendChild(this.tabContentElement_,
goog.soy.renderAsElement(vit.templates.candidates, data));
var hoverCardTargets = goog.dom.getElementsByClass(
goog.getCssName('candidate-contact'));
goog.array.forEach(hoverCardTargets, function(el) {
this.hoverCard_.attach(el);
}, this);
};
/**
* Called before a hover card is shown.
* @param {goog.events.Event} e The event object.
* @private
*/
vit.component.ContestInfo.prototype.onBeforeShowCard_ = function(e) {
var card = /** @type {goog.ui.AdvancedTooltip} */ (e.target);
var anchor = card.anchor;
var data = {
name: anchor.getAttribute('data-name'),
url: anchor.getAttribute('data-url'),
phone: anchor.getAttribute('data-phone'),
email: anchor.getAttribute('data-email'),
image: anchor.getAttribute('data-image')
};
card.setHtml(vit.templates.candidateCard(data));
};
/** @override */
vit.component.ContestInfo.prototype.disposeInternal = function() {
this.context_ = null;
this.contests_ = null;
this.region_ = null;
this.tabContentElement_ = null;
this.tabSelectListenerKey_ = null;
this.tabBar_ = null;
goog.base(this, 'disposeInternal');
};
/** @override */
vit.component.ContestInfo.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
if (this.tabBar_) {
this.getHandler().listen(
this.tabBar_,
goog.ui.Component.EventType.SELECT,
this.handleTabSelection_
);
this.tabBar_.setSelectedTabIndex(0);
}
if (this.hoverCard_) {
this.getHandler().listen(
this.hoverCard_,
goog.ui.PopupBase.EventType.BEFORE_SHOW,
this.onBeforeShowCard_);
}
};
/** @override */
vit.component.ContestInfo.prototype.exitDocument = function() {
goog.base(this, 'exitDocument');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Accordion component that uses csszippies.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Accordion');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events');
goog.require('goog.ui.Zippy');
goog.require('goog.ui.ZippyEvent');
goog.require('vit.component.Component');
goog.require('vit.component.CssZippy');
/**
* Accordion component that uses CssZippies.
*
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Accordion = function(opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The header.
* @type {Array.<vit.component.CssZippy>}
* @private
*/
this.zippies_;
/**
* The currently selected element.
* @type {Element}
* @private
*/
this.selected_;
};
goog.inherits(vit.component.Accordion, vit.component.Component);
/** @override */
vit.component.Accordion.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
/** @type {Array.<vit.component.CssZippy>} */
var zippies = [];
var zippyEls = goog.dom.getElementsByClass(goog.getCssName('zippy'), element);
goog.array.forEach(zippyEls, function(zippyEl) {
var zippy = new vit.component.CssZippy(zippyEl);
zippies.push(zippy);
}, this);
this.zippies_ = zippies;
};
/**
* Handle zippy toggle events.
* @param {goog.ui.ZippyEvent} ev Zippy toggle event.
* @private
*/
vit.component.Accordion.prototype.onZippyToggle_ = function(ev) {
if (!ev.expanded) {
if (this.selected_ == ev.target.getElement()) {
this.selected_ = null;
} else {
return;
}
} else {
var expandedZippy = ev.target;
goog.array.forEach(this.zippies_, function(zippy) {
if (expandedZippy != zippy) {
zippy.collapse();
}
});
this.selected_ = ev.target.getElement();
}
this.dispatchEvent(new goog.events.Event(goog.ui.Component.EventType.SELECT,
this));
};
/**
* Gets selected zippy element.
* @return {Element} The selected zippy element.
*/
vit.component.Accordion.prototype.getSelected = function() {
return this.selected_;
};
/** @override */
vit.component.Accordion.prototype.enterDocument = function() {
var handler = this.getHandler();
goog.array.forEach(this.zippies_, function(zippy) {
handler.listen(zippy, goog.ui.Zippy.Events.TOGGLE, this.onZippyToggle_);
}, this);
};
/** @override */
vit.component.Accordion.prototype.exitDocument = function() {
this.getHandler().removeAll();
};
/** @override */
vit.component.Accordion.prototype.disposeInternal = function() {
goog.array.forEach(this.zippies_, function(zippy) {
zippy.dispose();
}, this);
delete this.zippies_;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that handles rendering of polling locations on a map.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.LocationMap');
goog.require('goog.dom');
goog.require('goog.events.EventTarget');
goog.require('vit.component.Component');
goog.require('vit.context');
goog.require('vit.templates.largeMap');
/**
* Component that handles rendering of the region selector.
*
* @param {vit.api.CivicInfo.Address=} opt_origin Origin address.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.LocationMap = function(opt_origin, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The list of polling locations to place on the map.
* @type {Array.<vit.api.CivicInfo.PollingLocation>}
* @private
*/
this.locationList_;
/**
* The type of polling locations on the map.
* @type {string}
* @private
*/
this.locationType_;
/**
* The origin address.
* @type {?vit.api.CivicInfo.Address}
* @private
*/
this.origin_ = opt_origin || null;
/**
* The map.
* @type {google.maps.Map}
* @private
*/
this.map_;
/**
* The bounds that contain active markers.
* @type {google.maps.LatLngBounds}
* @private
*/
this.bounds_;
/**
* A Geocoder instance.
* @type {google.maps.Geocoder}
* @private
*/
this.geocoder_;
/**
* List of map markers.
* @type {Array.<google.maps.Marker>}
* @private
*/
this.markers_ = [];
/**
* Origin Marker.
* @type {google.maps.Marker}
* @private
*/
this.originMarker_;
/**
* Timeout between adding markers and fitting the map to the bounds.
* @private
* @type {?number}
*/
this.fitTimeout_;
};
goog.inherits(vit.component.LocationMap, vit.component.Component);
/**
* Enumeration of event types.
* @enum {string}
*/
vit.component.LocationMap.Events = {
SELECT: 'select',
GEOCODE: 'geocode'
};
/**
* The timeout in ms between adding a marker and fitting the map.
* @type {number}
*/
vit.component.LocationMap.FIT_TIMEOUT = 100;
/**
* Maximum number of points to geocode at a time.
*/
vit.component.LocationMap.MAX_GEOCODE = 5;
/** @override */
vit.component.LocationMap.prototype.createDom = function() {
var element = goog.soy.renderAsElement(vit.templates.largeMap);
this.setElementInternal(element);
};
/**
* Selects a polling location marker.
* @param {number} index The index of the polling location to select.
*/
vit.component.LocationMap.prototype.selectLocation = function(index) {
var bounds = this.bounds_;
this.geocodeLocation(this.locationList_[index], goog.bind(
function(index, location) {
this.dispatchEvent(new vit.component.LocationMap.LocationEvent(
vit.component.LocationMap.Events.GEOCODE, this, this.locationType_,
index));
this.addLocation_(index, location, bounds, true);
this.onMarkerClick_(this.markers_[index], index);
}, this, index));
};
/**
* Sets the origin and list of locations.
*
* @param {string} locationType Type of locations.
* @param {Array.<vit.api.CivicInfo.PollingLocation>} locationList List of
* polling locations to place on map.
*/
vit.component.LocationMap.prototype.setLocations =
function(locationType, locationList) {
this.removeMarkers();
this.locationType_ = locationType;
this.locationList_ = locationList;
var bounds = new google.maps.LatLngBounds();
this.bounds_ = bounds;
if (this.origin_) {
var origin = /** @type {vit.api.CivicInfo.Address} */ (this.origin_);
this.geocodeAddress(origin, goog.bind(this.addOrigin_, this, bounds));
}
var end = Math.min(vit.component.LocationMap.MAX_GEOCODE,
locationList.length);
for (var i = 0; i < end; i++) {
this.geocodeLocation(locationList[i], goog.bind(
function(index, location) {
this.dispatchEvent(new vit.component.LocationMap.LocationEvent(
vit.component.LocationMap.Events.GEOCODE, this, this.locationType_,
index));
this.addLocation_(index, location, bounds);
}, this, i));
}
for (var i = end; i < locationList.length; i++) {
this.addLocation_(i, locationList[i], bounds);
}
};
/**
* Geocodes a location.
* @param {vit.api.CivicInfo.PollingLocation} location Location to geocode.
* @param {function(vit.api.CivicInfo.PollingLocation)} callback Function to
* call when geocoding completes.
*/
vit.component.LocationMap.prototype.geocodeLocation = function(location,
callback) {
if (!location) {
callback(location);
return;
}
this.geocodeAddress(location.address, goog.bind(function(address) {
location.address = address;
callback(location);
}, this));
};
/**
* Geocodes an address.
* @param {vit.api.CivicInfo.Address} address Location to geocode.
* @param {function(vit.api.CivicInfo.Address)} callback Function to
* call when geocoding completes successfully. It won't be called otherwise.
*/
vit.component.LocationMap.prototype.geocodeAddress = function(address,
callback) {
if (!address) {
callback(address);
return;
}
if (address && address.location) {
callback(address);
return;
}
var request = {
address: vit.api.CivicInfo.addressToString(address, true)
};
this.getGeocoder_().geocode(request, goog.bind(function(resp, status) {
if (status != google.maps.GeocoderStatus.OK) {
return;
}
var bestResp = null;
for (var i = 0; i < resp.length; i++)
{
if (this.geocodeIsSane(resp[i])) {
bestResp = resp[i];
break;
}
}
if (!bestResp) {
// No sane geocodes.
return;
}
address.location = bestResp.geometry.location;
callback(address);
}, this));
};
/**
* Checks that a geocode result is sane.
* @param {google.maps.GeocoderResult} geocode The result to check.
* @return {boolean} Whether or not the geocode is sane.
*/
vit.component.LocationMap.prototype.geocodeIsSane = function(geocode) {
if (!(geocode && geocode.geometry && geocode.address_components)) {
return false;
}
var type = geocode.geometry.location_type;
if (type != google.maps.GeocoderLocationType.ROOFTOP &&
type != google.maps.GeocoderLocationType.RANGE_INTERPOLATED) {
return false;
}
// Find the state component.
var geocodeState;
for (var i = 0; i < geocode.address_components.length; i++) {
for (var j = 0; j < geocode.address_components[i].types.length; j++) {
// TODO(jmwaura): Define address component types in constants somewhere.
if (geocode.address_components[i].types[j] ==
"administrative_area_level_1") {
geocodeState = geocode.address_components[i].short_name;
break;
}
}
if (geocodeState) {
break;
}
}
if (!geocodeState) {
return false;
}
if (this.origin_ && this.origin_.state) {
if (this.origin_.state.toLowerCase() != geocodeState.toLowerCase()) {
return false;
}
}
return true;
}
/**
* Add an origin marker to the map. Will recycle markers if possible.
*
* @param {google.maps.LatLngBounds} bounds Polling location bounds.
* @private
*/
vit.component.LocationMap.prototype.addOrigin_ = function(bounds) {
if (!(this.origin_ && this.origin_.location)) {
return;
}
var latLng = this.origin_.location;
var marker = this.originMarker_;
if (!marker) {
marker = new google.maps.Marker();
this.originMarker_ = marker;
}
/**
* @type {google.maps.MarkerOptions}
*/
marker.setOptions({
map: this.map_,
position: latLng,
title: this.origin_.line1 || ''
});
google.maps.event.addListener(marker, 'click', goog.bind(
this.onOriginMarkerClick_, this, marker));
bounds.extend(latLng);
clearTimeout(this.fitTimeout_);
this.fitTimeout_ = setTimeout(goog.bind(function(bounds) {
this.map_.fitBounds(bounds);
}, this, bounds), vit.component.LocationMap.FIT_TIMEOUT);
};
/**
* Handle origin marker click events.
* @param {google.maps.Marker} marker The marker that was clicked.
* @private
*/
vit.component.LocationMap.prototype.onOriginMarkerClick_ = function(marker) {
var infoWindow = this.getInfoWindow_();
infoWindow.close();
infoWindow.setContent(this.renderOriginInfo_());
infoWindow.open(this.map_, marker);
};
/**
* Add a polling location marker to the map. Will recycle markers if possible.
*
* @param {number} index Polling location index.
* @param {vit.api.CivicInfo.PollingLocation} location Polling location object.
* @param {google.maps.LatLngBounds} bounds Polling location bounds.
* @param {boolean=} opt_noFit Do not fit map to new bounds.
* @private
*/
vit.component.LocationMap.prototype.addLocation_ =
function(index, location, bounds, opt_noFit) {
if (!(location && location.address && location.address.location)) {
return;
}
var latLng = location.address.location;
var marker = this.markers_[index];
if (!marker) {
marker = new google.maps.Marker();
this.markers_[index] = marker;
}
/**
* @type {google.maps.MarkerOptions}
*/
marker.setOptions({
map: this.map_,
position: latLng,
title: location.address && location.address.locationName || location.name
});
google.maps.event.addListener(marker, 'click', goog.bind(this.onMarkerClick_,
this, marker, index));
bounds.extend(latLng);
clearTimeout(this.fitTimeout_);
if (!opt_noFit) {
this.fitTimeout_ = setTimeout(goog.bind(function(bounds) {
this.map_.fitBounds(bounds);
}, this, bounds), vit.component.LocationMap.FIT_TIMEOUT);
}
};
/**
* Handle marker click events.
* @param {google.maps.Marker} marker The marker that was clicked.
* @param {number} index The marker index.
* @private
*/
vit.component.LocationMap.prototype.onMarkerClick_ = function(marker, index) {
var infoWindow = this.getInfoWindow_();
infoWindow.close();
this.dispatchEvent(new vit.component.LocationMap.LocationEvent(
vit.component.LocationMap.Events.SELECT, this, this.locationType_, index));
infoWindow.setContent(this.renderInfo_(this.locationList_[index]));
infoWindow.open(this.map_, marker);
};
/**
* Render info window for polling location.
* @param {vit.api.CivicInfo.PollingLocation} location The location to render.
* @return {Element} The info window content.
* @private
*/
vit.component.LocationMap.prototype.renderInfo_ = function(location) {
return goog.soy.renderAsElement(
vit.templates.pollingLocationInfoWindow, {pollingLocation: location,
originAddress: this.origin_});
};
/**
* Render info window for origin.
* @return {Element} The info window content.
* @private
*/
vit.component.LocationMap.prototype.renderOriginInfo_ = function() {
return goog.soy.renderAsElement(
vit.templates.normalizedAddress, {normalizedInput: this.origin_});
};
/**
* Remove all markers from the map.
*/
vit.component.LocationMap.prototype.removeMarkers = function() {
if (this.infoWindow_) {
this.infoWindow_.close();
}
for (var i = 0; i < this.markers_.length; i++) {
if (!this.markers_[i]) {
continue;
}
google.maps.event.clearInstanceListeners(this.markers_[i]);
this.markers_[i].setMap(null);
}
};
/**
* Get an InfoWindow object.
* @return {google.maps.InfoWindow} The info window.
* @private
*/
vit.component.LocationMap.prototype.getInfoWindow_ = function() {
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
return this.infoWindow_;
};
/**
* Get an Geocoder object.
* @return {google.maps.Geocoder} The geocoder instance.
* @private
*/
vit.component.LocationMap.prototype.getGeocoder_ = function() {
if (! this.geocoder_) {
this.geocoder_ = new google.maps.Geocoder();
}
return this.geocoder_;
};
/** @override */
vit.component.LocationMap.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
if (!this.origin_) {
// If no origin specified, center on the US.
this.loadMap(new google.maps.LatLng(39.061849, -96.811523), 3);
} else {
var origin = /** @type {vit.api.CivicInfo.Address} */ (this.origin_);
this.geocodeAddress(origin, goog.bind(function(address) {
// If the address is successfully geocoded, use it,
// otherwise center on the US.
this.loadMap(address && address.location ||
new google.maps.LatLng(39.061849, -96.811523), 3);
}, this));
}
};
/**
* Initialize the map.
* @param {google.maps.LatLng} center Map center.
* @param {number} zoom Zoom level.
*/
vit.component.LocationMap.prototype.loadMap = function(center, zoom) {
/** @type {google.maps.MapOptions} */
var opts = {
center: center,
maxZoom: 17,
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map_ = new google.maps.Map(this.getElement(), opts);
};
/** @override */
vit.component.LocationMap.prototype.exitDocument = function() {
goog.base(this, 'exitDocument');
};
/** @override */
vit.component.LocationMap.prototype.disposeInternal = function() {
this.locationList_ = null;
this.origin_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Object representing a location related event.
*
* @param {string} type Event type.
* @param {goog.events.EventTarget} target object initiating event.
* @param {string} locationType Type of location.
* @param {number} locationId Id of location.
* @extends {goog.events.Event}
* @constructor
*/
vit.component.LocationMap.LocationEvent = function(type, target,
locationType, locationId) {
goog.base(this, type, target);
/**
* Type of location.
* @type {string}
*/
this.locationType = locationType;
/**
* Id of location.
* @type {number}
*/
this.locationId = locationId;
};
goog.inherits(vit.component.LocationMap.LocationEvent, goog.events.Event);
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that renders local election official info.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Leo');
goog.require('goog.dom');
goog.require('vit.component.Component');
goog.require('vit.context');
goog.require('vit.templates.leo');
/**
* Component that handles rendering of the region selector.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Leo = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The notice subscription id.
* @type {!number}
* @private
*/
this.subscriptionId_;
};
goog.inherits(vit.component.Leo, vit.component.Component);
/** @override */
vit.component.Leo.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
this.subscriptionId_ = this.context_.subscribe(vit.context.CIVIC_INFO,
this.handleCivicInfo_, this);
};
/**
* Handles newly published civic info response by displaying a LEO box.
* @param {vit.api.CivicInfo.Response} civicInfo The published info.
* @private
*/
vit.component.Leo.prototype.handleCivicInfo_ = function(civicInfo) {
goog.dom.removeChildren(this.getElement());
if (!(civicInfo && civicInfo.state && civicInfo.state[0])) {
return;
}
/*
* Prefer the local election official, as long as there is a name and either
* a website or an official with a phone number.
*/
var region = civicInfo.state[0];
var local = region.local_jurisdiction;
/**
* @type {?vit.component.Leo.LeoInfo}
*/
var leo = local && this.getLeo_(local.electionAdministrationBody) || null;
if (!leo) {
leo = this.getLeo_(region.electionAdministrationBody);
}
if (!leo) {
return;
}
goog.soy.renderElement(this.getElement(), vit.templates.leo, leo);
};
/**
* Type definition for LEO info as passed to the template.
* @typedef {{
* administrationName: string,
* url: ?string,
* address: ?string,
* localOfficial: ?string,
* emailAddress: ?string,
* phoneNumber: ?string
* }}
*/
vit.component.Leo.LeoInfo;
/**
* Returns the the most appropriate data to display for local official contact
* information. Prefers the local election official, as long as there is a
* name and either
* a website or an official with a phone number.
* @param {vit.api.CivicInfo.ElectionAdministrationBody} jurisdiction The
* jurisdiction to check for LEO information.
* @return {?vit.component.Leo.LeoInfo} The Local Election Official Information.
* @private
*/
vit.component.Leo.prototype.getLeo_ = function(jurisdiction) {
var leo = {};
if (!(jurisdiction && jurisdiction.name)) {
return null;
} else {
leo.administrationName = jurisdiction.name;
}
if (jurisdiction.electionInfoUrl) {
leo.url = jurisdiction.electionInfoUrl;
}
if (jurisdiction.electionOfficials && jurisdiction.electionOfficials.length) {
var officials = jurisdiction.electionOfficials;
for (var i = 0; i < officials.length; i++) {
if (officials[i].name && officials[i].officePhoneNumber) {
leo.localOfficial = officials[i].name;
leo.phoneNumber = officials[i].officePhoneNumber;
leo.emailAddress = officials[i].emailAddress;
break;
}
}
}
if (!(leo.url || leo.phoneNumber)) {
return null;
}
/** @type {vit.api.CivicInfo.Address} */
var address =
jurisdiction.correspondenceAddress || jurisdiction.physicalAddress;
if (address) {
var addressStr = vit.api.CivicInfo.addressToString(address);
if (addressStr) {
leo.address = addressStr;
}
}
return /** {vit.component.Leo.LeoInfo} */ (leo);
};
/** @override */
vit.component.Leo.prototype.exitDocument = function() {
if (goog.isDefAndNotNull(this.subscriptionId_)) {
this.context_.unsubscribeById(this.subscriptionId_);
}
goog.base(this, 'exitDocument');
};
/** @override */
vit.component.Leo.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that handles rendering of notices.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Alert');
goog.require('goog.dom');
goog.require('vit.component.Component');
goog.require('vit.context');
goog.require('vit.templates.alert');
/**
* Component that handles rendering of the region selector.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Alert = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The notice subscription id.
* @type {!number}
* @private
*/
this.subscriptionId_;
};
goog.inherits(vit.component.Alert, vit.component.Component);
/** @override */
vit.component.Alert.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
this.subscriptionId_ = this.context_.subscribe(vit.context.NOTICE,
this.handleNotice_, this);
};
/**
* Handles a published notice by displaying an alert box.
* @param {vit.context.Notice} notice The published notice.
* @private
*/
vit.component.Alert.prototype.handleNotice_ = function(notice) {
if (notice) {
goog.soy.renderElement(this.getElement(), vit.templates.alert, notice);
} else {
goog.dom.removeChildren(this.getElement());
}
};
/** @override */
vit.component.Alert.prototype.exitDocument = function() {
if (goog.isDefAndNotNull(this.subscriptionId_)) {
this.context_.unsubscribeById(this.subscriptionId_);
}
goog.base(this, 'exitDocument');
};
/** @override */
vit.component.Alert.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that manages scrolling tabs.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.ScrollingTabBar');
goog.require('goog.soy');
goog.require('goog.ui.Button');
goog.require('goog.ui.Component.EventType');
goog.require('goog.ui.TabBar');
goog.require('vit.component.Component');
goog.require('vit.util');
/**
* Create contest info component.
*
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.ScrollingTabBar = function(opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* Tab Bar component.
* @type {goog.ui.TabBar}
* @private
*/
this.tabBar_;
/**
* Tab bounds array. The bounds for tab index i are tabBounds_[i] and
* tabBounds_[i+1].
* @type {Array.<number>}
* @private
*/
this.tabBounds_;
/**
* Left button.
* @type {goog.ui.Button}
* @private
*/
this.leftButton_;
/**
* Right button.
* @type {goog.ui.Button}
* @private
*/
this.rightButton_;
};
goog.inherits(vit.component.ScrollingTabBar, vit.component.Component);
/**
* Additional padding in px from the edge of the tab viewport.
* @type {number}
* @const
*/
vit.component.ScrollingTabBar.VIEWPORT_PADDING = 30;
/** @override */
vit.component.ScrollingTabBar.prototype.decorateInternal = function(element) {
this.setElementInternal(element);
var tabBarEl = this.getElementByClass(goog.getCssName('goog-tab-bar'));
if (!tabBarEl) {
return;
}
var tabBar = new goog.ui.TabBar();
this.addChild(tabBar);
tabBar.decorate(tabBarEl);
this.tabBar_ = tabBar;
this.getHandler().listen(
this.tabBar_,
goog.ui.Component.EventType.SELECT,
this.handleTabSelection_);
var leftButton = new goog.ui.Button(null);
this.addChild(leftButton);
leftButton.decorate(this.getElementByClass(
goog.getCssName('scrolling-tab-bar-left-btn')));
this.getHandler().listen(
leftButton,
goog.ui.Component.EventType.ACTION,
goog.bind(this.handleScrollButtonAction_, this, 0.5));
this.leftButton_ = leftButton;
var rightButton = new goog.ui.Button(null);
this.addChild(rightButton);
rightButton.decorate(this.getElementByClass(
goog.getCssName('scrolling-tab-bar-right-btn')));
this.getHandler().listen(
rightButton,
goog.ui.Component.EventType.ACTION,
goog.bind(this.handleScrollButtonAction_, this, -0.5));
this.rightButton_ = rightButton;
};
/**
* Gets the index of the selected tab.
* @return {number} The selected tab index.
*/
vit.component.ScrollingTabBar.prototype.getSelectedTabIndex = function() {
return this.tabBar_.getSelectedTabIndex();
};
/**
* Gets the index of the selected tab.
* @param {number} index Index of tab to select.
*/
vit.component.ScrollingTabBar.prototype.setSelectedTabIndex = function(index) {
this.tabBar_.setSelectedTabIndex(index);
};
/**
* Handles tab selection events.
* @param {goog.events.Event} e The event object.
* @private
*/
vit.component.ScrollingTabBar.prototype.handleTabSelection_ = function(e) {
var selectedTab = /** @type {goog.ui.Component}*/ e.target;
var tabIndex = this.tabBar_.getSelectedTabIndex();
this.fitTab_(tabIndex);
};
/**
* Handles left button actions.
* @param {number} distance The distance to scroll as a fraction of the
* viewport width.
* @param {goog.events.Event} e The event object.
* @private
*/
vit.component.ScrollingTabBar.prototype.handleScrollButtonAction_ =
function(distance, e) {
var viewportWidth =
this.getElementByClass(goog.getCssName('scrolling-tab-bar-viewport'))
.clientWidth;
var tabWidth = this.tabBounds_[this.tabBounds_.length - 1];
var left = this.tabBar_.getElement().offsetLeft;
left = left + (distance * viewportWidth);
left = Math.min(0, Math.max(left, viewportWidth - tabWidth));
goog.style.setStyle(this.tabBar_.getElement(), 'left', left + 'px');
this.updateButtonEnabledState_(left, tabWidth, viewportWidth);
};
/**
* Updates the enabled state of the buttons.
* @param {number} left The left offset of the tab bar.
* @param {number} tabBarWidth The width of the tab bar.
* @param {number} viewportWidth The width of the viewport.
* @private
*/
vit.component.ScrollingTabBar.prototype.updateButtonEnabledState_ =
function(left, tabBarWidth, viewportWidth) {
var enableLeft = left < 0;
this.leftButton_.setEnabled(enableLeft);
vit.util.setCssEnabled(this.leftButton_.getElement(), enableLeft);
var enableRight = (viewportWidth - left) < tabBarWidth;
this.rightButton_.setEnabled(enableRight);
vit.util.setCssEnabled(this.rightButton_.getElement(), enableRight);
};
/**
* Returns the left offset that will allow a tab to fit in the viewport.
* @param {number} tabIndex Index of the selected tab.
* @private
*/
vit.component.ScrollingTabBar.prototype.fitTab_ = function(tabIndex) {
if (!this.tabBounds_) {
this.tabBounds_ = this.measureTabBounds();
}
var tabLeft = this.tabBounds_[tabIndex];
var tabRight = this.tabBounds_[tabIndex + 1];
var tabWidth = this.tabBounds_[this.tabBounds_.length - 1];
var viewportWidth = this.getElementByClass('scrolling-tab-bar-viewport')
.clientWidth;
var viewportBoundLeft = 0 - this.tabBar_.getElement().offsetLeft;
var viewportBoundRight = viewportBoundLeft + viewportWidth;
var left;
if (tabLeft < viewportBoundLeft) {
var newOffset = vit.component.ScrollingTabBar.VIEWPORT_PADDING - tabLeft;
left = Math.min(0, newOffset);
} else if (tabRight > viewportBoundRight) {
var newOffset = viewportWidth -
vit.component.ScrollingTabBar.VIEWPORT_PADDING - tabRight;
left = Math.max(viewportWidth - tabWidth, newOffset);
} else {
left = -viewportBoundLeft;
}
goog.style.setStyle(this.tabBar_.getElement(), 'left', left + 'px');
this.updateButtonEnabledState_(left, tabWidth, viewportWidth);
};
/**
* Measures tab bounds and returns them as an array.
* @return {Array.<number>} The left offset.
*/
vit.component.ScrollingTabBar.prototype.measureTabBounds = function() {
var tabBarEl = this.tabBar_.getElement();
var tabEls = goog.dom.getChildren(this.tabBar_.getElement());
var position = 0;
var tabCount = tabEls.length;
var tabBounds = [];
// Rather than try to calculate the outer width, use the difference between
// sum of client widths and client width of container. This assumes all tabs
// have the same margins and borders and that container has no padding. Also
// assumes no properties will change that will affect the tab widths.
//
for (var i = 0; i < tabCount; i++) {
tabBounds.push(position);
position += tabEls[i].clientWidth;
}
var containerWidth = tabBarEl.clientWidth;
var offset = Math.floor((containerWidth - position) / tabCount);
for (var i = 0; i < tabCount; i++) {
tabBounds[i] = tabBounds[i] + (i * offset);
}
// Add the container width so that it is possible to determine the bounds of
// every element from the array.
tabBounds.push(containerWidth - offset);
return tabBounds;
};
/** @override */
vit.component.ScrollingTabBar.prototype.disposeInternal = function() {
this.tabBar_ = null;
this.tabBounds_ = null;
this.leftButton_ = null;
this.rightButton_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that handles the address input dialog.
* @author jmwaura@google.com (Jesse Mwaura)
* TODO(jmwaura): This component expects to be disposed whenever its elements
* are removed from the dom. Clean up the event handling so that this is not
* the case.
*/
goog.provide('vit.component.AddressDialog');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.forms');
goog.require('goog.dom.selection');
goog.require('goog.events');
goog.require('goog.events.FocusHandler');
goog.require('goog.events.InputHandler');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.soy');
goog.require('goog.ui.Button');
goog.require('vit.component.Component');
goog.require('vit.component.RegionSelector');
goog.require('vit.templates.addressDialog');
/**
* Component that manages address input dialog.
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
* @extends {vit.component.Component}
* @constructor
*/
vit.component.AddressDialog = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* Address text box element.
* @type {Element}
* @private
*/
this.addressBox_;
/**
* Autocomplete suggestion element.
* @type {Element}
* @private
*/
this.hintBox_;
/**
* Suggestion listener.
* @type {?number}
* @private
*/
this.suggestionListener_;
/**
* Key handler.
* @type {goog.events.KeyHandler}
* @private
*/
this.keyHandler_;
/**
* Focus handler.
* @type {goog.events.FocusHandler}
* @private
*/
this.focusHandler_;
/**
* Input handler.
* @type {goog.events.InputHandler}
* @private
*/
this.inputHandler_;
};
goog.inherits(vit.component.AddressDialog, vit.component.Component);
vit.component.AddressDialog.ADDRESS_EXAMPLE = "1600 Pennsylvania Ave NW, " +
"Washington DC";
/** @override */
vit.component.AddressDialog.prototype.createDom = function() {
var element = goog.soy.renderAsElement(vit.templates.addressDialog);
this.setElementInternal(element);
var regionSelector = new vit.component.RegionSelector(this.context_);
this.addChild(regionSelector);
regionSelector.decorate(
this.getElementByClass(goog.getCssName('region-selector'))
);
var searchButton = new goog.ui.Button(null);
this.addChild(searchButton);
searchButton.decorate(
this.getElementByClass(goog.getCssName('address-search-button'))
);
this.getHandler().listen(searchButton, goog.ui.Component.EventType.ACTION,
this.submit_);
this.addressBox_ = this.getElementByClass(goog.getCssName('address-input'));
this.hintBox_ = this.getElementByClass(goog.getCssName('address-hint'));
this.keyHandler_ = this.keyHandler_ || new goog.events.KeyHandler();
this.registerDisposable(this.keyHandler_);
};
/**
* Submit the address.
* @private
*/
vit.component.AddressDialog.prototype.submit_ = function() {
var fieldValue = goog.dom.forms.getValue(this.addressBox_);
var value = goog.string.trim(/** @type {string} */(fieldValue));
if (!!value) {
goog.dom.classes.enable(
this.getElement(), goog.getCssName('loading'), true);
this.context_.set(vit.context.ADDRESS,
goog.dom.forms.getValue(this.addressBox_));
}
};
/** @override */
vit.component.AddressDialog.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
goog.dom.forms.setValue(this.hintBox_,
vit.component.AddressDialog.ADDRESS_EXAMPLE)
this.suggestionListener_ = this.context_.subscribe(
vit.context.ADDRESS_SUGGESTION,
goog.bind(this.handleSuggestion_, this)
);
this.keyHandler_.attach(this.addressBox_);
this.getHandler().listen(
this.keyHandler_,
goog.events.KeyHandler.EventType.KEY,
this.handleKeyEvents_
);
this.focusHandler_ = new goog.events.FocusHandler(this.addressBox_);
this.getHandler().listen(this.focusHandler_,
goog.events.FocusHandler.EventType.FOCUSIN, this.handleInput_);
this.inputHandler_ = new goog.events.InputHandler(this.addressBox_);
this.getHandler().listen(this.inputHandler_,
goog.events.InputHandler.EventType.INPUT, this.handleInput_);
};
/**
* Handle Key events.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
vit.component.AddressDialog.prototype.handleKeyEvents_ = function(e) {
var el = /** @type Element */ (e.target);
var value = goog.dom.forms.getValue(el);
var hint = goog.dom.forms.getValue(this.hintBox_);
/**
* If TAB, RIGHT or ENTER and at the end of the text, complete.
* Else if DELETE or BACKSPACE at end of text, remove hint.
* If ENTER, always submit (but after completion).
*/
if ((e.keyCode == goog.events.KeyCodes.TAB ||
e.keyCode == goog.events.KeyCodes.RIGHT ||
e.keyCode == goog.events.KeyCodes.ENTER) &&
goog.dom.selection.getStart(el) >= value.length &&
hint.lastIndexOf(value, 0) == 0) {
// TODO(jmwaura): Handle RTL languages.
goog.dom.forms.setValue(el, hint);
} else if ((e.keyCode == goog.events.KeyCodes.DELETE ||
e.keyCode == goog.events.KeyCodes.BACKSPACE) &&
goog.dom.selection.getStart(el) >= value.length &&
hint.length > value.length) {
goog.dom.forms.setValue(this.hintBox_, '');
e.preventDefault();
}
if (e.keyCode == goog.events.KeyCodes.ENTER) {
this.submit_();
}
};
/**
* Handle Input.
* @param {goog.events.BrowserEvent} e The event.
* @private
*/
vit.component.AddressDialog.prototype.handleInput_ = function(e) {
var el = /** @type Element */ (e.target);
var value = goog.dom.forms.getValue(el);
this.hintBox_.value = '';
this.context_.set(vit.context.ADDRESS_ENTRY, value);
};
/**
* Handle suggestions.
* @param {?string} suggestion The suggestion.
* @private
*/
vit.component.AddressDialog.prototype.handleSuggestion_ = function(suggestion) {
goog.dom.forms.setValue(this.hintBox_,
/** @type {string} */ (suggestion) || '');
};
/** @override */
vit.component.AddressDialog.prototype.exitDocument = function() {
this.focusHandler_.dispose();
this.focusHandler_ = null;
this.inputHandler_.dispose();
this.inputHandler_ = null;
this.keyHandler_.detach();
this.context_.unsubscribeById(this.suggestionListener_);
goog.base(this, 'exitDocument');
};
/** @override */
vit.component.AddressDialog.prototype.disposeInternal = function() {
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Base component that fires document change events.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Component');
goog.provide('vit.component.Component.EventType');
goog.require('goog.dom');
goog.require('goog.events.Event');
goog.require('goog.ui.Component');
/**
* Base component that fires document change events.
*
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {goog.ui.Component}
* @constructor
*/
vit.component.Component = function(opt_domHelper) {
goog.base(this, opt_domHelper);
};
goog.inherits(vit.component.Component, goog.ui.Component);
/** @override */
vit.component.Component.prototype.enterDocument = function() {
goog.base(this, 'enterDocument');
this.dispatchDocumentChangeEvent();
};
/**
* Dispatches a document change event.
* @protected
*/
vit.component.Component.prototype.dispatchDocumentChangeEvent = function() {
this.dispatchEvent(new goog.events.Event(
vit.component.Component.EventType.DOCUMENT_CHANGE, this));
};
/**
* Common events fired by VIT components.
* @enum {string}
*/
vit.component.Component.EventType = {
DOCUMENT_CHANGE: 'vit.component.documentchange'
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that handles rendering of the region selector.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.RegionSelector');
goog.require('goog.Uri.QueryData');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('vit.api');
goog.require('vit.api.StaticMap');
goog.require('vit.component.Component');
goog.require('vit.context');
/**
* Component that handles rendering of the region selector.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.RegionSelector = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* The currently selected state.
* @type {?string}
* @private
*/
this.currentRegion_ = null;
};
goog.inherits(vit.component.RegionSelector, vit.component.Component);
/**
* Decorates a region selector by adding handlers for user global
* events.
* @param {Element} element The DIV element to decorate.
* @override
*/
vit.component.RegionSelector.prototype.decorateInternal =
function(element) {
goog.base(this, 'decorateInternal', element);
var callback = goog.bind(this.updateRegion_, this);
/** @type {number} */
this.regionSubscription_ = this.context_.subscribe(vit.context.REGION,
callback);
this.updateRegion_(
/** @type {string} */ (this.context_.get(vit.context.REGION))
);
};
/**
* Update display to show currently selected region.
* @param {?string} region The currently selected region.
* @private
*/
vit.component.RegionSelector.prototype.updateRegion_ = function(region) {
/**
* Default to the US.
* TODO(jmwaura): Remove hard coded country, use configuration instead.
*/
region = /** @type {string} */ (region) || 'US';
/**
* Check that region has changed.
*/
if (region != this.currentRegion_) {
this.currentRegion_ = region;
goog.dom.removeChildren(this.element_);
goog.dom.appendChild(this.element_,
goog.dom.createDom(goog.dom.TagName.IMG,
{src: vit.api.StaticMap.generateMapUrl(region)}));
}
};
/** @override */
vit.component.RegionSelector.prototype.disposeInternal = function() {
if (goog.isDefAndNotNull(this.regionSubscription_)) {
this.context_.unsubscribeById(this.regionSubscription_);
}
this.context_ = null;
goog.base(this, 'disposeInternal');
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that renders the polling location data.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.PollingInfo');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.fx.dom.Scroll');
goog.require('goog.fx.easing');
goog.require('goog.ui.TabBar');
goog.require('vit.api.StaticMap');
goog.require('vit.component.Accordion');
goog.require('vit.component.Component');
goog.require('vit.component.LocationMap');
goog.require('vit.templates.pollingInfo');
goog.require('vit.util');
/**
* Component that handles rendering of polling location information.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.PollingInfo = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
/**
* Location map component.
* @type {vit.component.LocationMap}
* @private
*/
this.locationMap_;
/**
* Formatted data.
* @type {Object.<string, *>}
*/
this.formattedData_;
/**
* Map of LocationTypes to Polling Location lists
* @type {Object.<string, goog.ui.TabBar>}
* @private
*/
this.locationLists_ = {};
};
goog.inherits(vit.component.PollingInfo, vit.component.Component);
/**
* Enumeration of location types.
* @enum {string}
*/
vit.component.PollingInfo.LocationType = {
EARLY_VOTE: 'early_vote',
POLLING_LOCATION: 'polling_location'
};
/** @override */
vit.component.PollingInfo.prototype.createDom = function() {
var data = this.formatData_();
this.formattedData_ = data;
var element = goog.soy.renderAsElement(vit.templates.pollingInfo, data);
this.decorateVoterInfo(element);
this.setElementInternal(element);
};
/**
* Decorate Voter Info elements.
* @param {Element} el The element that contains the voter info.
*/
vit.component.PollingInfo.prototype.decorateVoterInfo = function(el) {
var accordionEl = goog.dom.getElementByClass(
goog.getCssName('voter-info-accordion'), el);
var accordion = new vit.component.Accordion();
this.addChild(accordion);
accordion.decorate(accordionEl);
this.getHandler().listen(accordion, goog.ui.Component.EventType.SELECT,
this.onAccordionSelect);
var earlyVoteZippyEl = goog.dom.getElementByClass(
goog.getCssName('early-vote-zippy'), el);
var earlyVoteEl = earlyVoteZippyEl && goog.dom.getElementByClass(
goog.getCssName('location-list'), earlyVoteZippyEl);
if (earlyVoteEl) {
var earlyVoteList = new goog.ui.TabBar();
this.locationLists_[vit.component.PollingInfo.LocationType.EARLY_VOTE] =
earlyVoteList;
this.addChild(earlyVoteList);
earlyVoteList.decorate(earlyVoteEl);
this.getHandler().listen(earlyVoteList, goog.ui.Component.EventType.SELECT,
goog.bind(function(list, ev) {
this.scrollIntoView(ev.target.getElement());
this.locationMap_.selectLocation(list.getSelectedTabIndex());
}, this, earlyVoteList));
}
var otherLocationsZippyEl = goog.dom.getElementByClass(
goog.getCssName('other-locations-zippy'), el);
var otherLocationsEl = otherLocationsZippyEl && goog.dom.getElementByClass(
goog.getCssName('location-list'), otherLocationsZippyEl);
if (otherLocationsEl) {
var otherLocationsList = new goog.ui.TabBar();
this.locationLists_[
vit.component.PollingInfo.LocationType.POLLING_LOCATION] =
otherLocationsList;
this.addChild(otherLocationsList);
otherLocationsList.decorate(otherLocationsEl);
this.getHandler().listen(otherLocationsList,
goog.ui.Component.EventType.SELECT,
goog.bind(function(list, ev) {
this.scrollIntoView(ev.target.getElement());
this.locationMap_.selectLocation(list.getSelectedTabIndex());
}, this, otherLocationsList));
}
};
/**
* Scrolls an element into view.
* @param {Element} child Child element to scroll into view.
*/
vit.component.PollingInfo.prototype.scrollIntoView = function(child) {
var parent = goog.dom.getParentElement(child);
var coords = goog.style.getContainerOffsetToScrollInto(child, parent, true);
new goog.fx.dom.Scroll(parent, [parent.scrollLeft, parent.scrollTop],
[parent.scrollLeft, coords.y], 300, goog.fx.easing.easeOut).play();
};
/**
* Handles a selection from the polling info accordion.
* @param {goog.events.Event} ev The SELECT event.
*/
vit.component.PollingInfo.prototype.onAccordionSelect = function(ev) {
var sectionEl = ev.target.getSelected();
if (!sectionEl) {
this.removeLocationMap_();
return;
}
if (goog.dom.classes.has(sectionEl, goog.getCssName('early-vote-zippy')) &&
this.formattedData_.earlyVoteSites &&
this.formattedData_.normalizedInput) {
this.getLocationMap_().setLocations(
vit.component.PollingInfo.LocationType.EARLY_VOTE,
this.formattedData_.earlyVoteSites);
} else if (goog.dom.classes.has(sectionEl,
goog.getCssName('other-locations-zippy')) &&
this.formattedData_.allPollingLocations &&
this.formattedData_.normalizedInput) {
this.getLocationMap_().setLocations(
vit.component.PollingInfo.LocationType.POLLING_LOCATION,
this.formattedData_.allPollingLocations);
} else {
this.removeLocationMap_();
}
};
/**
* Gets an existing locationMap or renders one if none exists.
* @return {vit.component.LocationMap} The location map.
* @private
*/
vit.component.PollingInfo.prototype.getLocationMap_ = function() {
if (!this.locationMap_) {
this.locationMap_ = new vit.component.LocationMap(
this.formattedData_.normalizedInput);
var contestPaneEl = goog.dom.getElementByClass(
goog.getCssName('contest-pane'));
this.locationMap_.render(contestPaneEl);
this.getHandler().listen(this.locationMap_,
vit.component.LocationMap.Events.SELECT, goog.bind(
this.handleMapSelectEvent, this));
this.getHandler().listen(this.locationMap_,
vit.component.LocationMap.Events.GEOCODE, goog.bind(
this.handleMapGeocodeEvent, this));
}
return this.locationMap_;
};
/**
* Handle select event from map.
* @param {vit.component.LocationMap.LocationEvent} ev The event.
*/
vit.component.PollingInfo.prototype.handleMapSelectEvent = function(ev) {
var tabBar = this.locationLists_[ev.locationType];
if (tabBar.getSelectedTabIndex() != ev.locationId) {
tabBar.setSelectedTabIndex(ev.locationId);
}
};
/**
* Handle geocode event from map.
* @param {vit.component.LocationMap.LocationEvent} ev The event.
*/
vit.component.PollingInfo.prototype.handleMapGeocodeEvent = function(ev) {
var tabBar = this.locationLists_[ev.locationType];
var el = tabBar.getChildAt(ev.locationId)
.getElementByClass(goog.getCssName('polling-pin-icon'));
goog.dom.classes.remove(el, goog.getCssName('hidden'));
};
/**
* Removes an existing locationMap.
* @private
*/
vit.component.PollingInfo.prototype.removeLocationMap_ = function() {
if (this.locationMap_) {
goog.events.removeAll(this.locationMap_);
this.locationMap_.dispose();
this.locationMap_ = null;
}
};
/**
* Formats API data for use in the template.
* @return {Object.<string, *>} Object containing info to render.
* @private
*/
vit.component.PollingInfo.prototype.formatData_ = function() {
var civicInfo = /** @type vit.api.CivicInfo.Response */
(this.context_.get(vit.context.CIVIC_INFO));
var staticMapUrl;
var directionsUrl;
var mapUrl;
if (civicInfo.pollingLocations && civicInfo.pollingLocations.length) {
var pl = civicInfo.pollingLocations[0];
staticMapUrl = this.getStaticMapUrl_(pl.address);
directionsUrl = this.getDirectionsUrl_(civicInfo.normalizedInput,
pl.address);
mapUrl = this.getMapUrl_(pl.address);
}
var formattedPollingLocations = civicInfo.pollingLocations &&
civicInfo.pollingLocations.length &&
this.formatAllThePollingLocations_(civicInfo.pollingLocations) || null;
var formattedEarlyVoteSites = civicInfo.earlyVoteSites &&
civicInfo.earlyVoteSites.length &&
this.formatAllThePollingLocations_(civicInfo.earlyVoteSites) || null;
return {
pollingLocation: formattedPollingLocations && formattedPollingLocations[0],
normalizedInput: this.formatAddress_(civicInfo.normalizedInput),
staticMapUrl: staticMapUrl,
directionsUrl: directionsUrl,
mapUrl: mapUrl,
allPollingLocations: formattedPollingLocations &&
formattedPollingLocations.length > 1 &&
formattedPollingLocations || null,
earlyVoteSites: formattedEarlyVoteSites,
suggestOfficial: vit.agent.CivicInfo.suggestOfficialWebsite(civicInfo)
};
};
/**
* Get a static map URL for a polling location.
* @param {vit.api.CivicInfo.Address} address Polling location address
* for which to generate a URL.
* @return {?string} Map URL.
* @private
*/
vit.component.PollingInfo.prototype.getStaticMapUrl_ = function(address) {
if (!address) {
return null;
}
var addressString = vit.api.CivicInfo.addressToString(address, true, true);
return vit.api.StaticMap.generateMapUrl(addressString, true, '150x100');
};
/**
* Get a directions URL for a polling location.
* @param {vit.api.CivicInfo.Address} from Address to use as start for
* directions.
* @param {vit.api.CivicInfo.Address} to Polling location address to use as
* destination for directions.
* @return {string} Map URL.
* @private
*/
vit.component.PollingInfo.prototype.getDirectionsUrl_ = function(from, to) {
var options = {
'saddr': vit.api.CivicInfo.addressToString(from, true, true),
'daddr': vit.api.CivicInfo.addressToString(to, true, true)
};
return new goog.Uri(vit.component.PollingInfo.MAPS_URL).setQueryData(
goog.Uri.QueryData.createFromMap(options)).toString();
};
/**
* Get a map URL for a polling location.
* @param {vit.api.CivicInfo.Address} address Polling location address
* for which to generate a URL.
* @return {string} Map URL.
* @private
*/
vit.component.PollingInfo.prototype.getMapUrl_ = function(address) {
var options = {
'q': vit.api.CivicInfo.addressToString(address, true, true)
};
return new goog.Uri(vit.component.PollingInfo.MAPS_URL).setQueryData(
goog.Uri.QueryData.createFromMap(options)).toString();
};
/**
* Formats a pollingLocation for use in the template.
* @param {vit.api.CivicInfo.PollingLocation} pollingLocation Polling location
* to format.
* @return {vit.api.CivicInfo.PollingLocation} Formatted polling location.
* @private
*/
vit.component.PollingInfo.prototype.formatPollingLocation_ =
function(pollingLocation) {
var clone = goog.object.clone(pollingLocation);
clone.address = pollingLocation.address && this.formatAddress_(clone.address);
clone.pollingHours = this.formatHours_(clone.pollingHours);
return /** @type {vit.api.CivicInfo.PollingLocation} */ (clone);
};
/**
* Formats all polling locations in a list for use in the template.
* @param {Array.<vit.api.CivicInfo.PollingLocation>} pollingLocations Polling
* locations to format.
* @return {Array.<vit.api.CivicInfo.PollingLocation>} Formatted polling
* locations.
* @private
*/
vit.component.PollingInfo.prototype.formatAllThePollingLocations_ =
function(pollingLocations) {
/**
* Array of polling locations.
* @type {Array.<vit.api.CivicInfo.PollingLocation>}
*/
var formatted = [];
var len = pollingLocations.length;
for (var i = 0; i < len; i++) {
formatted.push(this.formatPollingLocation_(pollingLocations[i]));
}
return formatted;
};
/**
* Formats an address for use in the template.
* @param {vit.api.CivicInfo.Address} address Address to format.
* @return {vit.api.CivicInfo.Address} Formatted address.
* @private
*/
vit.component.PollingInfo.prototype.formatAddress_ = function(address) {
if (!address) {
return address;
}
return /** @type {vit.api.CivicInfo.Address} */ ({
locationName: address.locationName &&
vit.util.selectiveTitleCase(address.locationName),
line1: address.line1 && vit.util.selectiveTitleCase(address.line1),
line2: address.line2 && vit.util.selectiveTitleCase(address.line2),
line3: address.line3 && vit.util.selectiveTitleCase(address.line3),
city: address.city && vit.util.selectiveTitleCase(address.city),
state: address.state && (address.state.length == 2) ?
address.state.toUpperCase() : address.state,
zip: address.zip
});
};
/**
* Formats polling hours for use in the template.
* @param {string} hours Hours string to format.
* @return {string} Formatted hours.
* @private
*/
vit.component.PollingInfo.prototype.formatHours_ = function(hours) {
if (!hours) {
return hours;
}
return hours.replace(/_/g, '-'); // Yay, DC!
};
/** @override */
vit.component.PollingInfo.prototype.disposeInternal = function() {
this.removeLocationMap_();
this.context_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Static map api URL.
* @type {string}
* @const
*/
vit.component.PollingInfo.MAPS_URL = 'https://maps.google.com/maps';
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Component that handles the address input and polling pane.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.component.Polling');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('vit.component.AddressDialog');
goog.require('vit.component.Component');
goog.require('vit.component.PollingInfo');
/**
* Component that handles rendering of polling location and address input.
*
* @param {vit.context.Context} context The application context.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper to use.
*
* @extends {vit.component.Component}
* @constructor
*/
vit.component.Polling = function(context, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The application context context.
* @type {vit.context.Context}
* @private
*/
this.context_ = context;
};
goog.inherits(vit.component.Polling, vit.component.Component);
/** @override */
vit.component.Polling.prototype.createDom = function() {
this.decorateInternal(this.dom_.createElement('div'));
};
/**
* Decorates a div by adding either the address dialog or the polling location
* component.
* @param {Element} element The DIV element to decorate.
* @override
*/
vit.component.Polling.prototype.decorateInternal = function(element) {
goog.base(this, 'decorateInternal', element);
var callback = goog.bind(this.handleCivicInfoChange_, this);
/**
* The subscription ID for polling location changes.
* @type {number}
* @private
*/
this.civicInfoSubscriptionId_ =
this.context_.subscribe(vit.context.CIVIC_INFO, callback);
this.updatePollingPane_();
};
/** @override */
vit.component.Polling.prototype.disposeInternal = function() {
if (goog.isDefAndNotNull(this.pollingInfoSubscriptionId_)) {
this.context_.unsubscribeById(this.pollingInfoSubscriptionId_);
}
this.context_ = null;
goog.base(this, 'disposeInternal');
};
/**
* Handle a polling location change by either showing the polling location
* information or the address entry dialog. Only redraw the polling location
* info if it has actually changed.
* @param {?vit.api.CivicInfo.Response} civicInfo The new polling location info.
* @param {?vit.api.CivicInfo.Response} oldCivicInfo The old polling location
* info.
* @private
*/
vit.component.Polling.prototype.handleCivicInfoChange_ =
function(civicInfo, oldCivicInfo) {
this.updatePollingPane_();
};
/**
* Update polling pane.
* @private
*/
vit.component.Polling.prototype.updatePollingPane_ = function() {
var civicInfo = /** @type vit.api.CivicInfo.Response */
(this.context_.get(vit.context.CIVIC_INFO));
if (civicInfo && (civicInfo.pollingLocations || civicInfo.earlyVoteSites)) {
this.renderPollingInfo_();
} else {
this.renderAddressDialog_();
}
};
/**
* Add a PollingInfo child component.
* @private
*/
vit.component.Polling.prototype.renderPollingInfo_ = function() {
this.disposeChildren_(this.removeChildren(true));
this.addChild(new vit.component.PollingInfo(this.context_), true);
var changeButton = this.getElementByClass(
goog.getCssName('change-address-link'));
this.getHandler().listenOnce(changeButton, goog.events.EventType.CLICK,
this.renderAddressDialog_);
};
/**
* Add an AddressDialog child component.
* @private
*/
vit.component.Polling.prototype.renderAddressDialog_ = function() {
this.disposeChildren_(this.removeChildren(true));
this.addChild(new vit.component.AddressDialog(this.context_), true);
};
/**
* Dispose of both pollingInfo and addressDialog components.
* @param {Array.<vit.component.Component>=} children Children to dispose.
* @private
*/
vit.component.Polling.prototype.disposeChildren_ = function(children) {
if (!children) {
return;
}
goog.array.forEach(/** @type {Array.<vit.component.Component>} */ (children),
function(child) {
child.dispose();
}
);
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview A key/value store that maintains application context
* and publishes notifications if any members change.
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit.context');
goog.provide('vit.context.ConfigName');
goog.provide('vit.context.Context');
goog.provide('vit.context.NoticeType');
goog.require('goog.Disposable');
goog.require('goog.object');
goog.require('goog.pubsub.PubSub');
/**
* Constructs a key/value store to maintain context.
* @constructor
* @extends {goog.Disposable}
*/
vit.context.Context = function() {
goog.base(this);
/**
* The stored data keyed by notification path.
* @type {Object.<string, *>}
* @private
*/
this.backingMap_ = {};
/**
* PubSub object used to publish change events.
* @type {goog.pubsub.PubSub}
* @private
*/
this.pubsub_ = new goog.pubsub.PubSub();
};
goog.inherits(vit.context.Context, goog.Disposable);
/**
* Stores data at the given key.
* @param {string} key Key at which to store data.
* @param {*} value Data to store.
*/
vit.context.Context.prototype.set = function(key, value) {
var old = goog.object.get(this.backingMap_, key);
goog.object.set(this.backingMap_, key, value);
this.publishChangeEvent(key, value, old);
};
/**
* Gets data at the given key.
* @param {string} key Key for which to get data.
* @return {*} the value stored at the given key.
*/
vit.context.Context.prototype.get = function(key) {
return goog.object.get(this.backingMap_, key);
};
/**
* Removes data at the given key.
* @param {string} key Key for which to remove data.
* @return {boolean} Whether or not a value was removed.
*/
vit.context.Context.prototype.remove = function(key) {
var old = goog.object.get(this.backingMap_, key);
var removed = goog.object.remove(this.backingMap_, key);
if (removed) {
this.publishChangeEvent(key, undefined, old);
}
return removed;
};
/**
* Subscribes a function to change notifications for a given key.
* @param {string} key The key on which to listen for changes.
* @param {Function} fn Function that will be called when a change occurs.
* @param {Object=} opt_context Object in whose context the function is to be
* called (the global scope if none).
* @return {number} Subscription ID.
*/
vit.context.Context.prototype.subscribe = function(key, fn, opt_context) {
return this.pubsub_.subscribe(key, fn, opt_context);
};
/**
* Unsubscribes a function from change notifications for a given key.
* @param {string} key The key from which to unsubscribe.
* @param {Function} fn Function that was previously subscribed to the key.
* @param {Object=} opt_context Object in whose context the function was to
* be called (the global scope if none).
* @return {boolean} Whether a matching subscription was removed.
*/
vit.context.Context.prototype.unsubscribe = function(key, fn,
opt_context) {
return this.pubsub_.unsubscribe(key, fn, opt_context);
};
/**
* Removes a subscription based on a given subscription id.
* @param {?number} subscriptionId Subscription ID.
* @return {boolean} Whether a matching subscription was removed.
*/
vit.context.Context.prototype.unsubscribeById = function(subscriptionId) {
if (goog.isDefAndNotNull(subscriptionId)) {
return this.pubsub_.unsubscribeByKey(subscriptionId);
}
return false;
};
/**
* Publish the change event with the new value.
* @param {string} key Key that changed.
* @param {*} newValue New value at given key.
* @param {*} oldValue Old value at the given key.
* @protected
*/
vit.context.Context.prototype.publishChangeEvent = function(key, newValue,
oldValue) {
this.pubsub_.publish(key, newValue, oldValue);
};
/**
* @override
*/
vit.context.Context.prototype.disposeInternal = function() {
this.pubsub_.dispose();
goog.object.clear(this.backingMap_);
this.backingMap_ = null;
goog.base(this, 'disposeInternal');
};
/**
* The ready state of the application.
* @type {string}
* @const
*/
vit.context.READY = 'ready';
/**
* The input address to be used for lookup.
* @type {string}
* @const
*/
vit.context.ADDRESS = 'address';
/**
* The currently selected state.
* @type {string}
* @const
*/
vit.context.REGION = 'region';
/**
* The information returned by the last lookup.
* @type {string}
* @const
*/
vit.context.CIVIC_INFO = 'civic_info';
/**
* The last published notice.
* @type {string}
* @const
*/
vit.context.NOTICE = 'notice';
/**
* The referring page or parent iframe.
*/
vit.context.REFERRER = 'referrer';
/**
* Type of notice.
* @enum {string}
*/
vit.context.NoticeType = {
INFO: 'info',
WARNING: 'warning',
ERROR: 'error'
};
/**
* Type definition of a notice.
* @typedef {{
* type: vit.context.NoticeType,
* title: string,
* desc: string
* }}
*/
vit.context.Notice;
/**
* The last published configuration.
* @type {string}
* @const
*/
vit.context.CONFIG = 'config';
/**
* The last reported address entry string.
* @type {string}
* @const
*/
vit.context.ADDRESS_ENTRY = 'address_entry';
/**
* The last address suggestion.
* @type {string}
* @const
*/
vit.context.ADDRESS_SUGGESTION = 'address_suggestion';
/**
* Type of config.
* @enum {string}
*/
vit.context.ConfigName = {
ELECTION_ID: 'election_id',
OFFICIAL_ONLY: 'official_only',
ADDRESS: 'address',
REGION: 'region'
};
| JavaScript |
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Main entry point for the Voter Information Tool.
*
* @author jmwaura@google.com (Jesse Mwaura)
*/
goog.provide('vit');
goog.provide('vit.Base');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.dom.ViewportSizeMonitor');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.locale');
goog.require('goog.net.jsloader');
goog.require('vit.agent.Autocomplete');
goog.require('vit.agent.CivicInfo');
goog.require('vit.agent.Xpc');
goog.require('vit.analytics.Analytics');
goog.require('vit.component.Component');
goog.require('vit.component.Page');
goog.require('vit.context');
goog.require('vit.context.Context');
/**
* Module to manage all top level components.
* @constructor
* @extends {vit.context.Context}
*/
vit.Base = function() {
goog.base(this);
/**
* The page component.
* @type {vit.component.Page}
* @private
*/
this.pageComponent_;
/**
* Configuration object.
* @type {Object.<string, *>}
* @private
*/
this.config_;
/**
* The xpc agent that handles communication between this page and the
* VIT frame.
* @type {vit.agent.Xpc}
* @private
*/
this.xpc_;
/**
* The timeout id for pending document change events.
* @type {?number}
* @private
*/
this.documentChangeTimeout_;
/**
* The listener for document change events.
* @type {?number}
* @private
*/
this.documentChangeListener_;
/**
* The listener for viewport size change events.
* @type {?number}
* @private
*/
this.viewportSizeListener_;
/**
* The last recorded content height.
* @type {?number}
* @private
*/
this.contentHeight_;
};
goog.inherits(vit.Base, vit.context.Context);
/**
* Default configuration for the tool.
* @const {Object}
*/
vit.Base.DEFAULT_CONFIG = {
'election_id': '4000',
'referrer': document.referrer
};
/**
* Number of milliseconds to wait for configuration.
* @const {number}
*/
vit.Base.CONFIG_TIMEOUT = 250;
/**
* The interval in milliseconds to wait before reacting to a document change
* event.
* @const {number}
*/
vit.Base.DOCUMENT_CHANGE_DEBOUNCE_TIMEOUT = 100;
/**
* Initialize VoterInfo. Install components and trigger initialization.
* @return {vit.Base} This instance.
*/
vit.Base.prototype.init = function() {
// Track the page view immediately.
vit.analytics.Analytics.getInstance().trackPageview();
this.subscribe(vit.context.CONFIG, this.onConfig_, this);
// Go ahead and start up with defaults after timeout elapses.
var timeout = setTimeout(goog.bind(function() {
this.set(vit.context.CONFIG, vit.Base.DEFAULT_CONFIG);
},this), vit.Base.CONFIG_TIMEOUT);
// Set up the xpc connection and listen for incoming configuration changes.
var xpc = new vit.agent.Xpc();
xpc.initInner();
xpc.registerService(vit.agent.Xpc.Service.CONFIG,
goog.bind(function(timeout, payload) {
// We have our configuration. Disable the timeout.
clearTimeout(timeout);
if (goog.isDefAndNotNull(this.get(vit.context.CONFIG))) {
// Configuration may only be set once. Ignore this.
return;
}
// Extend the defaults with the incoming configuration.
var config = {};
goog.object.extend(config, vit.Base.DEFAULT_CONFIG,
goog.json.parse(payload));
this.set(vit.context.CONFIG, config);
}, this, timeout));
xpc.connect(goog.bind(function() {
this.xpc_ = xpc;
this.registerDisposable(this.xpc_);
}, this));
return this;
};
/**
* Initialize components that are dependent on the page having loaded.
* @param {!Object.<string,*>} config The new configuration.
* @private
*/
vit.Base.prototype.onConfig_ = function(config) {
if (this.config_) {
throw new Error('Already configured.');
}
var uriList = [];
// Load jsapi for the ClientLocation or skip if a region is configured.
if (! goog.isDef(config[vit.context.REGION])) {
uriList.push({uri: new goog.Uri('https://www.google.com/jsapi')});
}
// Load maps api.
uriList.push({uri: new goog.Uri('https://maps.googleapis.com/maps/api/js')
.setParameterValue('key', vit.api.API_KEY)
.setParameterValue('sensor', 'false')
.setParameterValue('libraries', 'places')
.setParameterValue('v', '3.10')
.setParameterValue('language',
goog.locale.getLanguageSubTag(goog.LOCALE))});
// load gapi client.
uriList.push({
uri: new goog.Uri('https://apis.google.com/js/client.js'),
callbackParam: 'onload'
});
vit.util.load(uriList, goog.bind(this.onDepsLoaded_, this));
// Load analytics. No need to wait until loaded, we'll use async calls anyway.
goog.net.jsloader.load('https://ssl.google-analytics.com/ga.js');
};
/**
* Initialize components that are dependent on the all the js having loaded.
* @private
*/
vit.Base.prototype.onDepsLoaded_ = function() {
var civicInfoAgent = new vit.agent.CivicInfo(this).init();
this.registerDisposable(civicInfoAgent);
var autocompleteAgent = new vit.agent.Autocomplete(this).init();
this.registerDisposable(autocompleteAgent);
var config = this.get(vit.context.CONFIG);
if (config[vit.context.ConfigName.ADDRESS]) {
this.set(vit.context.ADDRESS, config[vit.context.ConfigName.ADDRESS]);
} else if (goog.isDef(config[vit.context.ConfigName.REGION])) {
// Make sure region is not explicitly set to null.
// This way we can distinguish between "please don't geocode" and
// "I have no clue, you do it."
if (config[vit.context.ConfigName.REGION]) {
this.set(vit.context.REGION, config[vit.context.ConfigName.REGION]);
}
} else {
if (google.loader.ClientLocation && google.loader.ClientLocation.address &&
google.loader.ClientLocation.address.region &&
google.loader.ClientLocation.address.country_code == 'US') {
this.set(vit.context.REGION, google.loader.ClientLocation.address.region);
}
}
this.decorate();
this.set(vit.context.READY, true);
};
/**
* Create components and attach to dom.
*/
vit.Base.prototype.decorate = function() {
var pageComponent = new vit.component.Page(this);
// Attach listener before rendering the page.
this.documentChangeListener_ = goog.events.listen(pageComponent,
vit.component.Component.EventType.DOCUMENT_CHANGE,
goog.bind(this.onDocumentChange_, this));
pageComponent.decorate(
goog.dom.getElementByClass(goog.getCssName('base')));
this.registerDisposable(pageComponent);
var vsm = new goog.dom.ViewportSizeMonitor();
this.registerDisposable(vsm);
this.viewportSizeListener_ = goog.events.listen(vsm,
goog.events.EventType.RESIZE,
goog.bind(this.onDocumentChange_, this));
};
/**
* Checks if client height has changed and publishes these changes over the xpc
* channel.
* @private
*/
vit.Base.prototype.onDebouncedDocumentChange_ = function() {
if (! this.xpc_) {
return;
}
this.documentChangeTimeout_ = null;
var height = document.body.clientHeight;
if (height != this.contentHeight_) {
this.contentHeight_ = height;
this.xpc_.send(vit.agent.Xpc.Service.RESIZE, '' + height);
}
};
/**
* Handles document change events.
* @private
*/
vit.Base.prototype.onDocumentChange_ = function() {
if (goog.isDefAndNotNull(this.documentChangeTimeout_)) {
return;
}
this.documentChangeTimeout_ = setTimeout(
goog.bind(this.onDebouncedDocumentChange_, this),
vit.Base.DOCUMENT_CHANGE_DEBOUNCE_TIMEOUT);
};
/** @override */
vit.Base.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
};
/**
* Main entry point for VoterInfo.
* @return {vit.Base} New Base instance.
* @private
*/
vit.init_ = function() {
return new vit.Base().init();
};
goog.exportSymbol('vit.init', vit.init_);
| JavaScript |
Point = function(x, y) {
this.x = x;
this.y = y;
};
Line = function(x1, y1, x2, y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
};
Line.prototype.getX1 = function() {
return this.x1;
};
Line.prototype.getX2 = function() {
return this.x2;
};
Line.prototype.getY1 = function() {
return this.y1;
};
Line.prototype.getY2 = function() {
return this.y2;
};
// 斜率
Line.prototype.getK = function() {
return (this.y2 - this.y1) / (this.x2 - this.x1);
};
// y = kx + d
Line.prototype.getD = function() {
return this.y1 - this.getK() * this.x1;
};
// 是否平行
Line.prototype.isParallel = function(line) {
// 因为double精度不够,如果差值小于某个值,就当它是相同
var x1 = this.x2;
var x2 = this.x2;
// 两条线都竖直,绝对是平行的
if ((Math.abs(x1 - x2) < 0.01) && (Math.abs(line.getX1() - line.getX2()) < 0.01)) {
return true;
} else if ((Math.abs(x1 - x2) < 0.01) && (Math.abs(line.getX1() - line.getX2()) > 0.01)) {
// 一条竖直,另一条不竖直,肯定不是平行的
return false;
} else if ((Math.abs(x1 - x2) > 0.01) && (Math.abs(line.getX1() - line.getX2()) < 0.01)) {
return false;
} else {
// 如果两条线都不是竖直的,就计算斜率
return Math.abs(this.getK() - line.getK()) < 0.01;
}
};
// 是否是同一条线
Line.prototype.isSameLine = function(line) {
if (this.isParallel(line)) {
// 平行,而有一个点在另一条线上,则是同一条线
var k = line.getK();
var d = line.getD();
if (Math.abs(this.x1 * k + d - this.y1) < 0.01) {
return true;
} else {
return false;
}
} else {
// 如果不平行,就不用考虑了
return false;
}
};
// 交点在线上,不在延长线上
Line.prototype.contains = function(p) {
var x1 = this.x1;
var y1 = this.y1;
var x2 = this.x2;
var y2 = this.y2;
var x = p.x;
var y = p.y;
var s = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
var s1 = (x - x1) * (x - x1) + (y - y1) * (y - y1);
var s2 = (x - x2) * (x - x2) + (y - y2) * (y - y2);
return s > s1 && s > s2;
};
Line.prototype.getCrossPoint = function(line) {
// 斜率相同,可能平行,可能重合
if (this.isParallel(line)) {
return null;
}
var x;
var y;
if (Math.abs(this.x1 - this.x2) < 0.01) {
// 如果当前这条线垂直
// y = k * x + d
x = this.x1;
y = line.getK() * x + line.getD();
} else if (Math.abs(line.getX1() - line.getX2()) < 0.01) {
// 如果连接线垂直
x = line.getX1();
y = this.getD();
} else {
var k1 = this.getK();
var k2 = line.getK();
var d1 = this.getD();
var d2 = line.getD();
// y = k1 * x + d1
// y = k2 * x + d2
x = (d2 - d1) / (k1 - k2);
y = k1 * x + d1;
}
var p = new Point(x, y);
if (line.contains(p) && this.contains(p)) {
return p;
} else {
return null;
}
};
Rect = function(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
Rect.prototype.getCrossPoint = function(line) {
var p = null;
var top = new Line(this.x, this.y, this.x + this.w, this.y);
p = top.getCrossPoint(line);
if (p != null) {
return p;
}
var bottom = new Line(this.x, this.y + this.h, this.x + this.w, this.y + this.h);
p = bottom.getCrossPoint(line);
if (p != null) {
return p;
}
var left = new Line(this.x, this.y, this.x, this.y + this.h);
p = left.getCrossPoint(line);
if (p != null) {
return p;
}
var right = new Line(this.x + this.w, this.y, this.x + this.w, this.y + this.h);
p = right.getCrossPoint(line);
return p;
};
Table = function(name, x, y, w, h) {
this.name = name;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
Fk = function(name, from, to) {
this.name = name;
this.from = tables[from];
this.to = tables[to];
};
var tables = {};
var fks = {};
// 拖拽需要这两个东西
var target = null;
var dx = 0;
var dy = 0;
function startDrag(evt, id) {
target = document.getElementById(id);
dx = target.getAttribute('x') - evt.clientX;
dy = target.getAttribute('y') - evt.clientY;
}
function endDrag(id) {
// 更新拖拽后的坐标
tables[id.substring(4)].x = parseFloat(target.getAttribute('x'));
tables[id.substring(4)].y = parseFloat(target.getAttribute('y'));
// 计算哪些外键连接线受到影响
var items = [];
for (var i in fks) {
item = fks[i];
if ("use_" + item.from.name == id || "use_" + item.to.name == id) {
items.push(item);
}
}
// 重画受到影响的连接线
for (var i = 0; i < items.length; i++) {
var item = items[i];
var from = item.from;
var to = item.to;
var line = document.getElementById(item.name + '_line');
var polyline = document.getElementById(item.name + '_polyline');
var text = document.getElementById(item.name + '_text');
if (from.name == to.name) {
var x1 = from.x + from.w / 2;
var y1 = from.y + from.h / 2;
var x2 = to.x + to.w / 2;
var y2 = to.y + to.h / 2;
var w = from.w;
var h = from.h;
// line
line.setAttribute('points', (x1 + w / 2) + " " + y1 + "," +
(x1 + w) + " " + y1 + "," +
(x1 + w) + " " + (y1 - h) + "," +
x1 + "," + (y1 - h) + "," +
x1 + " " + (y1 - h / 2));
// text
text.setAttribute('x', x1);
text.setAttribute('y', (y1 - h / 2));
// polyline
polyline.setAttribute('points', x2 + ' ' + (y2 - h / 2) + ',' +
(x2 - 10) + ' ' + (y2 - 20 - h / 2) + ',' +
(x2 + 10) + ' ' + (y2 - 20 - h / 2));
} else {
var fromX = from.x;
var fromY = from.y;
var fromW = from.w;
var fromH = from.h;
var toX = to.x;
var toY = to.y;
var toW = to.w;
var toH = to.h;
var xx1 = fromX + fromW / 2;
var yy1 = fromY + fromH / 2;
var xx2 = toX + toW / 2;
var yy2 = toY + toH / 2;
var x1;
var y1;
var x2;
var y2;
if (from != to) {
var fromLine = new Line(xx1, yy1, xx2, yy2);
var fromRect = new Rect(fromX, fromY, fromW, fromH);
var fromCrossPoint = fromRect.getCrossPoint(fromLine);
if (fromCrossPoint != null) {
x1 = fromCrossPoint.x;
y1 = fromCrossPoint.y;
} else {
x1 = xx1;
y1 = yy1;
}
var toLine = new Line(xx2, yy2, xx1, yy1);
var toRect = new Rect(toX, toY, toW, toH);
var toCrossPoint = toRect.getCrossPoint(toLine);
if (toCrossPoint != null) {
x2 = toCrossPoint.x;
y2 = toCrossPoint.y;
} else {
x2 = xx2;
y2 = yy2;
}
} else {
x1 = xx1;
y1 = yy1;
x2 = xx2;
y2 = yy2;
}
// line
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
// text
text.setAttribute('x', (x1 + x2) / 2 - item.name.length * 5);
text.setAttribute('y', (y1 + y2) / 2);
// polyline
var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt(a * a + b * b);
var sin = b / c;
var cos = a / c;
var sin1 = sin * Math.cos(0.5) + cos * Math.sin(0.5);
var cos1 = cos * Math.cos(0.5) - sin * Math.sin(0.5);
var sin2 = sin * Math.cos(0.5) - cos * Math.sin(0.5);
var cos2 = cos * Math.cos(0.5) + sin * Math.sin(0.5);
var dy1 = y2 + sin1 * 20;
var dx1 = x2 + cos1 * 20;
var dy2 = y2 + sin2 * 20;
var dx2 = x2 + cos2 * 20;
polyline.setAttribute('points', x2 + ' ' + y2 + ',' + dx1 + ' ' + dy1 + ',' + dx2 + ' ' + dy2);
}
}
target = null;
}
function doDrag(evt, id) {
if (target != null) {
target.setAttribute('x', evt.clientX + dx);
target.setAttribute('y', evt.clientY + dy);
}
}
| JavaScript |
/* Copyright SpringSide, 2005-2006 | www.springside.org.cn
* -----------------------------------------------------------
* The SpringSide Menu, version 1.0
*
* Author: cac
*/
//actform
document.write("<form id='menuActform' method='GET' target='' action=''></form>");
//创建上下移动箭头
document.write("<DIV id='Smenu' style='position:absolute;top:" + SS_Top + ";left:" + SS_Left + ";width:" + SS_Width + ";height:" + SS_Height + ";border:" + SS_BorderWidth + " " + SS_BorderStyle + " " + SS_BorderColor + ";background-color:" + SS_BackgroundColor + ";z-index:0;visibility:hidden;clip:rect(0," + SS_Width + "," + SS_Height + ",0)'>");
document.write("<img onMouseUp='Smenu.ArrowSelected(this)' onMouseDown='Smenu.ArrowClicked(this)' onMouseOver='Smenu.OverArrow(this)' onMouseOut='Smenu.OutArrow(this);' id='SS_SlideUp' height='" + SS_ArrowHeight + "' width='" + SS_ArrowWidth + "' src='" + SS_DownArrow + "' style='position:absolute;top:0;left:0;cursor:pointer;visibility:hidden;z-index:650'>");
document.write("<img onMouseUp='Smenu.ArrowSelected(this)' onMouseDown='Smenu.ArrowClicked(this)' onMouseOver='Smenu.OverArrow(this)' onMouseOut='Smenu.OutArrow(this);' id='SS_SlideDown' height='" + SS_ArrowHeight + "' width='" + SS_ArrowWidth + "' src='" + SS_UpArrow + "' style='position:absolute;top:0;left:0;cursor:pointer;visibility:hidden;z-index:650'>");
document.getElementById("Smenu").style.visibility = "visible";
//创建菜单
var itemNum = 1;
while (eval("window.Menu" + itemNum)) itemNum++;
itemNum--;
i = itemNum;
while (i > 0)
{
Folder = eval("Menu" + i);
MakeMenu(Folder, i);
i--;
}
document.write("</DIV>");
document.write("<style>");
document.write(".OB1_Class{position:absolute;left:0;width:" + SS_Width + ";height:" + SS_MenuBarHeight + ";line-height:2;font-size:" + SS_MenuBarFontSize + "pt;cursor:pointer;color:" + SS_MenuBarFontColor + ";border-width:0;background-color:#2159DA}");
document.write(".OBs_Class{left:0;width:" + SS_Width + ";height:" + SS_MenuBarHeight + ";line-height:2;font-family:" + SS_MenuBarFontFamily + ";font-size:" + SS_MenuBarFontSize + "pt;cursor:pointer;color:" + SS_MenuBarFontColor + "; border-width:0; background-color: #2159DA}");
document.write("</style>");
var Smenu = new SideMenu(SS_Width, SS_Height, itemNum, SS_MenuBarHeight, SS_BorderWidth, SS_SlideSpeed, SS_IconsHeight + SS_LabelFontSize + SS_LabelMargin + SS_ItemsSpacing, SS_ArrowSlideSpeed);
InitBar(SS_BackgroundImg, SS_BackgroundDownImg, SS_BackgroundOverImg, SS_BackgroundOverDownImg);
window.status = ITEM_TITLE;
//------------------------------------------------------------------------------------------------------------------
/*
* 创建菜单
*/
function MakeMenu(Folder, zorder)
{
var i = zorder;
if (i == 1)
{
document.write("<INPUT position='UP' id='SS_MenuBar1' TYPE='button' style='height:" + SS_MenuBarHeight + ";top:0;' value='" + Folder[0] + "' class='OB1_Class' onClick='this.blur();Smenu.FolderClicked(" + i + ");SetBgimage(" + i + ");'>");
var input = document.createElement('INPUT');
input.type = 'hidden';
input.value = 'UP';
input.id = 'SS_Position1';
document.getElementById('menuActform').appendChild(input);
MakeSubMenu(Folder, i, SS_MenuBarHeight);
}
else
{
document.write("<INPUT position='DOWN' id='SS_MenuBar" + i + "' TYPE='button' value='" + Folder[0] + "' style=\"height:" + SS_MenuBarHeight + ";position:absolute;top:" + (SS_Height - (itemNum + 1 - i) * SS_MenuBarHeight - SS_BorderWidth * 2) + "\" class='OBs_Class' onClick='this.blur();Smenu.FolderClicked(" + i + ");SetBgimage(" + i + ");'>");
var input = document.createElement('INPUT');
input.type = 'hidden';
input.value = 'DOWN';
input.id = 'SS_Position' + i;
document.getElementById('menuActform').appendChild(input);
MakeSubMenu(Folder, i, (SS_Height - (itemNum + 1 - i) * SS_MenuBarHeight - SS_BorderWidth * 2) + SS_MenuBarHeight);
}
}
/*
* 创建二级菜单
*/
function MakeSubMenu(Folder, zorder, top)
{
var folderWidth = (SS_Width - SS_BorderWidth * 2);
var sfolderWidth = folderWidth - 15;
var items = 0;
var j = 1;
while (Folder[j] != null)
{
items++;
j++;
}
document.write("<DIV id='SS_Folder" + zorder + "' style='FILTER: DropShadow(Color=" + SS_LabelFontShadowColor + ", OffX=1, OffY=1, Positive=1);position:absolute;left:0;top:" + top + ";width:" + folderWidth + ";height:" + (SS_Margin * 2 + items * (SS_IconsHeight + SS_LabelFontSize + SS_LabelMargin) + (items - 1) * SS_ItemsSpacing) + ";z-index:" + zorder + ";clip:rect(0 0 0 0);' >");
for (var i = 1; i <= items; i++)
{
var subfolder = Folder[i];
var top = (SS_Margin + Math.ceil(i - 1) * (SS_ItemsSpacing + SS_LabelFontSize + SS_IconsHeight) - 4) ;
if (navigator.appName == "Netscape") {
var imgbg = 0;
} else {
var imgbg = 4;
}
document.write("<div style='cursor: pointer;margin-left: 5px;padding:2px 5px 2px " + (SS_IconsWidth + 3) + "px;background-position:0 " + imgbg + ";background-image:url(" + subfolder[0] + ");background-repeat:no-repeat;width:" + sfolderWidth + ";height:" + SS_IconsHeight + ";position:absolute;top:" + top + ";left:0;' onclick=doSubTag('" + subfolder[3] + "','" + subfolder[2] + "') onMouseDown='Smenu.ItemClicked(this)' onMouseOver='Smenu.OverItems(this)' onMouseOut='Smenu.OutItems(this)' > ");
document.write("<font style='font-family:" + SS_LabelFontFamily + ";font-size:" + SS_LabelFontSize + "pt;color:" + SS_LabelFontColor + "'>" + subfolder[1] + "</font>");
document.write("</div>");
}
document.write("</DIV>");
}
/*
* 转向指定页面
*/
function doSubTag(target, link)
{
document.getElementById("menuActform").action = link;
document.getElementById("menuActform").target = target;
document.getElementById("menuActform").submit();
}
/*
* SpringSide Menu Object
*/
function SideMenu(width, height, items, buttonHeight, borderWidth, slideSpeed, slideArrowValue, ArrowSlideSpeed)
{
this.currentFolder = 1;
this.currentItem = null;
this.slideCount = 0;
this.slideStep = 1;
this.slideArrowValue = slideArrowValue;
this.slideSpeed = slideSpeed;
this.borderWidth = borderWidth;
this.width = width;
this.visibleAreaHeight = height - 2 * borderWidth - items * buttonHeight;
this.visibleAreaWidth = width;
this.FolderClicked = FolderClicked;
this.SlideFolders = SlideFolders;
this.ItemClicked = ItemClicked;
this.OverItems = OverItems;
this.OutItems = OutItems;
this.OverArrow = OverArrow;
this.OutArrow = OutArrow;
this.ArrowClicked = ArrowClicked;
this.ArrowSelected = ArrowSelected;
this.ArrowSlideSpeed = ArrowSlideSpeed;
this.SlideItems = SlideItems;
this.SlideItemsAction = SlideItemsAction;
this.Start = Start;
this.ClipFolder = ClipFolder;
this.SetArrows = SetArrows;
this.HideArrows = HideArrows;
this.sliding = false;
this.items = items;
this.started = false;
if (navigator.appName == "Netscape") {
this.filter = /rect\([\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],?\)/;
} else {
this.filter = /rect\([\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],? [\+-]?(\d*)p[x|t],?\)/;
}
this.Start();
}
/*
* 初始化菜单图片及背景
*/
function InitBar(img, dimg, oimg, odimg)
{
var orign = new Array();
var oldTD = null;
for (var i = 1; i <= itemNum; i++)
{
document.getElementById("SS_MenuBar" + i).cid = Math.ceil((new Date().getTime()) * Math.random());
if (i == 1) document.getElementById("SS_MenuBar" + i).style.background = 'url(' + dimg + ')';
else document.getElementById("SS_MenuBar" + i).style.background = 'url(' + img + ')';
document.getElementById("SS_MenuBar" + i).onmousedown = function()
{
this.style.background = 'url(' + dimg + ')';
orign[this.cid] = this.style.background;
}
document.getElementById("SS_MenuBar" + i).onmouseover = function()
{
oldTD = this;
orign[this.cid] = this.style.background;
if (this.style.background == 'url(' + dimg + ')')
this.style.background = 'url(' + odimg + ')';
else this.style.background = 'url(' + oimg + ')';
}
document.getElementById("SS_MenuBar" + i).onmouseout = function()
{
if (oldTD != null && oldTD.cid == this.cid)
{
this.style.background = orign[this.cid];
}
}
}
}
/*
* 设置背景图片
*/
function SetBgimage(folder)
{
for (var i = 1; i <= itemNum; i++)
{
if (i != folder)
{
document.getElementById("SS_MenuBar" + i).style.background = 'url(' + SS_BackgroundImg + ')';
}
}
}
/*
* 菜单点击时动作
*/
function FolderClicked(folder)
{
if (this.sliding)
return;
if (folder == this.currentFolder)
return;
this.sliding = true;
this.slideCount = this.visibleAreaHeight;
this.slideStep = 1;
this.countStep = 0;
this.HideArrows();
this.SlideFolders(folder, document.getElementById("SS_Position" + folder).value == "DOWN");
}
function SlideFolders(folder, down)
{
var step;
//alert(document.getElementById("SS_MenuBar1").style.pixelHeight+1 );
//alert(document.getElementById("SS_MenuBar1").style.height);
if (down)
{
this.slideCount -= Math.floor(this.slideStep);
if (this.slideCount < 0)
this.slideStep += this.slideCount;
step = Math.floor(this.slideStep);
for (var i = 2; i <= folder; i++)
if (document.getElementById("SS_Position" + i).value == "DOWN")
{
if (navigator.appName == "Netscape") {
var buttonTop = parseInt(document.getElementById("SS_MenuBar" + i).style.top);
document.getElementById("SS_MenuBar" + i).style.top = buttonTop - step;
var folderTop = parseInt(document.getElementById("SS_Folder" + i).style.top);
document.getElementById("SS_Folder" + i).style.top = folderTop - step;
//alert(document.getElementById("SS_Folder" + i).style.top);
} else {
document.getElementById("SS_MenuBar" + i).style.pixelTop -= step;
document.getElementById("SS_Folder" + i).style.pixelTop -= step;
//alert(document.getElementById("SS_Folder" + i).style.pixelTop);
}
}
//filter = /rect\((\d*)px (\d*)px (\d*)px (\d*)px\)/;
var clipString = document.getElementById("SS_Folder" + folder).style.clip;
var clip = clipString.match(this.filter);
this.ClipFolder(folder, parseInt(clip[1]), this.visibleAreaWidth, (parseInt(clip[3]) + step), 0);
var clipString = document.getElementById("SS_Folder" + this.currentFolder).style.clip;
var clip = clipString.match(this.filter);
//alert(clip);
this.ClipFolder(this.currentFolder, parseInt(clip[1]), this.visibleAreaWidth, (parseInt(clip[3]) - step), 0);
this.slideStep *= this.slideSpeed;
if (this.slideCount > 0)
setTimeout("Smenu.SlideFolders(" + folder + ",true)", 20);
else
{
for (var k = 2; k <= folder; k++)
{
document.getElementById("SS_Position" + k).value = "UP";
}
this.currentFolder = folder;
this.SetArrows();
this.sliding = false;
}
}
else
{
this.slideCount -= Math.floor(this.slideStep);
if (this.slideCount < 0)
this.slideStep += this.slideCount;
step = Math.floor(this.slideStep);
for (var i = folder + 1; i <= this.items; i++)
if (document.getElementById("SS_Position" + i).value == "UP")
{
if (navigator.appName == "Netscape") {
var buttonTop = parseInt(document.getElementById("SS_MenuBar" + i).style.top);
document.getElementById("SS_MenuBar" + i).style.top = buttonTop + step;
var folderTop = parseInt(document.getElementById("SS_Folder" + i).style.top);
document.getElementById("SS_Folder" + i).style.top = folderTop + step;
//alert(document.getElementById("SS_MenuBar" + i).style.top);
} else {
document.getElementById("SS_MenuBar" + i).style.pixelTop += step;
document.getElementById("SS_Folder" + i).style.pixelTop += step;
//alert(document.getElementById("SS_Folder" + i).style.pixelTop);
}
}
//filter = /rect\((\d*)px (\d*)px (\d*)px (\d*)px\)/;
var clipString = document.getElementById("SS_Folder" + folder).style.clip;
var clip = clipString.match(this.filter);
this.ClipFolder(folder, parseInt(clip[1]), this.visibleAreaWidth, (parseInt(clip[3]) + step), 0);
var clipString = document.getElementById("SS_Folder" + this.currentFolder).style.clip;
var clip = clipString.match(this.filter);
this.ClipFolder(this.currentFolder, parseInt(clip[1]), this.visibleAreaWidth, (parseInt(clip[3]) - step), 0);
this.slideStep *= this.slideSpeed;
if (this.slideCount > 0)
setTimeout("Smenu.SlideFolders(" + folder + ",false)", 20);
else
{
for (var k = folder + 1; k <= this.items; k++)
document.getElementById("SS_Position" + k).value = "DOWN";
this.currentFolder = folder;
this.SetArrows();
this.sliding = false;
}
}
}
function ItemClicked(item)
{
if (this.sliding)
return;
item.style.border = "1 inset #ffffff";
}
function OverItems(item)
{
if (this.sliding)
return;
item.style.border = '1px solid #8BA8C6';
item.style.backgroundColor = '#CEE9FE';
}
function OutItems(item)
{
if (this.sliding)
return;
item.style.border = '0px solid #8BA8C6';
item.style.backgroundColor = '#FFFFFF';
}
function ArrowClicked(arrow)
{
if (this.sliding)
return;
arrow.style.border = "1 inset #ffffff";
}
function ArrowSelected(arrow)
{
if (this.sliding)
return;
arrow.style.border = "0 none black";
this.SlideItems(arrow.id == "SS_SlideUp");
}
function OverArrow(arrow)
{
if (this.sliding)
return;
arrow.style.border = "1 outset #ffffff";
var folder = document.getElementById("SS_Folder" + Smenu.currentFolder).style;
if (navigator.appName == "Netscape") {
var top = parseInt(document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.top);
var height = parseInt(document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.height);
} else {
var top = document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.pixelTop;
var height = document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.pixelHeight;
}
var startTop = top + height;
}
function OutArrow(arrow)
{
if (this.sliding)
return;
arrow.style.border = "0 none black";
}
function ClipFolder(folder, top, right, bottom, left)
{
document.getElementById("SS_Folder" + folder).style.clip = clip = 'rect(' + top + ' ' + right + ' ' + bottom + ' ' + left + ')';
}
function Start()
{
if (!this.started)
{
this.ClipFolder(1, 0, this.visibleAreaWidth, this.visibleAreaHeight, 0);
this.SetArrows();
}
}
function SetArrows()
{
var downHeight = document.getElementById("SS_SlideDown").height;
var upWidth = document.getElementById("SS_SlideUp").width;
var downWidth = document.getElementById("SS_SlideDown").width;
if (navigator.appName == "Netscape") {
var top = parseInt(document.getElementById("SS_MenuBar" + this.currentFolder).style.top);
var height = parseInt(document.getElementById("SS_MenuBar" + this.currentFolder).style.height);
document.getElementById("SS_SlideUp").style.top = top + height + this.visibleAreaHeight - downHeight - 20;
document.getElementById("SS_SlideUp").style.left = this.width - upWidth - this.borderWidth - 10;
document.getElementById("SS_SlideDown").style.top = top + height + 20;
document.getElementById("SS_SlideDown").style.left = this.width - downWidth - this.borderWidth - 10;
var startTop = top + height;
var floderTop = parseInt(document.getElementById("SS_Folder" + this.currentFolder).style.top);
var floderHeight = parseInt(document.getElementById("SS_Folder" + this.currentFolder).style.height);
} else {
var top = document.getElementById("SS_MenuBar" + this.currentFolder).style.pixelTop;
var height = document.getElementById("SS_MenuBar" + this.currentFolder).style.pixelHeight;
document.getElementById("SS_SlideUp").style.pixelTop = top + height + this.visibleAreaHeight - downHeight - 20;
document.getElementById("SS_SlideUp").style.pixelLeft = this.width - upWidth - this.borderWidth - 10;
document.getElementById("SS_SlideDown").style.pixelTop = top + height + 20;
document.getElementById("SS_SlideDown").style.pixelLeft = this.width - downWidth - this.borderWidth - 10;
var startTop = top + height;
var floderTop = document.getElementById("SS_Folder" + this.currentFolder).style.pixelTop;
var floderHeight = document.getElementById("SS_Folder" + this.currentFolder).style.pixelHeight;
}
if (floderTop < startTop)
document.getElementById("SS_SlideDown").style.visibility = "visible";
else
document.getElementById("SS_SlideDown").style.visibility = "hidden";
if (floderHeight - (startTop - floderTop) > this.visibleAreaHeight)
document.getElementById("SS_SlideUp").style.visibility = "visible";
else
document.getElementById("SS_SlideUp").style.visibility = "hidden";
}
function HideArrows()
{
document.getElementById("SS_SlideUp").style.visibility = "hidden";
document.getElementById("SS_SlideDown").style.visibility = "hidden";
}
function SlideItems(up)
{
this.sliding = true;
this.slideCount = Math.floor(this.slideArrowValue / this.ArrowSlideSpeed);
up ? this.SlideItemsAction(-this.ArrowSlideSpeed) : this.SlideItemsAction(this.ArrowSlideSpeed);
}
function SlideItemsAction(value)
{
if (navigator.appName == "Netscape") {
var top = parseInt(document.getElementById("SS_Folder" + this.currentFolder).style.top);
document.getElementById("SS_Folder" + this.currentFolder).style.top = top + value;
} else {
var top = document.getElementById("SS_Folder" + this.currentFolder).style.pixelTop;
document.getElementById("SS_Folder" + this.currentFolder).style.pixelTop = top + value;
}
//filter = /rect\((\d*)px (\d*)px (\d*)px (\d*)px\)/;
var clipString = document.getElementById("SS_Folder" + this.currentFolder).style.clip;
var clip = clipString.match(this.filter);
this.ClipFolder(this.currentFolder, (parseInt(clip[1]) - value), parseInt(clip[2]), (parseInt(clip[3]) - value), parseInt(clip[4]));
this.slideCount--;
if (this.slideCount > 0)
setTimeout("Smenu.SlideItemsAction(" + value + ")", 20);
else
{
if (Math.abs(value) * this.ArrowSlideSpeed != this.slideArrowValue)
{
document.getElementById("SS_Folder" + this.currentFolder).style.pixelTop += (value / Math.abs(value) * (this.slideArrowValue % this.ArrowSlideSpeed));
//filter = /rect\((\d*)px (\d*)px (\d*)px (\d*)px\)/;
var clipString = document.getElementById("SS_Folder" + this.currentFolder).style.clip;
var clip = clipString.match(this.filter);
this.ClipFolder(this.currentFolder, (parseInt(clip[1]) - (value / Math.abs(value) * (this.slideArrowValue % this.ArrowSlideSpeed))), parseInt(clip[2]), (parseInt(clip[3]) - (value / Math.abs(value) * (this.slideArrowValue % this.ArrowSlideSpeed))), parseInt(clip[4]));
}
this.SetArrows();
this.sliding = false;
}
}
function Onwheel()
{
if (navigator.appName == "Netscape") {
var top = parseInt(document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.top);
var height = parseInt(document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.height);
var folderTop = parseInt(document.getElementById("SS_Folder" + Smenu.currentFolder).style.top)
var folderHeight = parseInt(document.getElementById("SS_Folder" + Smenu.currentFolder).style.height)
} else {
var top = document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.pixelTop;
var height = document.getElementById("SS_MenuBar" + Smenu.currentFolder).style.pixelHeight;
var folderTop = document.getElementById("SS_Folder" + Smenu.currentFolder).style.pixelTop;
var folderHeight = document.getElementById("SS_Folder" + Smenu.currentFolder).style.pixelHeight;
}
var startTop = top + height;
if (event.wheelDelta >= 120 && folderTop < startTop)
{
Smenu.ArrowSelected(SS_SlideDown);
}
else if (event.wheelDelta <= -120 && folderHeight - (startTop - folderTop) > Smenu.visibleAreaHeight)
{
Smenu.ArrowSelected(SS_SlideUp);
}
} | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.