code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
// Copyright 2011 The Closure Library Authors. 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 PseudoRandom provides a mechanism for generating deterministic
* psuedo random numbers based on a seed. Based on the Park-Miller algorithm.
* See http://dx.doi.org/10.1145%2F63039.63042 for details.
*
*/
goog.provide('goog.testing.PseudoRandom');
goog.require('goog.Disposable');
/**
* Class for unit testing code that uses Math.random. Generates deterministic
* random numbers.
*
* @param {number=} opt_seed The seed to use.
* @param {boolean=} opt_install Whether to install the PseudoRandom at
* construction time.
* @extends {goog.Disposable}
* @constructor
*/
goog.testing.PseudoRandom = function(opt_seed, opt_install) {
goog.Disposable.call(this);
if (!goog.isDef(opt_seed)) {
opt_seed = goog.testing.PseudoRandom.seedUniquifier_++ + goog.now();
}
this.seed(opt_seed);
if (opt_install) {
this.install();
}
};
goog.inherits(goog.testing.PseudoRandom, goog.Disposable);
/**
* Helps create a unique seed.
* @type {number}
* @private
*/
goog.testing.PseudoRandom.seedUniquifier_ = 0;
/**
* Constant used as part of the algorithm.
* @type {number}
*/
goog.testing.PseudoRandom.A = 48271;
/**
* Constant used as part of the algorithm. 2^31 - 1.
* @type {number}
*/
goog.testing.PseudoRandom.M = 2147483647;
/**
* Constant used as part of the algorithm. It is equal to M / A.
* @type {number}
*/
goog.testing.PseudoRandom.Q = 44488;
/**
* Constant used as part of the algorithm. It is equal to M % A.
* @type {number}
*/
goog.testing.PseudoRandom.R = 3399;
/**
* Constant used as part of the algorithm to get values from range [0, 1).
* @type {number}
*/
goog.testing.PseudoRandom.ONE_OVER_M_MINUS_ONE =
1.0 / (goog.testing.PseudoRandom.M - 1);
/**
* The seed of the random sequence and also the next returned value (before
* normalization). Must be between 1 and M - 1 (inclusive).
* @type {number}
* @private
*/
goog.testing.PseudoRandom.prototype.seed_ = 1;
/**
* Whether this PseudoRandom has been installed.
* @type {boolean}
* @private
*/
goog.testing.PseudoRandom.prototype.installed_;
/**
* The original Math.random function.
* @type {function(): number}
* @private
*/
goog.testing.PseudoRandom.prototype.mathRandom_;
/**
* Installs this PseudoRandom as the system number generator.
*/
goog.testing.PseudoRandom.prototype.install = function() {
if (!this.installed_) {
this.mathRandom_ = Math.random;
Math.random = goog.bind(this.random, this);
this.installed_ = true;
}
};
/** @override */
goog.testing.PseudoRandom.prototype.disposeInternal = function() {
goog.testing.PseudoRandom.superClass_.disposeInternal.call(this);
this.uninstall();
};
/**
* Uninstalls the PseudoRandom.
*/
goog.testing.PseudoRandom.prototype.uninstall = function() {
if (this.installed_) {
Math.random = this.mathRandom_;
this.installed_ = false;
}
};
/**
* Seed the generator.
*
* @param {number=} seed The seed to use.
*/
goog.testing.PseudoRandom.prototype.seed = function(seed) {
this.seed_ = seed % (goog.testing.PseudoRandom.M - 1);
if (this.seed_ <= 0) {
this.seed_ += goog.testing.PseudoRandom.M - 1;
}
};
/**
* @return {number} The next number in the sequence.
*/
goog.testing.PseudoRandom.prototype.random = function() {
var hi = Math.floor(this.seed_ / goog.testing.PseudoRandom.Q);
var lo = this.seed_ % goog.testing.PseudoRandom.Q;
var test = goog.testing.PseudoRandom.A * lo -
goog.testing.PseudoRandom.R * hi;
if (test > 0) {
this.seed_ = test;
} else {
this.seed_ = test + goog.testing.PseudoRandom.M;
}
return (this.seed_ - 1) * goog.testing.PseudoRandom.ONE_OVER_M_MINUS_ONE;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 Utility for sharding tests.
*
* Usage instructions:
* <ol>
* <li>Instead of writing your large test in foo_test.html, write it in
* foo_test_template.html</li>
* <li>Add a call to {@code goog.testing.ShardingTestCase.shardByFileName()}
* near the top of your test, before any test cases or setup methods.</li>
* <li>Symlink foo_test_template.html into different sharded test files
* named foo_1of4_test.html, foo_2of4_test.html, etc, using `ln -s`.</li>
* <li>Add the symlinks as foo_1of4_test.html.
* In perforce, run the command `g4 add foo_1of4_test.html` followed
* by `g4 reopen -t symlink foo_1of4_test.html` so that perforce treats the file
* as a symlink
* </li>
* </ol>
*
*/
goog.provide('goog.testing.ShardingTestCase');
goog.require('goog.asserts');
goog.require('goog.testing.TestCase');
/**
* A test case that runs tests in per-file shards.
* @param {number} shardIndex Shard index for this page,
* <strong>1-indexed</strong>.
* @param {number} numShards Number of shards to split up test cases into.
* @extends {goog.testing.TestCase}
* @constructor
*/
goog.testing.ShardingTestCase = function(shardIndex, numShards, opt_name) {
goog.base(this, opt_name);
goog.asserts.assert(shardIndex > 0, 'Shard index should be positive');
goog.asserts.assert(numShards > 0, 'Number of shards should be positive');
goog.asserts.assert(shardIndex <= numShards,
'Shard index out of bounds');
/**
* @type {number}
* @private
*/
this.shardIndex_ = shardIndex;
/**
* @type {number}
* @private
*/
this.numShards_ = numShards;
};
goog.inherits(goog.testing.ShardingTestCase, goog.testing.TestCase);
/**
* Whether we've actually partitioned the tests yet. We may execute twice
* ('Run again without reloading') without failing.
* @type {boolean}
* @private
*/
goog.testing.ShardingTestCase.prototype.sharded_ = false;
/**
* Installs a runTests global function that goog.testing.JsUnit will use to
* run tests, which will run a single shard of the tests present on the page.
* @override
*/
goog.testing.ShardingTestCase.prototype.runTests = function() {
if (!this.sharded_) {
var numTests = this.getCount();
goog.asserts.assert(numTests >= this.numShards_,
'Must have at least as many tests as shards!');
var shardSize = Math.ceil(numTests / this.numShards_);
var startIndex = (this.shardIndex_ - 1) * shardSize;
var endIndex = startIndex + shardSize;
goog.asserts.assert(this.order == goog.testing.TestCase.Order.SORTED,
'Only SORTED order is allowed for sharded tests');
this.setTests(this.getTests().slice(startIndex, endIndex));
this.sharded_ = true;
}
// Call original runTests method to execute the tests.
goog.base(this, 'runTests');
};
/**
* Shards tests based on the test filename. Assumes that the filename is
* formatted like 'foo_1of5_test.html'.
* @param {string=} opt_name A descriptive name for the test case.
*/
goog.testing.ShardingTestCase.shardByFileName = function(opt_name) {
var path = window.location.pathname;
var shardMatch = path.match(/_(\d+)of(\d+)_test\.html/);
goog.asserts.assert(shardMatch,
'Filename must be of the form "foo_1of5_test.html"');
var shardIndex = parseInt(shardMatch[1], 10);
var numShards = parseInt(shardMatch[2], 10);
var testCase = new goog.testing.ShardingTestCase(
shardIndex, numShards, opt_name);
goog.testing.TestCase.initializeTestRunner(testCase);
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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.
// All Rights Reserved
/**
* @fileoverview A driver for testing renderers.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.testing.ui.RendererHarness');
goog.require('goog.Disposable');
goog.require('goog.dom.NodeType');
goog.require('goog.testing.asserts');
goog.require('goog.testing.dom');
/**
* A driver for testing renderers.
*
* @param {goog.ui.ControlRenderer} renderer A renderer to test.
* @param {Element} renderParent The parent of the element where controls will
* be rendered.
* @param {Element} decorateParent The parent of the element where controls will
* be decorated.
* @constructor
* @extends {goog.Disposable}
*/
goog.testing.ui.RendererHarness = function(renderer, renderParent,
decorateParent) {
goog.Disposable.call(this);
/**
* The renderer under test.
* @type {goog.ui.ControlRenderer}
* @private
*/
this.renderer_ = renderer;
/**
* The parent of the element where controls will be rendered.
* @type {Element}
* @private
*/
this.renderParent_ = renderParent;
/**
* The original HTML of the render element.
* @type {string}
* @private
*/
this.renderHtml_ = renderParent.innerHTML;
/**
* Teh parent of the element where controls will be decorated.
* @type {Element}
* @private
*/
this.decorateParent_ = decorateParent;
/**
* The original HTML of the decorated element.
* @type {string}
* @private
*/
this.decorateHtml_ = decorateParent.innerHTML;
};
goog.inherits(goog.testing.ui.RendererHarness, goog.Disposable);
/**
* A control to create by decoration.
* @type {goog.ui.Control}
* @private
*/
goog.testing.ui.RendererHarness.prototype.decorateControl_;
/**
* A control to create by rendering.
* @type {goog.ui.Control}
* @private
*/
goog.testing.ui.RendererHarness.prototype.renderControl_;
/**
* Whether all the necessary assert methods have been called.
* @type {boolean}
* @private
*/
goog.testing.ui.RendererHarness.prototype.verified_ = false;
/**
* Attach a control and render its DOM.
* @param {goog.ui.Control} control A control.
* @return {Element} The element created.
*/
goog.testing.ui.RendererHarness.prototype.attachControlAndRender =
function(control) {
this.renderControl_ = control;
control.setRenderer(this.renderer_);
control.render(this.renderParent_);
return control.getElement();
};
/**
* Attach a control and decorate the element given in the constructor.
* @param {goog.ui.Control} control A control.
* @return {Element} The element created.
*/
goog.testing.ui.RendererHarness.prototype.attachControlAndDecorate =
function(control) {
this.decorateControl_ = control;
control.setRenderer(this.renderer_);
var child = this.decorateParent_.firstChild;
assertEquals('The decorated node must be an element',
goog.dom.NodeType.ELEMENT, child.nodeType);
control.decorate(/** @type {Element} */ (child));
return control.getElement();
};
/**
* Assert that the rendered element and the decorated element match.
*/
goog.testing.ui.RendererHarness.prototype.assertDomMatches = function() {
assert('Both elements were not generated',
!!(this.renderControl_ && this.decorateControl_));
goog.testing.dom.assertHtmlMatches(
this.renderControl_.getElement().innerHTML,
this.decorateControl_.getElement().innerHTML);
this.verified_ = true;
};
/**
* Destroy the harness, verifying that all assertions had been checked.
* @override
* @protected
*/
goog.testing.ui.RendererHarness.prototype.disposeInternal = function() {
// If the harness was not verified appropriately, throw an exception.
assert('Expected assertDomMatches to be called',
this.verified_ || !this.renderControl_ || !this.decorateControl_);
if (this.decorateControl_) {
this.decorateControl_.dispose();
}
if (this.renderControl_) {
this.renderControl_.dispose();
}
this.renderParent_.innerHTML = this.renderHtml_;
this.decorateParent_.innerHTML = this.decorateHtml_;
goog.testing.ui.RendererHarness.superClass_.disposeInternal.call(this);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Tools for testing Closure renderers against static markup
* spec pages.
*
*/
goog.provide('goog.testing.ui.style');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.testing.asserts');
/**
* Uses document.write to add an iFrame to the page with the reference path in
* the src attribute. Used for loading an html file containing reference
* structures to test against into the page. Should be called within the body of
* the jsunit test page.
* @param {string} referencePath A path to a reference HTML file.
*/
goog.testing.ui.style.writeReferenceFrame = function(referencePath) {
document.write('<iframe id="reference" name="reference" ' +
'src="' + referencePath + '"></iframe>');
};
/**
* Returns a reference to the first element child of a node with the given id
* from the page loaded into the reference iFrame. Used to retrieve a particular
* reference DOM structure to test against.
* @param {string} referenceId The id of a container element for a reference
* structure in the reference page.
* @return {Node} The root element of the reference structure.
*/
goog.testing.ui.style.getReferenceNode = function(referenceId) {
return goog.dom.getFirstElementChild(
window.frames['reference'].document.getElementById(referenceId));
};
/**
* Returns an array of all element children of a given node.
* @param {Node} element The node to get element children of.
* @return {Array.<Node>} An array of all the element children.
*/
goog.testing.ui.style.getElementChildren = function(element) {
var first = goog.dom.getFirstElementChild(element);
if (!first) {
return [];
}
var children = [first], next;
while (next = goog.dom.getNextElementSibling(children[children.length - 1])) {
children.push(next);
}
return children;
};
/**
* Tests whether a given node is a "content" node of a reference structure,
* which means it is allowed to have arbitrary children.
* @param {Node} element The node to test.
* @return {boolean} Whether the given node is a content node or not.
*/
goog.testing.ui.style.isContentNode = function(element) {
return element.className.indexOf('content') != -1;
};
/**
* Tests that the structure, node names, and classes of the given element are
* the same as the reference structure with the given id. Throws an error if the
* element doesn't have the same nodes at each level of the DOM with the same
* classes on each. The test ignores all DOM structure within content nodes.
* @param {Node} element The root node of the DOM structure to test.
* @param {string} referenceId The id of the container for the reference
* structure to test against.
*/
goog.testing.ui.style.assertStructureMatchesReference = function(element,
referenceId) {
goog.testing.ui.style.assertStructureMatchesReferenceInner_(element,
goog.testing.ui.style.getReferenceNode(referenceId));
};
/**
* A recursive function for comparing structure, node names, and classes between
* a test and reference DOM structure. Throws an error if one of these things
* doesn't match. Used internally by
* {@link goog.testing.ui.style.assertStructureMatchesReference}.
* @param {Node} element DOM element to test.
* @param {Node} reference DOM element to use as a reference (test against).
* @private
*/
goog.testing.ui.style.assertStructureMatchesReferenceInner_ = function(element,
reference) {
if (!element && !reference) {
return;
}
assertTrue('Expected two elements.', !!element && !!reference);
assertEquals('Expected nodes to have the same nodeName.',
element.nodeName, reference.nodeName);
var elementClasses = goog.dom.classes.get(element);
goog.array.forEach(goog.dom.classes.get(reference), function(referenceClass) {
assertContains('Expected test node to have all reference classes.',
referenceClass, elementClasses);
});
// Call assertStructureMatchesReferenceInner_ on all element children
// unless this is a content node
var elChildren = goog.testing.ui.style.getElementChildren(element),
refChildren = goog.testing.ui.style.getElementChildren(reference);
if (!goog.testing.ui.style.isContentNode(reference)) {
if (elChildren.length != refChildren.length) {
assertEquals('Expected same number of children for a non-content node.',
elChildren.length, refChildren.length);
}
for (var i = 0; i < elChildren.length; i++) {
goog.testing.ui.style.assertStructureMatchesReferenceInner_(elChildren[i],
refChildren[i]);
}
}
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 Additional asserts for testing ControlRenderers.
*
* @author mkretzschmar@google.com (Martin Kretzschmar)
*/
goog.provide('goog.testing.ui.rendererasserts');
goog.require('goog.testing.asserts');
/**
* Assert that a control renderer constructor doesn't call getCssClass.
*
* @param {?function(new:goog.ui.ControlRenderer)} rendererClassUnderTest The
* renderer constructor to test.
*/
goog.testing.ui.rendererasserts.assertNoGetCssClassCallsInConstructor =
function(rendererClassUnderTest) {
var getCssClassCalls = 0;
/**
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
function TestControlRenderer() {
rendererClassUnderTest.call(this);
}
goog.inherits(TestControlRenderer, rendererClassUnderTest);
/** @override */
TestControlRenderer.prototype.getCssClass = function() {
getCssClassCalls++;
return TestControlRenderer.superClass_.getCssClass.call(this);
};
var testControlRenderer = new TestControlRenderer();
assertEquals('Constructors should not call getCssClass, ' +
'getCustomRenderer must be able to override it post construction.',
0, getCssClassCalls);
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 test classes for tests that can wait for conditions.
*
* Normal unit tests must complete their test logic within a single function
* execution. This is ideal for most tests, but makes it difficult to test
* routines that require real time to complete. The tests and TestCase in this
* file allow for tests that can wait until a condition is true before
* continuing execution.
*
* Each test has the typical three phases of execution: setUp, the test itself,
* and tearDown. During each phase, the test function may add wait conditions,
* which result in new test steps being added for that phase. All steps in a
* given phase must complete before moving on to the next phase. An error in
* any phase will stop that test and report the error to the test runner.
*
* This class should not be used where adequate mocks exist. Time-based routines
* should use the MockClock, which runs much faster and provides equivalent
* results. Continuation tests should be used for testing code that depends on
* browser behaviors that are difficult to mock. For example, testing code that
* relies on Iframe load events, event or layout code that requires a setTimeout
* to become valid, and other browser-dependent native object interactions for
* which mocks are insufficient.
*
* Sample usage:
*
* <pre>
* var testCase = new goog.testing.ContinuationTestCase();
* testCase.autoDiscoverTests();
*
* if (typeof G_testRunner != 'undefined') {
* G_testRunner.initialize(testCase);
* }
*
* function testWaiting() {
* var someVar = true;
* waitForTimeout(function() {
* assertTrue(someVar)
* }, 500);
* }
*
* function testWaitForEvent() {
* var et = goog.events.EventTarget();
* waitForEvent(et, 'test', function() {
* // Test step runs after the event fires.
* })
* et.dispatchEvent(et, 'test');
* }
*
* function testWaitForCondition() {
* var counter = 0;
*
* waitForCondition(function() {
* // This function is evaluated periodically until it returns true, or it
* // times out.
* return ++counter >= 3;
* }, function() {
* // This test step is run once the condition becomes true.
* assertEquals(3, counter);
* });
* }
* </pre>
*
* @author brenneman@google.com (Shawn Brenneman)
*/
goog.provide('goog.testing.ContinuationTestCase');
goog.provide('goog.testing.ContinuationTestCase.Step');
goog.provide('goog.testing.ContinuationTestCase.Test');
goog.require('goog.array');
goog.require('goog.events.EventHandler');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.TestCase.Test');
goog.require('goog.testing.asserts');
/**
* Constructs a test case that supports tests with continuations. Test functions
* may issue "wait" commands that suspend the test temporarily and continue once
* the wait condition is met.
*
* @param {string=} opt_name Optional name for the test case.
* @constructor
* @extends {goog.testing.TestCase}
*/
goog.testing.ContinuationTestCase = function(opt_name) {
goog.testing.TestCase.call(this, opt_name);
/**
* An event handler for waiting on Closure or browser events during tests.
* @type {goog.events.EventHandler}
* @private
*/
this.handler_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.testing.ContinuationTestCase, goog.testing.TestCase);
/**
* The default maximum time to wait for a single test step in milliseconds.
* @type {number}
*/
goog.testing.ContinuationTestCase.MAX_TIMEOUT = 1000;
/**
* Lock used to prevent multiple test steps from running recursively.
* @type {boolean}
* @private
*/
goog.testing.ContinuationTestCase.locked_ = false;
/**
* The current test being run.
* @type {goog.testing.ContinuationTestCase.Test}
* @private
*/
goog.testing.ContinuationTestCase.prototype.currentTest_ = null;
/**
* Enables or disables the wait functions in the global scope.
* @param {boolean} enable Whether the wait functions should be exported.
* @private
*/
goog.testing.ContinuationTestCase.prototype.enableWaitFunctions_ =
function(enable) {
if (enable) {
goog.exportSymbol('waitForCondition',
goog.bind(this.waitForCondition, this));
goog.exportSymbol('waitForEvent', goog.bind(this.waitForEvent, this));
goog.exportSymbol('waitForTimeout', goog.bind(this.waitForTimeout, this));
} else {
// Internet Explorer doesn't allow deletion of properties on the window.
goog.global['waitForCondition'] = undefined;
goog.global['waitForEvent'] = undefined;
goog.global['waitForTimeout'] = undefined;
}
};
/** @override */
goog.testing.ContinuationTestCase.prototype.runTests = function() {
this.enableWaitFunctions_(true);
goog.testing.ContinuationTestCase.superClass_.runTests.call(this);
};
/** @override */
goog.testing.ContinuationTestCase.prototype.finalize = function() {
this.enableWaitFunctions_(false);
goog.testing.ContinuationTestCase.superClass_.finalize.call(this);
};
/** @override */
goog.testing.ContinuationTestCase.prototype.cycleTests = function() {
// Get the next test in the queue.
if (!this.currentTest_) {
this.currentTest_ = this.createNextTest_();
}
// Run the next step of the current test, or exit if all tests are complete.
if (this.currentTest_) {
this.runNextStep_();
} else {
this.finalize();
}
};
/**
* Creates the next test in the queue.
* @return {goog.testing.ContinuationTestCase.Test} The next test to execute, or
* null if no pending tests remain.
* @private
*/
goog.testing.ContinuationTestCase.prototype.createNextTest_ = function() {
var test = this.next();
if (!test) {
return null;
}
var name = test.name;
goog.testing.TestCase.currentTestName = name;
this.result_.runCount++;
this.log('Running test: ' + name);
return new goog.testing.ContinuationTestCase.Test(
new goog.testing.TestCase.Test(name, this.setUp, this),
test,
new goog.testing.TestCase.Test(name, this.tearDown, this));
};
/**
* Cleans up a finished test and cycles to the next test.
* @private
*/
goog.testing.ContinuationTestCase.prototype.finishTest_ = function() {
var err = this.currentTest_.getError();
if (err) {
this.doError(this.currentTest_, err);
} else {
this.doSuccess(this.currentTest_);
}
goog.testing.TestCase.currentTestName = null;
this.currentTest_ = null;
this.locked_ = false;
this.handler_.removeAll();
this.timeout(goog.bind(this.cycleTests, this), 0);
};
/**
* Executes the next step in the current phase, advancing through each phase as
* all steps are completed.
* @private
*/
goog.testing.ContinuationTestCase.prototype.runNextStep_ = function() {
if (this.locked_) {
// Attempting to run a step before the previous step has finished. Try again
// after that step has released the lock.
return;
}
var phase = this.currentTest_.getCurrentPhase();
if (!phase || !phase.length) {
// No more steps for this test.
this.finishTest_();
return;
}
// Find the next step that is not in a wait state.
var stepIndex = goog.array.findIndex(phase, function(step) {
return !step.waiting;
});
if (stepIndex < 0) {
// All active steps are currently waiting. Return until one wakes up.
return;
}
this.locked_ = true;
var step = phase[stepIndex];
try {
step.execute();
// Remove the successfully completed step. If an error is thrown, all steps
// will be removed for this phase.
goog.array.removeAt(phase, stepIndex);
} catch (e) {
this.currentTest_.setError(e);
// An assertion has failed, or an exception was raised. Clear the current
// phase, whether it is setUp, test, or tearDown.
this.currentTest_.cancelCurrentPhase();
// Cancel the setUp and test phase no matter where the error occurred. The
// tearDown phase will still run if it has pending steps.
this.currentTest_.cancelTestPhase();
}
this.locked_ = false;
this.runNextStep_();
};
/**
* Creates a new test step that will run after a user-specified
* timeout. No guarantee is made on the execution order of the
* continuation, except for those provided by each browser's
* window.setTimeout. In particular, if two continuations are
* registered at the same time with very small delta for their
* durations, this class can not guarantee that the continuation with
* the smaller duration will be executed first.
* @param {Function} continuation The test function to invoke after the timeout.
* @param {number=} opt_duration The length of the timeout in milliseconds.
*/
goog.testing.ContinuationTestCase.prototype.waitForTimeout =
function(continuation, opt_duration) {
var step = this.addStep_(continuation);
step.setTimeout(goog.bind(this.handleComplete_, this, step),
opt_duration || 0);
};
/**
* Creates a new test step that will run after an event has fired. If the event
* does not fire within a reasonable timeout, the test will fail.
* @param {goog.events.EventTarget|EventTarget} eventTarget The target that will
* fire the event.
* @param {string} eventType The type of event to listen for.
* @param {Function} continuation The test function to invoke after the event
* fires.
*/
goog.testing.ContinuationTestCase.prototype.waitForEvent = function(
eventTarget,
eventType,
continuation) {
var step = this.addStep_(continuation);
var duration = goog.testing.ContinuationTestCase.MAX_TIMEOUT;
step.setTimeout(goog.bind(this.handleTimeout_, this, step, duration),
duration);
this.handler_.listenOnce(eventTarget,
eventType,
goog.bind(this.handleComplete_, this, step));
};
/**
* Creates a new test step which will run once a condition becomes true. The
* condition will be polled at a user-specified interval until it becomes true,
* or until a maximum timeout is reached.
* @param {Function} condition The condition to poll.
* @param {Function} continuation The test code to evaluate once the condition
* becomes true.
* @param {number=} opt_interval The polling interval in milliseconds.
* @param {number=} opt_maxTimeout The maximum amount of time to wait for the
* condition in milliseconds (defaults to 1000).
*/
goog.testing.ContinuationTestCase.prototype.waitForCondition = function(
condition,
continuation,
opt_interval,
opt_maxTimeout) {
var interval = opt_interval || 100;
var timeout = opt_maxTimeout || goog.testing.ContinuationTestCase.MAX_TIMEOUT;
var step = this.addStep_(continuation);
this.testCondition_(step, condition, goog.now(), interval, timeout);
};
/**
* Creates a new asynchronous test step which will be added to the current test
* phase.
* @param {Function} func The test function that will be executed for this step.
* @return {goog.testing.ContinuationTestCase.Step} A new test step.
* @private
*/
goog.testing.ContinuationTestCase.prototype.addStep_ = function(func) {
if (!this.currentTest_) {
throw Error('Cannot add test steps outside of a running test.');
}
var step = new goog.testing.ContinuationTestCase.Step(
this.currentTest_.name,
func,
this.currentTest_.scope);
this.currentTest_.addStep(step);
return step;
};
/**
* Handles completion of a step's wait condition. Advances the test, allowing
* the step's test method to run.
* @param {goog.testing.ContinuationTestCase.Step} step The step that has
* finished waiting.
* @private
*/
goog.testing.ContinuationTestCase.prototype.handleComplete_ = function(step) {
step.clearTimeout();
step.waiting = false;
this.runNextStep_();
};
/**
* Handles the timeout event for a step that has exceeded the maximum time. This
* causes the current test to fail.
* @param {goog.testing.ContinuationTestCase.Step} step The timed-out step.
* @param {number} duration The length of the timeout in milliseconds.
* @private
*/
goog.testing.ContinuationTestCase.prototype.handleTimeout_ =
function(step, duration) {
step.ref = function() {
fail('Continuation timed out after ' + duration + 'ms.');
};
// Since the test is failing, cancel any other pending event listeners.
this.handler_.removeAll();
this.handleComplete_(step);
};
/**
* Tests a wait condition and executes the associated test step once the
* condition is true.
*
* If the condition does not become true before the maximum duration, the
* interval will stop and the test step will fail in the kill timer.
*
* @param {goog.testing.ContinuationTestCase.Step} step The waiting test step.
* @param {Function} condition The test condition.
* @param {number} startTime Time when the test step began waiting.
* @param {number} interval The duration in milliseconds to wait between tests.
* @param {number} timeout The maximum amount of time to wait for the condition
* to become true. Measured from the startTime in milliseconds.
* @private
*/
goog.testing.ContinuationTestCase.prototype.testCondition_ = function(
step,
condition,
startTime,
interval,
timeout) {
var duration = goog.now() - startTime;
if (condition()) {
this.handleComplete_(step);
} else if (duration < timeout) {
step.setTimeout(goog.bind(this.testCondition_,
this,
step,
condition,
startTime,
interval,
timeout),
interval);
} else {
this.handleTimeout_(step, duration);
}
};
/**
* Creates a continuation test case, which consists of multiple test steps that
* occur in several phases.
*
* The steps are distributed between setUp, test, and tearDown phases. During
* the execution of each step, 0 or more steps may be added to the current
* phase. Once all steps in a phase have completed, the next phase will be
* executed.
*
* If any errors occur (such as an assertion failure), the setUp and Test phases
* will be cancelled immediately. The tearDown phase will always start, but may
* be cancelled as well if it raises an error.
*
* @param {goog.testing.TestCase.Test} setUp A setUp test method to run before
* the main test phase.
* @param {goog.testing.TestCase.Test} test A test method to run.
* @param {goog.testing.TestCase.Test} tearDown A tearDown test method to run
* after the test method completes or fails.
* @constructor
* @extends {goog.testing.TestCase.Test}
*/
goog.testing.ContinuationTestCase.Test = function(setUp, test, tearDown) {
// This test container has a name, but no evaluation function or scope.
goog.testing.TestCase.Test.call(this, test.name, null, null);
/**
* The list of test steps to run during setUp.
* @type {Array.<goog.testing.TestCase.Test>}
* @private
*/
this.setUp_ = [setUp];
/**
* The list of test steps to run for the actual test.
* @type {Array.<goog.testing.TestCase.Test>}
* @private
*/
this.test_ = [test];
/**
* The list of test steps to run during the tearDown phase.
* @type {Array.<goog.testing.TestCase.Test>}
* @private
*/
this.tearDown_ = [tearDown];
};
goog.inherits(goog.testing.ContinuationTestCase.Test,
goog.testing.TestCase.Test);
/**
* The first error encountered during the test run, if any.
* @type {Error}
* @private
*/
goog.testing.ContinuationTestCase.Test.prototype.error_ = null;
/**
* @return {Error} The first error to be raised during the test run or null if
* no errors occurred.
*/
goog.testing.ContinuationTestCase.Test.prototype.getError = function() {
return this.error_;
};
/**
* Sets an error for the test so it can be reported. Only the first error set
* during a test will be reported. Additional errors that occur in later test
* phases will be discarded.
* @param {Error} e An error.
*/
goog.testing.ContinuationTestCase.Test.prototype.setError = function(e) {
this.error_ = this.error_ || e;
};
/**
* @return {Array.<goog.testing.TestCase.Test>} The current phase of steps
* being processed. Returns null if all steps have been completed.
*/
goog.testing.ContinuationTestCase.Test.prototype.getCurrentPhase = function() {
if (this.setUp_.length) {
return this.setUp_;
}
if (this.test_.length) {
return this.test_;
}
if (this.tearDown_.length) {
return this.tearDown_;
}
return null;
};
/**
* Adds a new test step to the end of the current phase. The new step will wait
* for a condition to be met before running, or will fail after a timeout.
* @param {goog.testing.ContinuationTestCase.Step} step The test step to add.
*/
goog.testing.ContinuationTestCase.Test.prototype.addStep = function(step) {
var phase = this.getCurrentPhase();
if (phase) {
phase.push(step);
} else {
throw Error('Attempted to add a step to a completed test.');
}
};
/**
* Cancels all remaining steps in the current phase. Called after an error in
* any phase occurs.
*/
goog.testing.ContinuationTestCase.Test.prototype.cancelCurrentPhase =
function() {
this.cancelPhase_(this.getCurrentPhase());
};
/**
* Skips the rest of the setUp and test phases, but leaves the tearDown phase to
* clean up.
*/
goog.testing.ContinuationTestCase.Test.prototype.cancelTestPhase = function() {
this.cancelPhase_(this.setUp_);
this.cancelPhase_(this.test_);
};
/**
* Clears a test phase and cancels any pending steps found.
* @param {Array.<goog.testing.TestCase.Test>} phase A list of test steps.
* @private
*/
goog.testing.ContinuationTestCase.Test.prototype.cancelPhase_ =
function(phase) {
while (phase && phase.length) {
var step = phase.pop();
if (step instanceof goog.testing.ContinuationTestCase.Step) {
step.clearTimeout();
}
}
};
/**
* Constructs a single step in a larger continuation test. Each step is similar
* to a typical TestCase test, except it may wait for an event or timeout to
* occur before running the test function.
*
* @param {string} name The test name.
* @param {Function} ref The test function to run.
* @param {Object=} opt_scope The object context to run the test in.
* @constructor
* @extends {goog.testing.TestCase.Test}
*/
goog.testing.ContinuationTestCase.Step = function(name, ref, opt_scope) {
goog.testing.TestCase.Test.call(this, name, ref, opt_scope);
};
goog.inherits(goog.testing.ContinuationTestCase.Step,
goog.testing.TestCase.Test);
/**
* Whether the step is currently waiting for a condition to continue. All new
* steps begin in wait state.
* @type {boolean}
*/
goog.testing.ContinuationTestCase.Step.prototype.waiting = true;
/**
* A saved reference to window.clearTimeout so that MockClock or other overrides
* don't affect continuation timeouts.
* @type {Function}
* @private
*/
goog.testing.ContinuationTestCase.Step.protectedClearTimeout_ =
window.clearTimeout;
/**
* A saved reference to window.setTimeout so that MockClock or other overrides
* don't affect continuation timeouts.
* @type {Function}
* @private
*/
goog.testing.ContinuationTestCase.Step.protectedSetTimeout_ = window.setTimeout;
/**
* Key to this step's timeout. If the step is waiting for an event, the timeout
* will be used as a kill timer. If the step is waiting
* @type {number}
* @private
*/
goog.testing.ContinuationTestCase.Step.prototype.timeout_;
/**
* Starts a timeout for this step. Each step may have only one timeout active at
* a time.
* @param {Function} func The function to call after the timeout.
* @param {number} duration The number of milliseconds to wait before invoking
* the function.
*/
goog.testing.ContinuationTestCase.Step.prototype.setTimeout =
function(func, duration) {
this.clearTimeout();
var setTimeout = goog.testing.ContinuationTestCase.Step.protectedSetTimeout_;
this.timeout_ = setTimeout(func, duration);
};
/**
* Clears the current timeout if it is active.
*/
goog.testing.ContinuationTestCase.Step.prototype.clearTimeout = function() {
if (this.timeout_) {
var clear = goog.testing.ContinuationTestCase.Step.protectedClearTimeout_;
clear(this.timeout_);
delete this.timeout_;
}
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 module simplifies testing code which uses stateful
* singletons. {@code goog.testing.singleton.reset} resets all instances, so
* next time when {@code getInstance} is called, a new instance is created.
* It's recommended to reset the singletons in {@code tearDown} to prevent
* interference between subsequent tests.
*
* The {@code goog.testing.singleton} functions expect that the goog.DEBUG flag
* is enabled, and the tests are either uncompiled or compiled without renaming.
*
*/
goog.provide('goog.testing.singleton');
/**
* Deletes all singleton instances, so {@code getInstance} will return a new
* instance on next call.
*/
goog.testing.singleton.reset = function() {
var singletons = goog.getObjectByName('goog.instantiatedSingletons_');
var ctor;
while (ctor = singletons.pop()) {
delete ctor.instance_;
}
};
/**
* @deprecated Please use {@code goog.addSingletonGetter}.
*/
goog.testing.singleton.addSingletonGetter = goog.addSingletonGetter;
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Mock Clock implementation for working with setTimeout,
* setInterval, clearTimeout and clearInterval within unit tests.
*
* Derived from jsUnitMockTimeout.js, contributed to JsUnit by
* Pivotal Computer Systems, www.pivotalsf.com
*
*/
goog.provide('goog.testing.MockClock');
goog.require('goog.Disposable');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.events');
goog.require('goog.testing.events.Event');
/**
* Class for unit testing code that uses setTimeout and clearTimeout.
*
* NOTE: If you are using MockClock to test code that makes use of
* goog.fx.Animation, then you must either:
*
* 1. Install and dispose of the MockClock in setUpPage() and tearDownPage()
* respectively (rather than setUp()/tearDown()).
*
* or
*
* 2. Ensure that every test clears the animation queue by calling
* mockClock.tick(x) at the end of each test function (where `x` is large
* enough to complete all animations).
*
* Otherwise, if any animation is left pending at the time that
* MockClock.dispose() is called, that will permanently prevent any future
* animations from playing on the page.
*
* @param {boolean=} opt_autoInstall Install the MockClock at construction time.
* @constructor
* @extends {goog.Disposable}
*/
goog.testing.MockClock = function(opt_autoInstall) {
goog.Disposable.call(this);
/**
* Reverse-order queue of timers to fire.
*
* The last item of the queue is popped off. Insertion happens from the
* right. For example, the expiration times for each element of the queue
* might be in the order 300, 200, 200.
*
* @type {Array.<Object>}
* @private
*/
this.queue_ = [];
/**
* Set of timeouts that should be treated as cancelled.
*
* Rather than removing cancelled timers directly from the queue, this set
* simply marks them as deleted so that they can be ignored when their
* turn comes up. The keys are the timeout keys that are cancelled, each
* mapping to true.
*
* @type {Object}
* @private
*/
this.deletedKeys_ = {};
if (opt_autoInstall) {
this.install();
}
};
goog.inherits(goog.testing.MockClock, goog.Disposable);
/**
* Default wait timeout for mocking requestAnimationFrame (in milliseconds).
*
* @type {number}
* @const
*/
goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT = 20;
/**
* Count of the number of timeouts made.
* @type {number}
* @private
*/
goog.testing.MockClock.prototype.timeoutsMade_ = 0;
/**
* PropertyReplacer instance which overwrites and resets setTimeout,
* setInterval, etc. or null if the MockClock is not installed.
* @type {goog.testing.PropertyReplacer}
* @private
*/
goog.testing.MockClock.prototype.replacer_ = null;
/**
* Map of deleted keys. These keys represents keys that were deleted in a
* clearInterval, timeoutid -> object.
* @type {Object}
* @private
*/
goog.testing.MockClock.prototype.deletedKeys_ = null;
/**
* The current simulated time in milliseconds.
* @type {number}
* @private
*/
goog.testing.MockClock.prototype.nowMillis_ = 0;
/**
* Additional delay between the time a timeout was set to fire, and the time
* it actually fires. Useful for testing workarounds for this Firefox 2 bug:
* https://bugzilla.mozilla.org/show_bug.cgi?id=291386
* May be negative.
* @type {number}
* @private
*/
goog.testing.MockClock.prototype.timeoutDelay_ = 0;
/**
* Installs the MockClock by overriding the global object's implementation of
* setTimeout, setInterval, clearTimeout and clearInterval.
*/
goog.testing.MockClock.prototype.install = function() {
if (!this.replacer_) {
var r = this.replacer_ = new goog.testing.PropertyReplacer();
r.set(goog.global, 'setTimeout', goog.bind(this.setTimeout_, this));
r.set(goog.global, 'setInterval', goog.bind(this.setInterval_, this));
r.set(goog.global, 'setImmediate', goog.bind(this.setImmediate_, this));
r.set(goog.global, 'clearTimeout', goog.bind(this.clearTimeout_, this));
r.set(goog.global, 'clearInterval', goog.bind(this.clearInterval_, this));
// Replace the requestAnimationFrame functions.
this.replaceRequestAnimationFrame_();
// PropertyReplacer#set can't be called with renameable functions.
this.oldGoogNow_ = goog.now;
goog.now = goog.bind(this.getCurrentTime, this);
}
};
/**
* Installs the mocks for requestAnimationFrame and cancelRequestAnimationFrame.
* @private
*/
goog.testing.MockClock.prototype.replaceRequestAnimationFrame_ = function() {
var r = this.replacer_;
var requestFuncs = ['requestAnimationFrame',
'webkitRequestAnimationFrame',
'mozRequestAnimationFrame',
'oRequestAnimationFrame',
'msRequestAnimationFrame'];
var cancelFuncs = ['cancelRequestAnimationFrame',
'webkitCancelRequestAnimationFrame',
'mozCancelRequestAnimationFrame',
'oCancelRequestAnimationFrame',
'msCancelRequestAnimationFrame'];
for (var i = 0; i < requestFuncs.length; ++i) {
if (goog.global && goog.global[requestFuncs[i]]) {
r.set(goog.global, requestFuncs[i],
goog.bind(this.requestAnimationFrame_, this));
}
}
for (var i = 0; i < cancelFuncs.length; ++i) {
if (goog.global && goog.global[cancelFuncs[i]]) {
r.set(goog.global, cancelFuncs[i],
goog.bind(this.cancelRequestAnimationFrame_, this));
}
}
};
/**
* Removes the MockClock's hooks into the global object's functions and revert
* to their original values.
*/
goog.testing.MockClock.prototype.uninstall = function() {
if (this.replacer_) {
this.replacer_.reset();
this.replacer_ = null;
goog.now = this.oldGoogNow_;
}
};
/** @override */
goog.testing.MockClock.prototype.disposeInternal = function() {
this.uninstall();
this.queue_ = null;
this.deletedKeys_ = null;
goog.testing.MockClock.superClass_.disposeInternal.call(this);
};
/**
* Resets the MockClock, removing all timeouts that are scheduled and resets
* the fake timer count.
*/
goog.testing.MockClock.prototype.reset = function() {
this.queue_ = [];
this.deletedKeys_ = {};
this.nowMillis_ = 0;
this.timeoutsMade_ = 0;
this.timeoutDelay_ = 0;
};
/**
* Sets the amount of time between when a timeout is scheduled to fire and when
* it actually fires.
* @param {number} delay The delay in milliseconds. May be negative.
*/
goog.testing.MockClock.prototype.setTimeoutDelay = function(delay) {
this.timeoutDelay_ = delay;
};
/**
* @return {number} delay The amount of time between when a timeout is
* scheduled to fire and when it actually fires, in milliseconds. May
* be negative.
*/
goog.testing.MockClock.prototype.getTimeoutDelay = function() {
return this.timeoutDelay_;
};
/**
* Increments the MockClock's time by a given number of milliseconds, running
* any functions that are now overdue.
* @param {number=} opt_millis Number of milliseconds to increment the counter.
* If not specified, clock ticks 1 millisecond.
* @return {number} Current mock time in milliseconds.
*/
goog.testing.MockClock.prototype.tick = function(opt_millis) {
if (typeof opt_millis != 'number') {
opt_millis = 1;
}
var endTime = this.nowMillis_ + opt_millis;
this.runFunctionsWithinRange_(endTime);
this.nowMillis_ = endTime;
return endTime;
};
/**
* @return {number} The number of timeouts that have been scheduled.
*/
goog.testing.MockClock.prototype.getTimeoutsMade = function() {
return this.timeoutsMade_;
};
/**
* @return {number} The MockClock's current time in milliseconds.
*/
goog.testing.MockClock.prototype.getCurrentTime = function() {
return this.nowMillis_;
};
/**
* @param {number} timeoutKey The timeout key.
* @return {boolean} Whether the timer has been set and not cleared,
* independent of the timeout's expiration. In other words, the timeout
* could have passed or could be scheduled for the future. Either way,
* this function returns true or false depending only on whether the
* provided timeoutKey represents a timeout that has been set and not
* cleared.
*/
goog.testing.MockClock.prototype.isTimeoutSet = function(timeoutKey) {
return timeoutKey <= this.timeoutsMade_ && !this.deletedKeys_[timeoutKey];
};
/**
* Runs any function that is scheduled before a certain time. Timeouts can
* be made to fire early or late if timeoutDelay_ is non-0.
* @param {number} endTime The latest time in the range, in milliseconds.
* @private
*/
goog.testing.MockClock.prototype.runFunctionsWithinRange_ = function(
endTime) {
var adjustedEndTime = endTime - this.timeoutDelay_;
// Repeatedly pop off the last item since the queue is always sorted.
while (this.queue_.length &&
this.queue_[this.queue_.length - 1].runAtMillis <= adjustedEndTime) {
var timeout = this.queue_.pop();
if (!(timeout.timeoutKey in this.deletedKeys_)) {
// Only move time forwards.
this.nowMillis_ = Math.max(this.nowMillis_,
timeout.runAtMillis + this.timeoutDelay_);
// Call timeout in global scope and pass the timeout key as the argument.
timeout.funcToCall.call(goog.global, timeout.timeoutKey);
// In case the interval was cleared in the funcToCall
if (timeout.recurring) {
this.scheduleFunction_(
timeout.timeoutKey, timeout.funcToCall, timeout.millis, true);
}
}
}
};
/**
* Schedules a function to be run at a certain time.
* @param {number} timeoutKey The timeout key.
* @param {Function} funcToCall The function to call.
* @param {number} millis The number of milliseconds to call it in.
* @param {boolean} recurring Whether to function call should recur.
* @private
*/
goog.testing.MockClock.prototype.scheduleFunction_ = function(
timeoutKey, funcToCall, millis, recurring) {
var timeout = {
runAtMillis: this.nowMillis_ + millis,
funcToCall: funcToCall,
recurring: recurring,
timeoutKey: timeoutKey,
millis: millis
};
goog.testing.MockClock.insert_(timeout, this.queue_);
};
/**
* Inserts a timer descriptor into a descending-order queue.
*
* Later-inserted duplicates appear at lower indices. For example, the
* asterisk in (5,4,*,3,2,1) would be the insertion point for 3.
*
* @param {Object} timeout The timeout to insert, with numerical runAtMillis
* property.
* @param {Array.<Object>} queue The queue to insert into, with each element
* having a numerical runAtMillis property.
* @private
*/
goog.testing.MockClock.insert_ = function(timeout, queue) {
// Although insertion of N items is quadratic, requiring goog.structs.Heap
// from a unit test will make tests more prone to breakage. Since unit
// tests are normally small, scalability is not a primary issue.
// Find an insertion point. Since the queue is in reverse order (so we
// can pop rather than unshift), and later timers with the same time stamp
// should be executed later, we look for the element strictly greater than
// the one we are inserting.
for (var i = queue.length; i != 0; i--) {
if (queue[i - 1].runAtMillis > timeout.runAtMillis) {
break;
}
queue[i] = queue[i - 1];
}
queue[i] = timeout;
};
/**
* Maximum 32-bit signed integer.
*
* Timeouts over this time return immediately in many browsers, due to integer
* overflow. Such known browsers include Firefox, Chrome, and Safari, but not
* IE.
*
* @type {number}
* @private
*/
goog.testing.MockClock.MAX_INT_ = 2147483647;
/**
* Schedules a function to be called after {@code millis} milliseconds.
* Mock implementation for setTimeout.
* @param {Function} funcToCall The function to call.
* @param {number} millis The number of milliseconds to call it after.
* @return {number} The number of timeouts created.
* @private
*/
goog.testing.MockClock.prototype.setTimeout_ = function(funcToCall, millis) {
if (millis > goog.testing.MockClock.MAX_INT_) {
throw Error(
'Bad timeout value: ' + millis + '. Timeouts over MAX_INT ' +
'(24.8 days) cause timeouts to be fired ' +
'immediately in most browsers, except for IE.');
}
this.timeoutsMade_ = this.timeoutsMade_ + 1;
this.scheduleFunction_(this.timeoutsMade_, funcToCall, millis, false);
return this.timeoutsMade_;
};
/**
* Schedules a function to be called every {@code millis} milliseconds.
* Mock implementation for setInterval.
* @param {Function} funcToCall The function to call.
* @param {number} millis The number of milliseconds between calls.
* @return {number} The number of timeouts created.
* @private
*/
goog.testing.MockClock.prototype.setInterval_ = function(funcToCall, millis) {
this.timeoutsMade_ = this.timeoutsMade_ + 1;
this.scheduleFunction_(this.timeoutsMade_, funcToCall, millis, true);
return this.timeoutsMade_;
};
/**
* Schedules a function to be called when an animation frame is triggered.
* Mock implementation for requestAnimationFrame.
* @param {Function} funcToCall The function to call.
* @return {number} The number of timeouts created.
* @private
*/
goog.testing.MockClock.prototype.requestAnimationFrame_ = function(funcToCall) {
return this.setTimeout_(goog.bind(function() {
if (funcToCall) {
funcToCall(this.getCurrentTime());
} else if (goog.global.mozRequestAnimationFrame) {
var event = new goog.testing.events.Event('MozBeforePaint', goog.global);
event['timeStamp'] = this.getCurrentTime();
goog.testing.events.fireBrowserEvent(event);
}
}, this), goog.testing.MockClock.REQUEST_ANIMATION_FRAME_TIMEOUT);
};
/**
* Schedules a function to be called immediately after the current JS
* execution.
* Mock implementation for setImmediate.
* @param {Function} funcToCall The function to call.
* @return {number} The number of timeouts created.
* @private
*/
goog.testing.MockClock.prototype.setImmediate_ = function(funcToCall) {
return this.setTimeout_(funcToCall, 0);
};
/**
* Clears a timeout.
* Mock implementation for clearTimeout.
* @param {number} timeoutKey The timeout key to clear.
* @private
*/
goog.testing.MockClock.prototype.clearTimeout_ = function(timeoutKey) {
// Some common libraries register static state with timers.
// This is bad. It leads to all sorts of crazy test problems where
// 1) Test A sets up a new mock clock and a static timer.
// 2) Test B sets up a new mock clock, but re-uses the static timer
// from Test A.
// 3) A timeout key from test A gets cleared, breaking a timeout in
// Test B.
//
// For now, we just hackily fail silently if someone tries to clear a timeout
// key before we've allocated it.
// Ideally, we should throw an exception if we see this happening.
//
// TODO(user): We might also try allocating timeout ids from a global
// pool rather than a local pool.
if (this.isTimeoutSet(timeoutKey)) {
this.deletedKeys_[timeoutKey] = true;
}
};
/**
* Clears an interval.
* Mock implementation for clearInterval.
* @param {number} timeoutKey The interval key to clear.
* @private
*/
goog.testing.MockClock.prototype.clearInterval_ = function(timeoutKey) {
this.clearTimeout_(timeoutKey);
};
/**
* Clears a requestAnimationFrame.
* Mock implementation for cancelRequestAnimationFrame.
* @param {number} timeoutKey The requestAnimationFrame key to clear.
* @private
*/
goog.testing.MockClock.prototype.cancelRequestAnimationFrame_ =
function(timeoutKey) {
this.clearTimeout_(timeoutKey);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Utilities for working with JsUnit. Writes out the JsUnit file
* that needs to be included in every unit test.
*
* Testing code should not have dependencies outside of goog.testing so as to
* reduce the chance of masking missing dependencies.
*
*/
goog.provide('goog.testing.jsunit');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.TestRunner');
/**
* Base path for JsUnit app files, relative to Closure's base path.
* @type {string}
*/
goog.testing.jsunit.BASE_PATH =
'../../third_party/java/jsunit/core/app/';
/**
* Filename for the core JS Unit script.
* @type {string}
*/
goog.testing.jsunit.CORE_SCRIPT =
goog.testing.jsunit.BASE_PATH + 'jsUnitCore.js';
/**
* @define {boolean} If this code is being parsed by JsTestC, we let it disable
* the onload handler to avoid running the test in JsTestC.
*/
goog.testing.jsunit.AUTO_RUN_ONLOAD = true;
(function() {
// Increases the maximum number of stack frames in Google Chrome from the
// default 10 to 50 to get more useful stack traces.
Error.stackTraceLimit = 50;
// Store a reference to the window's timeout so that it can't be overridden
// by tests.
/** @type {!Function} */
var realTimeout = window.setTimeout;
// Check for JsUnit's test runner (need to check for >2.2 and <=2.2)
if (top['JsUnitTestManager'] || top['jsUnitTestManager']) {
// Running inside JsUnit so add support code.
var path = goog.basePath + goog.testing.jsunit.CORE_SCRIPT;
document.write('<script type="text/javascript" src="' +
path + '"></' + 'script>');
} else {
// Create a test runner.
var tr = new goog.testing.TestRunner();
// Export it so that it can be queried by Selenium and tests that use a
// compiled test runner.
goog.exportSymbol('G_testRunner', tr);
goog.exportSymbol('G_testRunner.initialize', tr.initialize);
goog.exportSymbol('G_testRunner.isInitialized', tr.isInitialized);
goog.exportSymbol('G_testRunner.isFinished', tr.isFinished);
goog.exportSymbol('G_testRunner.isSuccess', tr.isSuccess);
goog.exportSymbol('G_testRunner.getReport', tr.getReport);
goog.exportSymbol('G_testRunner.getRunTime', tr.getRunTime);
goog.exportSymbol('G_testRunner.getNumFilesLoaded', tr.getNumFilesLoaded);
goog.exportSymbol('G_testRunner.setStrict', tr.setStrict);
goog.exportSymbol('G_testRunner.logTestFailure', tr.logTestFailure);
// Export debug as a global function for JSUnit compatibility. This just
// calls log on the current test case.
if (!goog.global['debug']) {
goog.exportSymbol('debug', goog.bind(tr.log, tr));
}
// If the application has defined a global error filter, set it now. This
// allows users who use a base test include to set the error filter before
// the testing code is loaded.
if (goog.global['G_errorFilter']) {
tr.setErrorFilter(goog.global['G_errorFilter']);
}
// Add an error handler to report errors that may occur during
// initialization of the page.
var onerror = window.onerror;
window.onerror = function(error, url, line) {
// Call any existing onerror handlers.
if (onerror) {
onerror(error, url, line);
}
if (typeof error == 'object') {
// Webkit started passing an event object as the only argument to
// window.onerror. It doesn't contain an error message, url or line
// number. We therefore log as much info as we can.
if (error.target && error.target.tagName == 'SCRIPT') {
tr.logError('UNKNOWN ERROR: Script ' + error.target.src);
} else {
tr.logError('UNKNOWN ERROR: No error information available.');
}
} else {
tr.logError('JS ERROR: ' + error + '\nURL: ' + url + '\nLine: ' + line);
}
};
// Create an onload handler, if the test runner hasn't been initialized then
// no test has been registered with the test runner by the test file. We
// then create a new test case and auto discover any tests in the global
// scope. If this code is being parsed by JsTestC, we let it disable the
// onload handler to avoid running the test in JsTestC.
if (goog.testing.jsunit.AUTO_RUN_ONLOAD) {
var onload = window.onload;
window.onload = function(e) {
// Call any existing onload handlers.
if (onload) {
onload(e);
}
// Wait 500ms longer so that we don't interfere with Selenium.
realTimeout(function() {
if (!tr.initialized) {
var test = new goog.testing.TestCase(document.title);
test.autoDiscoverTests();
tr.initialize(test);
}
tr.execute();
}, 500);
window.onload = null;
};
}
}
})();
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 table for showing the results of performance testing.
*
* {@see goog.testing.benchmark} for an easy way to use this functionality.
*
* @author attila@google.com (Attila Bodis)
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.testing.PerformanceTable');
goog.require('goog.dom');
goog.require('goog.testing.PerformanceTimer');
/**
* A UI widget that runs performance tests and displays the results.
* @param {Element} root The element where the table should be attached.
* @param {goog.testing.PerformanceTimer=} opt_timer A timer to use for
* executing functions and profiling them.
* @param {number=} opt_precision Number of digits of precision to include in
* results. Defaults to 0.
* @constructor
*/
goog.testing.PerformanceTable = function(root, opt_timer, opt_precision) {
/**
* Where the table should be attached.
* @type {Element}
* @private
*/
this.root_ = root;
/**
* Number of digits of precision to include in results.
* Defaults to 0.
* @type {number}
* @private
*/
this.precision_ = opt_precision || 0;
var timer = opt_timer;
if (!timer) {
timer = new goog.testing.PerformanceTimer();
timer.setNumSamples(5);
timer.setDiscardOutliers(true);
}
/**
* A timer for running the tests.
* @type {goog.testing.PerformanceTimer}
* @private
*/
this.timer_ = timer;
this.initRoot_();
};
/**
* @return {goog.testing.PerformanceTimer} The timer being used.
*/
goog.testing.PerformanceTable.prototype.getTimer = function() {
return this.timer_;
};
/**
* Render the initial table.
* @private
*/
goog.testing.PerformanceTable.prototype.initRoot_ = function() {
this.root_.innerHTML =
'<table class="test-results" cellspacing="1">' +
' <thead>' +
' <tr>' +
' <th rowspan="2">Test Description</th>' +
' <th rowspan="2">Runs</th>' +
' <th colspan="4">Results (ms)</th>' +
' </tr>' +
' <tr>' +
' <th>Average</th>' +
' <th>Std Dev</th>' +
' <th>Minimum</th>' +
' <th>Maximum</th>' +
' </tr>' +
' </thead>' +
' <tbody>' +
' </tbody>' +
'</table>';
};
/**
* @return {Element} The body of the table.
* @private
*/
goog.testing.PerformanceTable.prototype.getTableBody_ = function() {
return this.root_.getElementsByTagName(goog.dom.TagName.TBODY)[0];
};
/**
* Round to the specified precision.
* @param {number} num The number to round.
* @return {string} The rounded number, as a string.
* @private
*/
goog.testing.PerformanceTable.prototype.round_ = function(num) {
var factor = Math.pow(10, this.precision_);
return String(Math.round(num * factor) / factor);
};
/**
* Run the given function with the performance timer, and show the results.
* @param {Function} fn The function to run.
* @param {string=} opt_desc A description to associate with this run.
*/
goog.testing.PerformanceTable.prototype.run = function(fn, opt_desc) {
this.runTask(
new goog.testing.PerformanceTimer.Task(/** @type {function()} */ (fn)),
opt_desc);
};
/**
* Run the given task with the performance timer, and show the results.
* @param {goog.testing.PerformanceTimer.Task} task The performance timer task
* to run.
* @param {string=} opt_desc A description to associate with this run.
*/
goog.testing.PerformanceTable.prototype.runTask = function(task, opt_desc) {
var results = this.timer_.runTask(task);
this.recordResults(results, opt_desc);
};
/**
* Record a performance timer results object to the performance table. See
* {@code goog.testing.PerformanceTimer} for details of the format of this
* object.
* @param {Object} results The performance timer results object.
* @param {string=} opt_desc A description to associate with these results.
*/
goog.testing.PerformanceTable.prototype.recordResults = function(
results, opt_desc) {
var average = results['average'];
var standardDeviation = results['standardDeviation'];
var isSuspicious = average < 0 || standardDeviation > average * .5;
var resultsRow = goog.dom.createDom('tr', null,
goog.dom.createDom('td', 'test-description',
opt_desc || 'No description'),
goog.dom.createDom('td', 'test-count', String(results['count'])),
goog.dom.createDom('td', 'test-average', this.round_(average)),
goog.dom.createDom('td', 'test-standard-deviation',
this.round_(standardDeviation)),
goog.dom.createDom('td', 'test-minimum', String(results['minimum'])),
goog.dom.createDom('td', 'test-maximum', String(results['maximum'])));
if (isSuspicious) {
resultsRow.className = 'test-suspicious';
}
this.getTableBody_().appendChild(resultsRow);
};
/**
* Report an error in the table.
* @param {*} reason The reason for the error.
*/
goog.testing.PerformanceTable.prototype.reportError = function(reason) {
this.getTableBody_().appendChild(
goog.dom.createDom('tr', null,
goog.dom.createDom('td', {'class': 'test-error', 'colSpan': 5},
String(reason))));
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 defines a loose mock implementation.
*/
goog.provide('goog.testing.LooseExpectationCollection');
goog.provide('goog.testing.LooseMock');
goog.require('goog.array');
goog.require('goog.structs.Map');
goog.require('goog.testing.Mock');
/**
* This class is an ordered collection of expectations for one method. Since
* the loose mock does most of its verification at the time of $verify, this
* class is necessary to manage the return/throw behavior when the mock is
* being called.
* @constructor
*/
goog.testing.LooseExpectationCollection = function() {
/**
* The list of expectations. All of these should have the same name.
* @type {Array.<goog.testing.MockExpectation>}
* @private
*/
this.expectations_ = [];
};
/**
* Adds an expectation to this collection.
* @param {goog.testing.MockExpectation} expectation The expectation to add.
*/
goog.testing.LooseExpectationCollection.prototype.addExpectation =
function(expectation) {
this.expectations_.push(expectation);
};
/**
* Gets the list of expectations in this collection.
* @return {Array.<goog.testing.MockExpectation>} The array of expectations.
*/
goog.testing.LooseExpectationCollection.prototype.getExpectations = function() {
return this.expectations_;
};
/**
* This is a mock that does not care about the order of method calls. As a
* result, it won't throw exceptions until verify() is called. The only
* exception is that if a method is called that has no expectations, then an
* exception will be thrown.
* @param {Object} objectToMock The object to mock.
* @param {boolean=} opt_ignoreUnexpectedCalls Whether to ignore unexpected
* calls.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @constructor
* @extends {goog.testing.Mock}
*/
goog.testing.LooseMock = function(objectToMock, opt_ignoreUnexpectedCalls,
opt_mockStaticMethods, opt_createProxy) {
goog.testing.Mock.call(this, objectToMock, opt_mockStaticMethods,
opt_createProxy);
/**
* A map of method names to a LooseExpectationCollection for that method.
* @type {goog.structs.Map}
* @private
*/
this.$expectations_ = new goog.structs.Map();
/**
* The calls that have been made; we cache them to verify at the end. Each
* element is an array where the first element is the name, and the second
* element is the arguments.
* @type {Array.<Array.<*>>}
* @private
*/
this.$calls_ = [];
/**
* Whether to ignore unexpected calls.
* @type {boolean}
* @private
*/
this.$ignoreUnexpectedCalls_ = !!opt_ignoreUnexpectedCalls;
};
goog.inherits(goog.testing.LooseMock, goog.testing.Mock);
/**
* A setter for the ignoreUnexpectedCalls field.
* @param {boolean} ignoreUnexpectedCalls Whether to ignore unexpected calls.
* @return {goog.testing.LooseMock} This mock object.
*/
goog.testing.LooseMock.prototype.$setIgnoreUnexpectedCalls = function(
ignoreUnexpectedCalls) {
this.$ignoreUnexpectedCalls_ = ignoreUnexpectedCalls;
return this;
};
/** @override */
goog.testing.LooseMock.prototype.$recordExpectation = function() {
if (!this.$expectations_.containsKey(this.$pendingExpectation.name)) {
this.$expectations_.set(this.$pendingExpectation.name,
new goog.testing.LooseExpectationCollection());
}
var collection = this.$expectations_.get(this.$pendingExpectation.name);
collection.addExpectation(this.$pendingExpectation);
};
/** @override */
goog.testing.LooseMock.prototype.$recordCall = function(name, args) {
if (!this.$expectations_.containsKey(name)) {
if (this.$ignoreUnexpectedCalls_) {
return;
}
this.$throwCallException(name, args);
}
// Start from the beginning of the expectations for this name,
// and iterate over them until we find an expectation that matches
// and also has calls remaining.
var collection = this.$expectations_.get(name);
var matchingExpectation = null;
var expectations = collection.getExpectations();
for (var i = 0; i < expectations.length; i++) {
var expectation = expectations[i];
if (this.$verifyCall(expectation, name, args)) {
matchingExpectation = expectation;
if (expectation.actualCalls < expectation.maxCalls) {
break;
} // else continue and see if we can find something that does match
}
}
if (matchingExpectation == null) {
this.$throwCallException(name, args, expectation);
}
matchingExpectation.actualCalls++;
if (matchingExpectation.actualCalls > matchingExpectation.maxCalls) {
this.$throwException('Too many calls to ' + matchingExpectation.name +
'\nExpected: ' + matchingExpectation.maxCalls + ' but was: ' +
matchingExpectation.actualCalls);
}
this.$calls_.push([name, args]);
return this.$do(matchingExpectation, args);
};
/** @override */
goog.testing.LooseMock.prototype.$reset = function() {
goog.testing.LooseMock.superClass_.$reset.call(this);
this.$expectations_ = new goog.structs.Map();
this.$calls_ = [];
};
/** @override */
goog.testing.LooseMock.prototype.$replay = function() {
goog.testing.LooseMock.superClass_.$replay.call(this);
// Verify that there are no expectations that can never be reached.
// This can't catch every situation, but it is a decent sanity check
// and it's similar to the behavior of EasyMock in java.
var collections = this.$expectations_.getValues();
for (var i = 0; i < collections.length; i++) {
var expectations = collections[i].getExpectations();
for (var j = 0; j < expectations.length; j++) {
var expectation = expectations[j];
// If this expectation can be called infinite times, then
// check if any subsequent expectation has the exact same
// argument list.
if (!isFinite(expectation.maxCalls)) {
for (var k = j + 1; k < expectations.length; k++) {
var laterExpectation = expectations[k];
if (laterExpectation.minCalls > 0 &&
goog.array.equals(expectation.argumentList,
laterExpectation.argumentList)) {
var name = expectation.name;
var argsString = this.$argumentsAsString(expectation.argumentList);
this.$throwException([
'Expected call to ', name, ' with arguments ', argsString,
' has an infinite max number of calls; can\'t expect an',
' identical call later with a positive min number of calls'
].join(''));
}
}
}
}
}
};
/** @override */
goog.testing.LooseMock.prototype.$verify = function() {
goog.testing.LooseMock.superClass_.$verify.call(this);
var collections = this.$expectations_.getValues();
for (var i = 0; i < collections.length; i++) {
var expectations = collections[i].getExpectations();
for (var j = 0; j < expectations.length; j++) {
var expectation = expectations[j];
if (expectation.actualCalls > expectation.maxCalls) {
this.$throwException('Too many calls to ' + expectation.name +
'\nExpected: ' + expectation.maxCalls + ' but was: ' +
expectation.actualCalls);
} else if (expectation.actualCalls < expectation.minCalls) {
this.$throwException('Not enough calls to ' + expectation.name +
'\nExpected: ' + expectation.minCalls + ' but was: ' +
expectation.actualCalls);
}
}
}
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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.
goog.provide('goog.testing.JsUnitException');
goog.provide('goog.testing.asserts');
goog.require('goog.testing.stacktrace');
// TODO(user): Copied from JsUnit with some small modifications, we should
// reimplement the asserters.
/**
* @typedef {Array|NodeList|Arguments|{length: number}}
*/
goog.testing.asserts.ArrayLike;
var DOUBLE_EQUALITY_PREDICATE = function(var1, var2) {
return var1 == var2;
};
var JSUNIT_UNDEFINED_VALUE;
var TO_STRING_EQUALITY_PREDICATE = function(var1, var2) {
return var1.toString() === var2.toString();
};
var PRIMITIVE_EQUALITY_PREDICATES = {
'String': DOUBLE_EQUALITY_PREDICATE,
'Number': DOUBLE_EQUALITY_PREDICATE,
'Boolean': DOUBLE_EQUALITY_PREDICATE,
'Date': function(date1, date2) {
return date1.getTime() == date2.getTime();
},
'RegExp': TO_STRING_EQUALITY_PREDICATE,
'Function': TO_STRING_EQUALITY_PREDICATE
};
/**
* Compares equality of two numbers, allowing them to differ up to a given
* tolerance.
* @param {number} var1 A number.
* @param {number} var2 A number.
* @param {number} tolerance the maximum allowed difference.
* @return {boolean} Whether the two variables are sufficiently close.
* @private
*/
goog.testing.asserts.numberRoughEqualityPredicate_ = function(
var1, var2, tolerance) {
return Math.abs(var1 - var2) <= tolerance;
};
/**
* @type {Object.<string, function(*, *, number): boolean>}
* @private
*/
goog.testing.asserts.primitiveRoughEqualityPredicates_ = {
'Number': goog.testing.asserts.numberRoughEqualityPredicate_
};
var _trueTypeOf = function(something) {
var result = typeof something;
try {
switch (result) {
case 'string':
break;
case 'boolean':
break;
case 'number':
break;
case 'object':
if (something == null) {
result = 'null';
break;
}
case 'function':
switch (something.constructor) {
case new String('').constructor:
result = 'String';
break;
case new Boolean(true).constructor:
result = 'Boolean';
break;
case new Number(0).constructor:
result = 'Number';
break;
case new Array().constructor:
result = 'Array';
break;
case new RegExp().constructor:
result = 'RegExp';
break;
case new Date().constructor:
result = 'Date';
break;
case Function:
result = 'Function';
break;
default:
var m = something.constructor.toString().match(
/function\s*([^( ]+)\(/);
if (m) {
result = m[1];
} else {
break;
}
}
break;
}
} catch (e) {
} finally {
result = result.substr(0, 1).toUpperCase() + result.substr(1);
}
return result;
};
var _displayStringForValue = function(aVar) {
var result;
try {
result = '<' + String(aVar) + '>';
} catch (ex) {
result = '<toString failed: ' + ex.message + '>';
// toString does not work on this object :-(
}
if (!(aVar === null || aVar === JSUNIT_UNDEFINED_VALUE)) {
result += ' (' + _trueTypeOf(aVar) + ')';
}
return result;
};
var fail = function(failureMessage) {
goog.testing.asserts.raiseException('Call to fail()', failureMessage);
};
var argumentsIncludeComments = function(expectedNumberOfNonCommentArgs, args) {
return args.length == expectedNumberOfNonCommentArgs + 1;
};
var commentArg = function(expectedNumberOfNonCommentArgs, args) {
if (argumentsIncludeComments(expectedNumberOfNonCommentArgs, args)) {
return args[0];
}
return null;
};
var nonCommentArg = function(desiredNonCommentArgIndex,
expectedNumberOfNonCommentArgs, args) {
return argumentsIncludeComments(expectedNumberOfNonCommentArgs, args) ?
args[desiredNonCommentArgIndex] :
args[desiredNonCommentArgIndex - 1];
};
var _validateArguments = function(expectedNumberOfNonCommentArgs, args) {
var valid = args.length == expectedNumberOfNonCommentArgs ||
args.length == expectedNumberOfNonCommentArgs + 1 &&
goog.isString(args[0]);
_assert(null, valid, 'Incorrect arguments passed to assert function');
};
var _assert = function(comment, booleanValue, failureMessage) {
if (!booleanValue) {
goog.testing.asserts.raiseException(comment, failureMessage);
}
};
/**
* @param {*} expected The expected value.
* @param {*} actual The actual value.
* @return {string} A failure message of the values don't match.
* @private
*/
goog.testing.asserts.getDefaultErrorMsg_ = function(expected, actual) {
var msg = 'Expected ' + _displayStringForValue(expected) + ' but was ' +
_displayStringForValue(actual);
if ((typeof expected == 'string') && (typeof actual == 'string')) {
// Try to find a human-readable difference.
var limit = Math.min(expected.length, actual.length);
var commonPrefix = 0;
while (commonPrefix < limit &&
expected.charAt(commonPrefix) == actual.charAt(commonPrefix)) {
commonPrefix++;
}
var commonSuffix = 0;
while (commonSuffix < limit &&
expected.charAt(expected.length - commonSuffix - 1) ==
actual.charAt(actual.length - commonSuffix - 1)) {
commonSuffix++;
}
if (commonPrefix + commonSuffix > limit) {
commonSuffix = 0;
}
if (commonPrefix > 2 || commonSuffix > 2) {
var printString = function(str) {
var startIndex = Math.max(0, commonPrefix - 2);
var endIndex = Math.min(str.length, str.length - (commonSuffix - 2));
return (startIndex > 0 ? '...' : '') +
str.substring(startIndex, endIndex) +
(endIndex < str.length ? '...' : '');
};
msg += '\nDifference was at position ' + commonPrefix +
'. Expected [' + printString(expected) +
'] vs. actual [' + printString(actual) + ']';
}
}
return msg;
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assert = function(a, opt_b) {
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(comment, goog.isBoolean(booleanValue),
'Bad argument to assert(boolean)');
_assert(comment, booleanValue, 'Call to assert(boolean) with false');
};
/**
* Asserts that the function throws an error.
*
* @param {!(string|Function)} a The assertion comment or the function to call.
* @param {!Function=} opt_b The function to call (if the first argument of
* {@code assertThrows} was the comment).
* @return {*} The error thrown by the function.
* @throws {goog.testing.JsUnitException} If the assertion failed.
*/
var assertThrows = function(a, opt_b) {
_validateArguments(1, arguments);
var func = nonCommentArg(1, 1, arguments);
var comment = commentArg(1, arguments);
_assert(comment, typeof func == 'function',
'Argument passed to assertThrows is not a function');
try {
func();
} catch (e) {
if (e && goog.isString(e['stacktrace']) && goog.isString(e['message'])) {
// Remove the stack trace appended to the error message by Opera 10.0
var startIndex = e['message'].length - e['stacktrace'].length;
if (e['message'].indexOf(e['stacktrace'], startIndex) == startIndex) {
e['message'] = e['message'].substr(0, startIndex - 14);
}
}
return e;
}
goog.testing.asserts.raiseException(comment,
'No exception thrown from function passed to assertThrows');
};
/**
* Asserts that the function does not throw an error.
*
* @param {!(string|Function)} a The assertion comment or the function to call.
* @param {!Function=} opt_b The function to call (if the first argument of
* {@code assertNotThrows} was the comment).
* @return {*} The return value of the function.
* @throws {goog.testing.JsUnitException} If the assertion failed.
*/
var assertNotThrows = function(a, opt_b) {
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var func = nonCommentArg(1, 1, arguments);
_assert(comment, typeof func == 'function',
'Argument passed to assertNotThrows is not a function');
try {
return func();
} catch (e) {
comment = comment ? (comment + '\n') : '';
comment += 'A non expected exception was thrown from function passed to ' +
'assertNotThrows';
// Some browsers don't have a stack trace so at least have the error
// description.
var stackTrace = e['stack'] || e['stacktrace'] || e.toString();
goog.testing.asserts.raiseException(comment, stackTrace);
}
};
/**
* Asserts that the given callback function results in a JsUnitException when
* called, and that the resulting failure message matches the given expected
* message.
* @param {function() : void} callback Function to be run expected to result
* in a JsUnitException (usually contains a call to an assert).
* @param {string=} opt_expectedMessage Failure message expected to be given
* with the exception.
*/
var assertThrowsJsUnitException = function(callback, opt_expectedMessage) {
var failed = false;
try {
goog.testing.asserts.callWithoutLogging(callback);
} catch (ex) {
if (!ex.isJsUnitException) {
fail('Expected a JsUnitException');
}
if (typeof opt_expectedMessage != 'undefined' &&
ex.message != opt_expectedMessage) {
fail('Expected message [' + opt_expectedMessage + '] but got [' +
ex.message + ']');
}
failed = true;
}
if (!failed) {
fail('Expected a failure: ' + opt_expectedMessage);
}
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertTrue = function(a, opt_b) {
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(comment, goog.isBoolean(booleanValue),
'Bad argument to assertTrue(boolean)');
_assert(comment, booleanValue, 'Call to assertTrue(boolean) with false');
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertFalse = function(a, opt_b) {
_validateArguments(1, arguments);
var comment = commentArg(1, arguments);
var booleanValue = nonCommentArg(1, 1, arguments);
_assert(comment, goog.isBoolean(booleanValue),
'Bad argument to assertFalse(boolean)');
_assert(comment, !booleanValue, 'Call to assertFalse(boolean) with true');
};
/**
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
var assertEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
_assert(commentArg(2, arguments), var1 === var2,
goog.testing.asserts.getDefaultErrorMsg_(var1, var2));
};
/**
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
var assertNotEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
_assert(commentArg(2, arguments), var1 !== var2,
'Expected not to be ' + _displayStringForValue(var2));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNull = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), aVar === null,
goog.testing.asserts.getDefaultErrorMsg_(null, aVar));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNotNull = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), aVar !== null,
'Expected not to be ' + _displayStringForValue(null));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertUndefined = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), aVar === JSUNIT_UNDEFINED_VALUE,
goog.testing.asserts.getDefaultErrorMsg_(JSUNIT_UNDEFINED_VALUE, aVar));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNotUndefined = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), aVar !== JSUNIT_UNDEFINED_VALUE,
'Expected not to be ' + _displayStringForValue(JSUNIT_UNDEFINED_VALUE));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNotNullNorUndefined = function(a, opt_b) {
_validateArguments(1, arguments);
assertNotNull.apply(null, arguments);
assertNotUndefined.apply(null, arguments);
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNonEmptyString = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments),
aVar !== JSUNIT_UNDEFINED_VALUE && aVar !== null &&
typeof aVar == 'string' && aVar !== '',
'Expected non-empty string but was ' + _displayStringForValue(aVar));
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNaN = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), isNaN(aVar), 'Expected NaN');
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertNotNaN = function(a, opt_b) {
_validateArguments(1, arguments);
var aVar = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments), !isNaN(aVar), 'Expected not NaN');
};
/**
* Runs a function in an environment where test failures are not logged. This is
* useful for testing test code, where failures can be a normal part of a test.
* @param {function() : void} fn Function to run without logging failures.
*/
goog.testing.asserts.callWithoutLogging = function(fn) {
var testRunner = goog.global['G_testRunner'];
var oldLogTestFailure = testRunner['logTestFailure'];
try {
// Any failures in the callback shouldn't be recorded.
testRunner['logTestFailure'] = undefined;
fn();
} finally {
testRunner['logTestFailure'] = oldLogTestFailure;
}
};
/**
* The return value of the equality predicate passed to findDifferences below,
* in cases where the predicate can't test the input variables for equality.
* @type {?string}
*/
goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS = null;
/**
* The return value of the equality predicate passed to findDifferences below,
* in cases where the input vriables are equal.
* @type {?string}
*/
goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL = '';
/**
* Determines if two items of any type match, and formulates an error message
* if not.
* @param {*} expected Expected argument to match.
* @param {*} actual Argument as a result of performing the test.
* @param {(function(string, *, *): ?string)=} opt_equalityPredicate An optional
* function that can be used to check equality of variables. It accepts 3
* arguments: type-of-variables, var1, var2 (in that order) and returns an
* error message if the variables are not equal,
* goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL if the variables
* are equal, or
* goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS if the predicate
* couldn't check the input variables. The function will be called only if
* the types of var1 and var2 are identical.
* @return {?string} Null on success, error message on failure.
*/
goog.testing.asserts.findDifferences = function(expected, actual,
opt_equalityPredicate) {
var failures = [];
var seen1 = [];
var seen2 = [];
// To avoid infinite recursion when the two parameters are self-referential
// along the same path of properties, keep track of the object pairs already
// seen in this call subtree, and abort when a cycle is detected.
function innerAssert(var1, var2, path) {
// This is used for testing, so we can afford to be slow (but more
// accurate). So we just check whether var1 is in seen1. If we
// found var1 in index i, we simply need to check whether var2 is
// in seen2[i]. If it is, we do not recurse to check var1/var2. If
// it isn't, we know that the structures of the two objects must be
// different.
//
// This is based on the fact that values at index i in seen1 and
// seen2 will be checked for equality eventually (when
// innerAssert_(seen1[i], seen2[i], path) finishes).
for (var i = 0; i < seen1.length; ++i) {
var match1 = seen1[i] === var1;
var match2 = seen2[i] === var2;
if (match1 || match2) {
if (!match1 || !match2) {
// Asymmetric cycles, so the objects have different structure.
failures.push('Asymmetric cycle detected at ' + path);
}
return;
}
}
seen1.push(var1);
seen2.push(var2);
innerAssert_(var1, var2, path);
seen1.pop();
seen2.pop();
}
var equalityPredicate = opt_equalityPredicate || function(type, var1, var2) {
var typedPredicate = PRIMITIVE_EQUALITY_PREDICATES[type];
if (!typedPredicate) {
return goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS;
}
var equal = typedPredicate(var1, var2);
return equal ? goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL :
goog.testing.asserts.getDefaultErrorMsg_(var1, var2);
};
/**
* @param {*} var1 An item in the expected object.
* @param {*} var2 The corresponding item in the actual object.
* @param {string} path Their path in the objects.
* @suppress {missingProperties} The map_ property is unknown to the compiler
* unless goog.structs.Map is loaded.
*/
function innerAssert_(var1, var2, path) {
if (var1 === var2) {
return;
}
var typeOfVar1 = _trueTypeOf(var1);
var typeOfVar2 = _trueTypeOf(var2);
if (typeOfVar1 == typeOfVar2) {
var isArray = typeOfVar1 == 'Array';
var errorMessage = equalityPredicate(typeOfVar1, var1, var2);
if (errorMessage !=
goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS) {
if (errorMessage !=
goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL) {
failures.push(path + ': ' + errorMessage);
}
} else if (isArray && var1.length != var2.length) {
failures.push(path + ': Expected ' + var1.length + '-element array ' +
'but got a ' + var2.length + '-element array');
} else {
var childPath = path + (isArray ? '[%s]' : (path ? '.%s' : '%s'));
// if an object has an __iterator__ property, we have no way of
// actually inspecting its raw properties, and JS 1.7 doesn't
// overload [] to make it possible for someone to generically
// use what the iterator returns to compare the object-managed
// properties. This gets us into deep poo with things like
// goog.structs.Map, at least on systems that support iteration.
if (!var1['__iterator__']) {
for (var prop in var1) {
if (isArray && goog.testing.asserts.isArrayIndexProp_(prop)) {
// Skip array indices for now. We'll handle them later.
continue;
}
if (prop in var2) {
innerAssert(var1[prop], var2[prop],
childPath.replace('%s', prop));
} else {
failures.push('property ' + prop +
' not present in actual ' + (path || typeOfVar2));
}
}
// make sure there aren't properties in var2 that are missing
// from var1. if there are, then by definition they don't
// match.
for (var prop in var2) {
if (isArray && goog.testing.asserts.isArrayIndexProp_(prop)) {
// Skip array indices for now. We'll handle them later.
continue;
}
if (!(prop in var1)) {
failures.push('property ' + prop +
' not present in expected ' +
(path || typeOfVar1));
}
}
// Handle array indices by iterating from 0 to arr.length.
//
// Although all browsers allow holes in arrays, browsers
// are inconsistent in what they consider a hole. For example,
// "[0,undefined,2]" has a hole on IE but not on Firefox.
//
// Because our style guide bans for...in iteration over arrays,
// we assume that most users don't care about holes in arrays,
// and that it is ok to say that a hole is equivalent to a slot
// populated with 'undefined'.
if (isArray) {
for (prop = 0; prop < var1.length; prop++) {
innerAssert(var1[prop], var2[prop],
childPath.replace('%s', String(prop)));
}
}
} else {
// special-case for closure objects that have iterators
if (goog.isFunction(var1.equals)) {
// use the object's own equals function, assuming it accepts an
// object and returns a boolean
if (!var1.equals(var2)) {
failures.push('equals() returned false for ' +
(path || typeOfVar1));
}
} else if (var1.map_) {
// assume goog.structs.Map or goog.structs.Set, where comparing
// their private map_ field is sufficient
innerAssert(var1.map_, var2.map_, childPath.replace('%s', 'map_'));
} else {
// else die, so user knows we can't do anything
failures.push('unable to check ' + (path || typeOfVar1) +
' for equality: it has an iterator we do not ' +
'know how to handle. please add an equals method');
}
}
}
} else {
failures.push(path + ' ' +
goog.testing.asserts.getDefaultErrorMsg_(var1, var2));
}
}
innerAssert(expected, actual, '');
return failures.length == 0 ? null :
goog.testing.asserts.getDefaultErrorMsg_(expected, actual) +
'\n ' + failures.join('\n ');
};
/**
* Notes:
* Object equality has some nasty browser quirks, and this implementation is
* not 100% correct. For example,
*
* <code>
* var a = [0, 1, 2];
* var b = [0, 1, 2];
* delete a[1];
* b[1] = undefined;
* assertObjectEquals(a, b); // should fail, but currently passes
* </code>
*
* See asserts_test.html for more interesting edge cases.
*
* The first comparison object provided is the expected value, the second is
* the actual.
*
* @param {*} a Assertion message or comparison object.
* @param {*} b Comparison object.
* @param {*=} opt_c Comparison object, if an assertion message was provided.
*/
var assertObjectEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var v1 = nonCommentArg(1, 2, arguments);
var v2 = nonCommentArg(2, 2, arguments);
var failureMessage = commentArg(2, arguments) ? commentArg(2, arguments) : '';
var differences = goog.testing.asserts.findDifferences(v1, v2);
_assert(failureMessage, !differences, differences);
};
/**
* Similar to assertObjectEquals above, but accepts a tolerance margin.
*
* @param {*} a Assertion message or comparison object.
* @param {*} b Comparison object.
* @param {*} c Comparison object or tolerance.
* @param {*=} opt_d Tolerance, if an assertion message was provided.
*/
var assertObjectRoughlyEquals = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var v1 = nonCommentArg(1, 3, arguments);
var v2 = nonCommentArg(2, 3, arguments);
var tolerance = nonCommentArg(3, 3, arguments);
var failureMessage = commentArg(3, arguments) ? commentArg(3, arguments) : '';
var equalityPredicate = function(type, var1, var2) {
var typedPredicate =
goog.testing.asserts.primitiveRoughEqualityPredicates_[type];
if (!typedPredicate) {
return goog.testing.asserts.EQUALITY_PREDICATE_CANT_PROCESS;
}
var equal = typedPredicate(var1, var2, tolerance);
return equal ? goog.testing.asserts.EQUALITY_PREDICATE_VARS_ARE_EQUAL :
goog.testing.asserts.getDefaultErrorMsg_(var1, var2) +
' which was more than ' + tolerance + ' away';
};
var differences = goog.testing.asserts.findDifferences(
v1, v2, equalityPredicate);
_assert(failureMessage, !differences, differences);
};
/**
* Compares two arbitrary objects for non-equalness.
*
* All the same caveats as for assertObjectEquals apply here:
* Undefined values may be confused for missing values, or vice versa.
*
* @param {*} a Assertion message or comparison object.
* @param {*} b Comparison object.
* @param {*=} opt_c Comparison object, if an assertion message was provided.
*/
var assertObjectNotEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var v1 = nonCommentArg(1, 2, arguments);
var v2 = nonCommentArg(2, 2, arguments);
var failureMessage = commentArg(2, arguments) ? commentArg(2, arguments) : '';
var differences = goog.testing.asserts.findDifferences(v1, v2);
_assert(failureMessage, differences, 'Objects should not be equal');
};
/**
* Compares two arrays ignoring negative indexes and extra properties on the
* array objects. Use case: Internet Explorer adds the index, lastIndex and
* input enumerable fields to the result of string.match(/regexp/g), which makes
* assertObjectEquals fail.
* @param {*} a The expected array (2 args) or the debug message (3 args).
* @param {*} b The actual array (2 args) or the expected array (3 args).
* @param {*=} opt_c The actual array (3 args only).
*/
var assertArrayEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var v1 = nonCommentArg(1, 2, arguments);
var v2 = nonCommentArg(2, 2, arguments);
var failureMessage = commentArg(2, arguments) ? commentArg(2, arguments) : '';
var typeOfVar1 = _trueTypeOf(v1);
_assert(failureMessage,
typeOfVar1 == 'Array',
'Expected an array for assertArrayEquals but found a ' + typeOfVar1);
var typeOfVar2 = _trueTypeOf(v2);
_assert(failureMessage,
typeOfVar2 == 'Array',
'Expected an array for assertArrayEquals but found a ' + typeOfVar2);
assertObjectEquals(failureMessage,
Array.prototype.concat.call(v1), Array.prototype.concat.call(v2));
};
/**
* Compares two objects that can be accessed like an array and assert that
* each element is equal.
* @param {string|Object} a Failure message (3 arguments)
* or object #1 (2 arguments).
* @param {Object} b Object #1 (2 arguments) or object #2 (3 arguments).
* @param {Object=} opt_c Object #2 (3 arguments).
*/
var assertElementsEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var v1 = nonCommentArg(1, 2, arguments);
var v2 = nonCommentArg(2, 2, arguments);
var failureMessage = commentArg(2, arguments) ? commentArg(2, arguments) : '';
if (!v1) {
assert(failureMessage, !v2);
} else {
assertEquals('length mismatch: ' + failureMessage, v1.length, v2.length);
for (var i = 0; i < v1.length; ++i) {
assertEquals(
'mismatch at index ' + i + ': ' + failureMessage, v1[i], v2[i]);
}
}
};
/**
* Compares two objects that can be accessed like an array and assert that
* each element is roughly equal.
* @param {string|Object} a Failure message (4 arguments)
* or object #1 (3 arguments).
* @param {Object} b Object #1 (4 arguments) or object #2 (3 arguments).
* @param {Object|number} c Object #2 (4 arguments) or tolerance (3 arguments).
* @param {number=} opt_d tolerance (4 arguments).
*/
var assertElementsRoughlyEqual = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var v1 = nonCommentArg(1, 3, arguments);
var v2 = nonCommentArg(2, 3, arguments);
var tolerance = nonCommentArg(3, 3, arguments);
var failureMessage = commentArg(3, arguments) ? commentArg(3, arguments) : '';
if (!v1) {
assert(failureMessage, !v2);
} else {
assertEquals('length mismatch: ' + failureMessage, v1.length, v2.length);
for (var i = 0; i < v1.length; ++i) {
assertRoughlyEquals(failureMessage, v1[i], v2[i], tolerance);
}
}
};
/**
* Compares two array-like objects without taking their order into account.
* @param {string|goog.testing.asserts.ArrayLike} a Assertion message or the
* expected elements.
* @param {goog.testing.asserts.ArrayLike} b Expected elements or the actual
* elements.
* @param {goog.testing.asserts.ArrayLike=} opt_c Actual elements.
*/
var assertSameElements = function(a, b, opt_c) {
_validateArguments(2, arguments);
var expected = nonCommentArg(1, 2, arguments);
var actual = nonCommentArg(2, 2, arguments);
var message = commentArg(2, arguments);
assertTrue('Bad arguments to assertSameElements(opt_message, expected: ' +
'ArrayLike, actual: ArrayLike)',
goog.isArrayLike(expected) && goog.isArrayLike(actual));
// Clones expected and actual and converts them to real arrays.
expected = goog.testing.asserts.toArray_(expected);
actual = goog.testing.asserts.toArray_(actual);
// TODO(user): It would be great to show only the difference
// between the expected and actual elements.
_assert(message, expected.length == actual.length,
'Expected ' + expected.length + ' elements: [' + expected + '], ' +
'got ' + actual.length + ' elements: [' + actual + ']');
var toFind = goog.testing.asserts.toArray_(expected);
for (var i = 0; i < actual.length; i++) {
var index = goog.testing.asserts.indexOf_(toFind, actual[i]);
_assert(message, index != -1, 'Expected [' + expected + '], got [' +
actual + ']');
toFind.splice(index, 1);
}
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertEvaluatesToTrue = function(a, opt_b) {
_validateArguments(1, arguments);
var value = nonCommentArg(1, 1, arguments);
if (!value) {
_assert(commentArg(1, arguments), false, 'Expected to evaluate to true');
}
};
/**
* @param {*} a The value to assert (1 arg) or debug message (2 args).
* @param {*=} opt_b The value to assert (2 args only).
*/
var assertEvaluatesToFalse = function(a, opt_b) {
_validateArguments(1, arguments);
var value = nonCommentArg(1, 1, arguments);
if (value) {
_assert(commentArg(1, arguments), false, 'Expected to evaluate to false');
}
};
/**
* Compares two HTML snippets.
*
* Take extra care if attributes are involved. {@code assertHTMLEquals}'s
* implementation isn't prepared for complex cases. For example, the following
* comparisons erroneously fail:
* <pre>
* assertHTMLEquals('<a href="x" target="y">', '<a target="y" href="x">');
* assertHTMLEquals('<div classname="a b">', '<div classname="b a">');
* assertHTMLEquals('<input disabled>', '<input disabled="disabled">');
* </pre>
*
* When in doubt, use {@code goog.testing.dom.assertHtmlMatches}.
*
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
var assertHTMLEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
var var1Standardized = standardizeHTML(var1);
var var2Standardized = standardizeHTML(var2);
_assert(commentArg(2, arguments), var1Standardized === var2Standardized,
goog.testing.asserts.getDefaultErrorMsg_(
var1Standardized, var2Standardized));
};
/**
* Compares two CSS property values to make sure that they represent the same
* things. This will normalize values in the browser. For example, in Firefox,
* this assertion will consider "rgb(0, 0, 255)" and "#0000ff" to be identical
* values for the "color" property. This function won't normalize everything --
* for example, in most browsers, "blue" will not match "#0000ff". It is
* intended only to compensate for unexpected normalizations performed by
* the browser that should also affect your expected value.
* @param {string} a Assertion message, or the CSS property name.
* @param {string} b CSS property name, or the expected value.
* @param {string} c The expected value, or the actual value.
* @param {string=} opt_d The actual value.
*/
var assertCSSValueEquals = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var propertyName = nonCommentArg(1, 3, arguments);
var expectedValue = nonCommentArg(2, 3, arguments);
var actualValue = nonCommentArg(3, 3, arguments);
var expectedValueStandardized =
standardizeCSSValue(propertyName, expectedValue);
var actualValueStandardized =
standardizeCSSValue(propertyName, actualValue);
_assert(commentArg(3, arguments),
expectedValueStandardized == actualValueStandardized,
goog.testing.asserts.getDefaultErrorMsg_(
expectedValueStandardized, actualValueStandardized));
};
/**
* @param {*} a The expected value (2 args) or the debug message (3 args).
* @param {*} b The actual value (2 args) or the expected value (3 args).
* @param {*=} opt_c The actual value (3 args only).
*/
var assertHashEquals = function(a, b, opt_c) {
_validateArguments(2, arguments);
var var1 = nonCommentArg(1, 2, arguments);
var var2 = nonCommentArg(2, 2, arguments);
var message = commentArg(2, arguments);
for (var key in var1) {
_assert(message,
key in var2, 'Expected hash had key ' + key + ' that was not found');
_assert(message, var1[key] == var2[key], 'Value for key ' + key +
' mismatch - expected = ' + var1[key] + ', actual = ' + var2[key]);
}
for (var key in var2) {
_assert(message, key in var1, 'Actual hash had key ' + key +
' that was not expected');
}
};
/**
* @param {*} a The expected value (3 args) or the debug message (4 args).
* @param {*} b The actual value (3 args) or the expected value (4 args).
* @param {*} c The tolerance (3 args) or the actual value (4 args).
* @param {*=} opt_d The tolerance (4 args only).
*/
var assertRoughlyEquals = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var expected = nonCommentArg(1, 3, arguments);
var actual = nonCommentArg(2, 3, arguments);
var tolerance = nonCommentArg(3, 3, arguments);
_assert(commentArg(3, arguments),
goog.testing.asserts.numberRoughEqualityPredicate_(
expected, actual, tolerance),
'Expected ' + expected + ', but got ' + actual +
' which was more than ' + tolerance + ' away');
};
/**
* Checks if the given element is the member of the given container.
* @param {*} a Failure message (3 arguments) or the contained element
* (2 arguments).
* @param {*} b The contained element (3 arguments) or the container
* (2 arguments).
* @param {*=} opt_c The container.
*/
var assertContains = function(a, b, opt_c) {
_validateArguments(2, arguments);
var contained = nonCommentArg(1, 2, arguments);
var container = nonCommentArg(2, 2, arguments);
_assert(commentArg(2, arguments),
goog.testing.asserts.contains_(container, contained),
'Expected \'' + container + '\' to contain \'' + contained + '\'');
};
/**
* Checks if the given element is not the member of the given container.
* @param {*} a Failure message (3 arguments) or the contained element
* (2 arguments).
* @param {*} b The contained element (3 arguments) or the container
* (2 arguments).
* @param {*=} opt_c The container.
*/
var assertNotContains = function(a, b, opt_c) {
_validateArguments(2, arguments);
var contained = nonCommentArg(1, 2, arguments);
var container = nonCommentArg(2, 2, arguments);
_assert(commentArg(2, arguments),
!goog.testing.asserts.contains_(container, contained),
'Expected \'' + container + '\' not to contain \'' + contained + '\'');
};
/**
* Converts an array like object to array or clones it if it's already array.
* @param {goog.testing.asserts.ArrayLike} arrayLike The collection.
* @return {!Array} Copy of the collection as array.
* @private
*/
goog.testing.asserts.toArray_ = function(arrayLike) {
var ret = [];
for (var i = 0; i < arrayLike.length; i++) {
ret[i] = arrayLike[i];
}
return ret;
};
/**
* Finds the position of the first occurrence of an element in a container.
* @param {goog.testing.asserts.ArrayLike} container
* The array to find the element in.
* @param {*} contained Element to find.
* @return {number} Index of the first occurrence or -1 if not found.
* @private
*/
goog.testing.asserts.indexOf_ = function(container, contained) {
if (container.indexOf) {
return container.indexOf(contained);
} else {
// IE6/7 do not have indexOf so do a search.
for (var i = 0; i < container.length; i++) {
if (container[i] === contained) {
return i;
}
}
return -1;
}
};
/**
* Tells whether the array contains the given element.
* @param {goog.testing.asserts.ArrayLike} container The array to
* find the element in.
* @param {*} contained Element to find.
* @return {boolean} Whether the element is in the array.
* @private
*/
goog.testing.asserts.contains_ = function(container, contained) {
// TODO(user): Can we check for container.contains as well?
// That would give us support for most goog.structs (though weird results
// with anything else with a contains method, like goog.math.Range). Falling
// back with container.some would catch all iterables, too.
return goog.testing.asserts.indexOf_(container, contained) != -1;
};
var standardizeHTML = function(html) {
var translator = document.createElement('DIV');
translator.innerHTML = html;
// Trim whitespace from result (without relying on goog.string)
return translator.innerHTML.replace(/^\s+|\s+$/g, '');
};
/**
* Standardizes a CSS value for a given property by applying it to an element
* and then reading it back.
* @param {string} propertyName CSS property name.
* @param {string} value CSS value.
* @return {string} Normalized CSS value.
*/
var standardizeCSSValue = function(propertyName, value) {
var styleDeclaration = document.createElement('DIV').style;
styleDeclaration[propertyName] = value;
return styleDeclaration[propertyName];
};
/**
* Raises a JsUnit exception with the given comment.
* @param {string} comment A summary for the exception.
* @param {string=} opt_message A description of the exception.
*/
goog.testing.asserts.raiseException = function(comment, opt_message) {
if (goog.global['CLOSURE_INSPECTOR___'] &&
goog.global['CLOSURE_INSPECTOR___']['supportsJSUnit']) {
goog.global['CLOSURE_INSPECTOR___']['jsUnitFailure'](comment, opt_message);
}
throw new goog.testing.JsUnitException(comment, opt_message);
};
/**
* Helper function for assertObjectEquals.
* @param {string} prop A property name.
* @return {boolean} If the property name is an array index.
* @private
*/
goog.testing.asserts.isArrayIndexProp_ = function(prop) {
return (prop | 0) == prop;
};
/**
* @param {string} comment A summary for the exception.
* @param {?string=} opt_message A description of the exception.
* @constructor
* @extends {Error}
*/
goog.testing.JsUnitException = function(comment, opt_message) {
this.isJsUnitException = true;
this.message = (comment ? comment : '') +
(comment && opt_message ? '\n' : '') +
(opt_message ? opt_message : '');
this.stackTrace = goog.testing.stacktrace.get();
// These fields are for compatibility with jsUnitTestManager.
this.comment = comment || null;
this.jsUnitMessage = opt_message || '';
// Ensure there is a stack trace.
if (Error.captureStackTrace) {
Error.captureStackTrace(this, goog.testing.JsUnitException);
} else {
this.stack = new Error().stack || '';
}
};
goog.inherits(goog.testing.JsUnitException, Error);
/** @override */
goog.testing.JsUnitException.prototype.toString = function() {
return this.message;
};
goog.exportSymbol('fail', fail);
goog.exportSymbol('assert', assert);
goog.exportSymbol('assertThrows', assertThrows);
goog.exportSymbol('assertNotThrows', assertNotThrows);
goog.exportSymbol('assertTrue', assertTrue);
goog.exportSymbol('assertFalse', assertFalse);
goog.exportSymbol('assertEquals', assertEquals);
goog.exportSymbol('assertNotEquals', assertNotEquals);
goog.exportSymbol('assertNull', assertNull);
goog.exportSymbol('assertNotNull', assertNotNull);
goog.exportSymbol('assertUndefined', assertUndefined);
goog.exportSymbol('assertNotUndefined', assertNotUndefined);
goog.exportSymbol('assertNotNullNorUndefined', assertNotNullNorUndefined);
goog.exportSymbol('assertNonEmptyString', assertNonEmptyString);
goog.exportSymbol('assertNaN', assertNaN);
goog.exportSymbol('assertNotNaN', assertNotNaN);
goog.exportSymbol('assertObjectEquals', assertObjectEquals);
goog.exportSymbol('assertObjectRoughlyEquals', assertObjectRoughlyEquals);
goog.exportSymbol('assertObjectNotEquals', assertObjectNotEquals);
goog.exportSymbol('assertArrayEquals', assertArrayEquals);
goog.exportSymbol('assertElementsEquals', assertElementsEquals);
goog.exportSymbol('assertElementsRoughlyEqual', assertElementsRoughlyEqual);
goog.exportSymbol('assertSameElements', assertSameElements);
goog.exportSymbol('assertEvaluatesToTrue', assertEvaluatesToTrue);
goog.exportSymbol('assertEvaluatesToFalse', assertEvaluatesToFalse);
goog.exportSymbol('assertHTMLEquals', assertHTMLEquals);
goog.exportSymbol('assertHashEquals', assertHashEquals);
goog.exportSymbol('assertRoughlyEquals', assertRoughlyEquals);
goog.exportSymbol('assertContains', assertContains);
goog.exportSymbol('assertNotContains', assertNotContains);
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 fake PortNetwork implementation that simply produces
* MockMessageChannels for all ports.
*
*/
goog.provide('goog.testing.messaging.MockPortNetwork');
goog.require('goog.messaging.PortNetwork'); // interface
goog.require('goog.testing.messaging.MockMessageChannel');
/**
* The fake PortNetwork.
*
* @param {!goog.testing.MockControl} mockControl The mock control for creating
* the mock message channels.
* @constructor
* @implements {goog.messaging.PortNetwork}
*/
goog.testing.messaging.MockPortNetwork = function(mockControl) {
/**
* The mock control for creating mock message channels.
* @type {!goog.testing.MockControl}
* @private
*/
this.mockControl_ = mockControl;
/**
* The mock ports that have been created.
* @type {!Object.<!goog.testing.messaging.MockMessageChannel>}
* @private
*/
this.ports_ = {};
};
/**
* Get the mock port with the given name.
* @param {string} name The name of the port to get.
* @return {!goog.testing.messaging.MockMessageChannel} The mock port.
* @override
*/
goog.testing.messaging.MockPortNetwork.prototype.dial = function(name) {
if (!(name in this.ports_)) {
this.ports_[name] =
new goog.testing.messaging.MockMessageChannel(this.mockControl_);
}
return this.ports_[name];
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 simple mock class for imitating HTML5 MessageEvents.
*
*/
goog.provide('goog.testing.messaging.MockMessageEvent');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventType');
goog.require('goog.testing.events');
/**
* Creates a new fake MessageEvent.
*
* @param {*} data The data of the message.
* @param {string=} opt_origin The origin of the message, for server-sent and
* cross-document events.
* @param {string=} opt_lastEventId The last event ID, for server-sent events.
* @param {Window=} opt_source The proxy for the source window, for
* cross-document events.
* @param {Array.<MessagePort>=} opt_ports The Array of ports sent with the
* message, for cross-document and channel events.
* @extends {goog.testing.events.Event}
* @constructor
*/
goog.testing.messaging.MockMessageEvent = function(
data, opt_origin, opt_lastEventId, opt_source, opt_ports) {
goog.base(this, goog.events.EventType.MESSAGE);
/**
* The data of the message.
* @type {*}
*/
this.data = data;
/**
* The origin of the message, for server-sent and cross-document events.
* @type {?string}
*/
this.origin = opt_origin || null;
/**
* The last event ID, for server-sent events.
* @type {?string}
*/
this.lastEventId = opt_lastEventId || null;
/**
* The proxy for the source window, for cross-document events.
* @type {Window}
*/
this.source = opt_source || null;
/**
* The Array of ports sent with the message, for cross-document and channel
* events.
* @type {Array.<!MessagePort>}
*/
this.ports = opt_ports || null;
};
goog.inherits(
goog.testing.messaging.MockMessageEvent, goog.testing.events.Event);
/**
* Wraps a new fake MessageEvent in a BrowserEvent, like how a real MessageEvent
* would be wrapped.
*
* @param {*} data The data of the message.
* @param {string=} opt_origin The origin of the message, for server-sent and
* cross-document events.
* @param {string=} opt_lastEventId The last event ID, for server-sent events.
* @param {Window=} opt_source The proxy for the source window, for
* cross-document events.
* @param {Array.<MessagePort>=} opt_ports The Array of ports sent with the
* message, for cross-document and channel events.
* @return {goog.events.BrowserEvent} The wrapping event.
*/
goog.testing.messaging.MockMessageEvent.wrap = function(
data, opt_origin, opt_lastEventId, opt_source, opt_ports) {
return new goog.events.BrowserEvent(
new goog.testing.messaging.MockMessageEvent(
data, opt_origin, opt_lastEventId, opt_source, opt_ports));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 simple dummy class for representing message ports in tests.
*
*/
goog.provide('goog.testing.messaging.MockMessagePort');
goog.require('goog.events.EventTarget');
/**
* Class for unit-testing code that uses MessagePorts.
* @param {*} id An opaque identifier, used because message ports otherwise have
* no distinguishing characteristics.
* @param {goog.testing.MockControl} mockControl The mock control used to create
* the method mock for #postMessage.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.testing.messaging.MockMessagePort = function(id, mockControl) {
goog.base(this);
/**
* An opaque identifier, used because message ports otherwise have no
* distinguishing characteristics.
* @type {*}
*/
this.id = id;
/**
* Whether or not the port has been started.
* @type {boolean}
*/
this.started = false;
/**
* Whether or not the port has been closed.
* @type {boolean}
*/
this.closed = false;
mockControl.createMethodMock(this, 'postMessage');
};
goog.inherits(goog.testing.messaging.MockMessagePort, goog.events.EventTarget);
/**
* A mock postMessage funciton. Actually an instance of
* {@link goog.testing.FunctionMock}.
* @param {*} message The message to send.
* @param {Array.<MessagePort>=} opt_ports Ports to send with the message.
*/
goog.testing.messaging.MockMessagePort.prototype.postMessage = function(
message, opt_ports) {};
/**
* Starts the port.
*/
goog.testing.messaging.MockMessagePort.prototype.start = function() {
this.started = true;
};
/**
* Closes the port.
*/
goog.testing.messaging.MockMessagePort.prototype.close = function() {
this.closed = true;
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 Mock MessageChannel implementation that can receive fake
* messages and test that the right messages are sent.
*
*/
goog.provide('goog.testing.messaging.MockMessageChannel');
goog.require('goog.messaging.AbstractChannel');
goog.require('goog.testing.asserts');
/**
* Class for unit-testing code that communicates over a MessageChannel.
* @param {goog.testing.MockControl} mockControl The mock control used to create
* the method mock for #send.
* @extends {goog.messaging.AbstractChannel}
* @constructor
*/
goog.testing.messaging.MockMessageChannel = function(mockControl) {
goog.base(this);
/**
* Whether the channel has been disposed.
* @type {boolean}
*/
this.disposed = false;
mockControl.createMethodMock(this, 'send');
};
goog.inherits(goog.testing.messaging.MockMessageChannel,
goog.messaging.AbstractChannel);
/**
* A mock send function. Actually an instance of
* {@link goog.testing.FunctionMock}.
* @param {string} serviceName The name of the remote service to run.
* @param {string|!Object} payload The payload to send to the remote page.
* @override
*/
goog.testing.messaging.MockMessageChannel.prototype.send = function(
serviceName, payload) {};
/**
* Sets a flag indicating that this is disposed.
* @override
*/
goog.testing.messaging.MockMessageChannel.prototype.dispose = function() {
this.disposed = true;
};
/**
* Mocks the receipt of a message. Passes the payload the appropriate service.
* @param {string} serviceName The service to run.
* @param {string|!Object} payload The argument to pass to the service.
*/
goog.testing.messaging.MockMessageChannel.prototype.receive = function(
serviceName, payload) {
this.deliver(serviceName, payload);
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 DeferredTestCase class. By calling waitForDeferred(),
* tests in DeferredTestCase can wait for a Deferred object to complete its
* callbacks before continuing to the next test.
*
* Example Usage:
*
* var deferredTestCase = goog.testing.DeferredTestCase.createAndInstall();
* // Optionally, set a longer-than-usual step timeout.
* deferredTestCase.stepTimeout = 15 * 1000; // 15 seconds
*
* function testDeferredCallbacks() {
* var callbackTime = goog.now();
* var callbacks = new goog.async.Deferred();
* deferredTestCase.addWaitForAsync('Waiting for 1st callback', callbacks);
* callbacks.addCallback(
* function() {
* assertTrue(
* 'We\'re going back in time!', goog.now() >= callbackTime);
* callbackTime = goog.now();
* });
* deferredTestCase.addWaitForAsync('Waiting for 2nd callback', callbacks);
* callbacks.addCallback(
* function() {
* assertTrue(
* 'We\'re going back in time!', goog.now() >= callbackTime);
* callbackTime = goog.now();
* });
* deferredTestCase.addWaitForAsync('Waiting for last callback', callbacks);
* callbacks.addCallback(
* function() {
* assertTrue(
* 'We\'re going back in time!', goog.now() >= callbackTime);
* callbackTime = goog.now();
* });
*
* deferredTestCase.waitForDeferred(callbacks);
* }
*
* Note that DeferredTestCase still preserves the functionality of
* AsyncTestCase.
*
* @see.goog.async.Deferred
* @see goog.testing.AsyncTestCase
*/
goog.provide('goog.testing.DeferredTestCase');
goog.require('goog.async.Deferred');
goog.require('goog.testing.AsyncTestCase');
goog.require('goog.testing.TestCase');
/**
* A test case that can asynchronously wait on a Deferred object.
* @param {string=} opt_name A descriptive name for the test case.
* @constructor
* @extends {goog.testing.AsyncTestCase}
*/
goog.testing.DeferredTestCase = function(opt_name) {
goog.testing.AsyncTestCase.call(this, opt_name);
};
goog.inherits(goog.testing.DeferredTestCase, goog.testing.AsyncTestCase);
/**
* Preferred way of creating a DeferredTestCase. Creates one and initializes it
* with the G_testRunner.
* @param {string=} opt_name A descriptive name for the test case.
* @return {goog.testing.DeferredTestCase} The created DeferredTestCase.
*/
goog.testing.DeferredTestCase.createAndInstall = function(opt_name) {
var deferredTestCase = new goog.testing.DeferredTestCase(opt_name);
goog.testing.TestCase.initializeTestRunner(deferredTestCase);
return deferredTestCase;
};
/**
* Handler for when the test produces an error.
* @param {Error|string} err The error object.
* @protected
* @throws Always throws a ControlBreakingException.
*/
goog.testing.DeferredTestCase.prototype.onError = function(err) {
this.doAsyncError(err);
};
/**
* Handler for when the test succeeds.
* @protected
*/
goog.testing.DeferredTestCase.prototype.onSuccess = function() {
this.continueTesting();
};
/**
* Adds a callback to update the wait message of this async test case. Using
* this method generously also helps to document the test flow.
* @param {string} msg The update wait status message.
* @param {goog.async.Deferred} d The deferred object to add the waitForAsync
* callback to.
* @see goog.testing.AsyncTestCase#waitForAsync
*/
goog.testing.DeferredTestCase.prototype.addWaitForAsync = function(msg, d) {
d.addCallback(goog.bind(this.waitForAsync, this, msg));
};
/**
* Wires up given Deferred object to the test case, then starts the
* goog.async.Deferred object's callback.
* @param {!string|goog.async.Deferred} a The wait status message or the
* deferred object to wait for.
* @param {goog.async.Deferred=} opt_b The deferred object to wait for.
*/
goog.testing.DeferredTestCase.prototype.waitForDeferred = function(a, opt_b) {
var waitMsg;
var deferred;
switch (arguments.length) {
case 1:
deferred = a;
waitMsg = null;
break;
case 2:
deferred = opt_b;
waitMsg = a;
break;
default: // Shouldn't be here in compiled mode
throw Error('Invalid number of arguments');
}
deferred.addCallbacks(this.onSuccess, this.onError, this);
if (!waitMsg) {
waitMsg = 'Waiting for deferred in ' + this.getCurrentStepName();
}
this.waitForAsync( /** @type {!string} */ (waitMsg));
deferred.callback(true);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 MockRandom provides a mechanism for specifying a stream of
* numbers to expect from calls to Math.random().
*
*/
goog.provide('goog.testing.MockRandom');
goog.require('goog.Disposable');
/**
* Class for unit testing code that uses Math.random.
*
* @param {Array.<number>} sequence The sequence of numbers to return.
* @param {boolean=} opt_install Whether to install the MockRandom at
* construction time.
* @extends {goog.Disposable}
* @constructor
*/
goog.testing.MockRandom = function(sequence, opt_install) {
goog.Disposable.call(this);
/**
* The sequence of numbers to be returned by calls to random()
* @type {Array.<number>}
* @private
*/
this.sequence_ = sequence || [];
/**
* The original Math.random function.
* @type {function(): number}
* @private
*/
this.mathRandom_ = Math.random;
if (opt_install) {
this.install();
}
};
goog.inherits(goog.testing.MockRandom, goog.Disposable);
/**
* Whether this MockRandom has been installed.
* @type {boolean}
* @private
*/
goog.testing.MockRandom.prototype.installed_;
/**
* Installs this MockRandom as the system number generator.
*/
goog.testing.MockRandom.prototype.install = function() {
if (!this.installed_) {
Math.random = goog.bind(this.random, this);
this.installed_ = true;
}
};
/**
* @return {number} The next number in the sequence. If there are no more values
* left, this will return a random number.
*/
goog.testing.MockRandom.prototype.random = function() {
return this.hasMoreValues() ? this.sequence_.shift() : this.mathRandom_();
};
/**
* @return {boolean} Whether there are more numbers left in the sequence.
*/
goog.testing.MockRandom.prototype.hasMoreValues = function() {
return this.sequence_.length > 0;
};
/**
* Injects new numbers into the beginning of the sequence.
* @param {Array.<number>|number} values Number or array of numbers to inject.
*/
goog.testing.MockRandom.prototype.inject = function(values) {
if (goog.isArray(values)) {
this.sequence_ = values.concat(this.sequence_);
} else {
this.sequence_.splice(0, 0, values);
}
};
/**
* Uninstalls the MockRandom.
*/
goog.testing.MockRandom.prototype.uninstall = function() {
if (this.installed_) {
Math.random = this.mathRandom_;
this.installed_ = false;
}
};
/** @override */
goog.testing.MockRandom.prototype.disposeInternal = function() {
this.uninstall();
delete this.sequence_;
delete this.mathRandom_;
goog.testing.MockRandom.superClass_.disposeInternal.call(this);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Enable mocking of functions not attached to objects
* whether they be global / top-level or anonymous methods / closures.
*
* See the unit tests for usage.
*
*/
goog.provide('goog.testing');
goog.provide('goog.testing.FunctionMock');
goog.provide('goog.testing.GlobalFunctionMock');
goog.provide('goog.testing.MethodMock');
goog.require('goog.object');
goog.require('goog.testing.LooseMock');
goog.require('goog.testing.Mock');
goog.require('goog.testing.MockInterface');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.StrictMock');
/**
* Class used to mock a function. Useful for mocking closures and anonymous
* callbacks etc. Creates a function object that extends goog.testing.Mock.
* @param {string=} opt_functionName The optional name of the function to mock.
* Set to '[anonymous mocked function]' if not passed in.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked function.
* @suppress {missingProperties} Mocks do not fit in the type system well.
*/
goog.testing.FunctionMock = function(opt_functionName, opt_strictness) {
var fn = function() {
var args = Array.prototype.slice.call(arguments);
args.splice(0, 0, opt_functionName || '[anonymous mocked function]');
return fn.$mockMethod.apply(fn, args);
};
var base = opt_strictness === goog.testing.Mock.LOOSE ?
goog.testing.LooseMock : goog.testing.StrictMock;
goog.object.extend(fn, new base({}));
return /** @type {goog.testing.MockInterface} */ (fn);
};
/**
* Mocks an existing function. Creates a goog.testing.FunctionMock
* and registers it in the given scope with the name specified by functionName.
* @param {Object} scope The scope of the method to be mocked out.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked method.
*/
goog.testing.MethodMock = function(scope, functionName, opt_strictness) {
if (!(functionName in scope)) {
throw Error(functionName + ' is not a property of the given scope.');
}
var fn = goog.testing.FunctionMock(functionName, opt_strictness);
fn.$propertyReplacer_ = new goog.testing.PropertyReplacer();
fn.$propertyReplacer_.set(scope, functionName, fn);
fn.$tearDown = goog.testing.MethodMock.$tearDown;
return fn;
};
/**
* Resets the global function that we mocked back to its original state.
* @this {goog.testing.MockInterface}
*/
goog.testing.MethodMock.$tearDown = function() {
this.$propertyReplacer_.reset();
};
/**
* Mocks a global / top-level function. Creates a goog.testing.MethodMock
* in the global scope with the name specified by functionName.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked global function.
*/
goog.testing.GlobalFunctionMock = function(functionName, opt_strictness) {
return goog.testing.MethodMock(goog.global, functionName, opt_strictness);
};
/**
* Convenience method for creating a mock for a function.
* @param {string=} opt_functionName The optional name of the function to mock
* set to '[anonymous mocked function]' if not passed in.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked function.
*/
goog.testing.createFunctionMock = function(opt_functionName, opt_strictness) {
return goog.testing.FunctionMock(opt_functionName, opt_strictness);
};
/**
* Convenience method for creating a mock for a method.
* @param {Object} scope The scope of the method to be mocked out.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked global function.
*/
goog.testing.createMethodMock = function(scope, functionName, opt_strictness) {
return goog.testing.MethodMock(scope, functionName, opt_strictness);
};
/**
* Convenience method for creating a mock for a constructor. Copies class
* members to the mock.
*
* <p>When mocking a constructor to return a mocked instance, remember to create
* the instance mock before mocking the constructor. If you mock the constructor
* first, then the mock framework will be unable to examine the prototype chain
* when creating the mock instance.
* @param {Object} scope The scope of the constructor to be mocked out.
* @param {string} constructorName The name of the constructor we're going to
* mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked constructor.
*/
goog.testing.createConstructorMock = function(scope, constructorName,
opt_strictness) {
var realConstructor = scope[constructorName];
var constructorMock = goog.testing.MethodMock(scope, constructorName,
opt_strictness);
// Copy class members from the real constructor to the mock. Do not copy
// the closure superClass_ property (see goog.inherits), the built-in
// prototype property, or properties added to Function.prototype
// (see goog.MODIFY_FUNCTION_PROTOTYPES in closure/base.js).
for (var property in realConstructor) {
if (property != 'superClass_' &&
property != 'prototype' &&
realConstructor.hasOwnProperty(property)) {
constructorMock[property] = realConstructor[property];
}
}
return constructorMock;
};
/**
* Convenience method for creating a mocks for a global / top-level function.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked global function.
*/
goog.testing.createGlobalFunctionMock = function(functionName, opt_strictness) {
return goog.testing.GlobalFunctionMock(functionName, opt_strictness);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 MockUserAgent overrides goog.userAgent.getUserAgentString()
* depending on a specified configuration.
*
*/
goog.provide('goog.testing.MockUserAgent');
goog.require('goog.Disposable');
goog.require('goog.userAgent');
/**
* Class for unit testing code that uses goog.userAgent.
*
* @extends {goog.Disposable}
* @constructor
*/
goog.testing.MockUserAgent = function() {
goog.Disposable.call(this);
/**
* The userAgent string used by goog.userAgent.
* @type {?string}
* @private
*/
this.userAgent_ = goog.userAgent.getUserAgentString();
/**
* The original goog.userAgent.getUserAgentString function.
* @type {function():?string}
* @private
*/
this.originalUserAgentFunction_ = goog.userAgent.getUserAgentString;
/**
* The navigator object used by goog.userAgent
* @type {Object}
* @private
*/
this.navigator_ = goog.userAgent.getNavigator();
/**
* The original goog.userAgent.getNavigator function
* @type {function():Object}
* @private
*/
this.originalNavigatorFunction_ = goog.userAgent.getNavigator;
};
goog.inherits(goog.testing.MockUserAgent, goog.Disposable);
/**
* Whether this MockUserAgent has been installed.
* @type {boolean}
* @private
*/
goog.testing.MockUserAgent.prototype.installed_;
/**
* Installs this MockUserAgent.
*/
goog.testing.MockUserAgent.prototype.install = function() {
if (!this.installed_) {
goog.userAgent.getUserAgentString =
goog.bind(this.getUserAgentString, this);
goog.userAgent.getNavigator = goog.bind(this.getNavigator, this);
this.installed_ = true;
}
};
/**
* @return {?string} The userAgent set in this class.
*/
goog.testing.MockUserAgent.prototype.getUserAgentString = function() {
return this.userAgent_;
};
/**
* @param {string} userAgent The desired userAgent string to use.
*/
goog.testing.MockUserAgent.prototype.setUserAgentString = function(userAgent) {
this.userAgent_ = userAgent;
};
/**
* @return {Object} The Navigator set in this class.
*/
goog.testing.MockUserAgent.prototype.getNavigator = function() {
return this.navigator_;
};
/**
* @param {Object} navigator The desired Navigator object to use.
*/
goog.testing.MockUserAgent.prototype.setNavigator = function(navigator) {
this.navigator_ = navigator;
};
/**
* Uninstalls the MockUserAgent.
*/
goog.testing.MockUserAgent.prototype.uninstall = function() {
if (this.installed_) {
goog.userAgent.getUserAgentString = this.originalUserAgentFunction_;
goog.userAgent.getNavigator = this.originalNavigatorFunction_;
this.installed_ = false;
}
};
/** @override */
goog.testing.MockUserAgent.prototype.disposeInternal = function() {
this.uninstall();
delete this.userAgent_;
delete this.originalUserAgentFunction_;
delete this.navigator_;
delete this.originalNavigatorFunction_;
goog.testing.MockUserAgent.superClass_.disposeInternal.call(this);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 defines a strict mock implementation.
*/
goog.provide('goog.testing.StrictMock');
goog.require('goog.array');
goog.require('goog.testing.Mock');
/**
* This is a mock that verifies that methods are called in the order that they
* are specified during the recording phase. Since it verifies order, it
* follows 'fail fast' semantics. If it detects a deviation from the
* expectations, it will throw an exception and not wait for verify to be
* called.
* @param {Object} objectToMock The object to mock.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @constructor
* @extends {goog.testing.Mock}
*/
goog.testing.StrictMock = function(objectToMock, opt_mockStaticMethods,
opt_createProxy) {
goog.testing.Mock.call(this, objectToMock, opt_mockStaticMethods,
opt_createProxy);
/**
* An array of MockExpectations.
* @type {Array.<goog.testing.MockExpectation>}
* @private
*/
this.$expectations_ = [];
};
goog.inherits(goog.testing.StrictMock, goog.testing.Mock);
/** @override */
goog.testing.StrictMock.prototype.$recordExpectation = function() {
this.$expectations_.push(this.$pendingExpectation);
};
/** @override */
goog.testing.StrictMock.prototype.$recordCall = function(name, args) {
if (this.$expectations_.length == 0) {
this.$throwCallException(name, args);
}
// If the current expectation has a different name, make sure it was called
// enough and then discard it. We're through with it.
var currentExpectation = this.$expectations_[0];
while (!this.$verifyCall(currentExpectation, name, args)) {
// This might be an item which has passed its min, and we can now
// look past it, or it might be below its min and generate an error.
if (currentExpectation.actualCalls < currentExpectation.minCalls) {
this.$throwCallException(name, args, currentExpectation);
}
this.$expectations_.shift();
if (this.$expectations_.length < 1) {
// Nothing left, but this may be a failed attempt to call the previous
// item on the list, which may have been between its min and max.
this.$throwCallException(name, args, currentExpectation);
}
currentExpectation = this.$expectations_[0];
}
if (currentExpectation.maxCalls == 0) {
this.$throwCallException(name, args);
}
currentExpectation.actualCalls++;
// If we hit the max number of calls for this expectation, we're finished
// with it.
if (currentExpectation.actualCalls == currentExpectation.maxCalls) {
this.$expectations_.shift();
}
return this.$do(currentExpectation, args);
};
/** @override */
goog.testing.StrictMock.prototype.$reset = function() {
goog.testing.StrictMock.superClass_.$reset.call(this);
goog.array.clear(this.$expectations_);
};
/** @override */
goog.testing.StrictMock.prototype.$verify = function() {
goog.testing.StrictMock.superClass_.$verify.call(this);
while (this.$expectations_.length > 0) {
var expectation = this.$expectations_[0];
if (expectation.actualCalls < expectation.minCalls) {
this.$throwException('Missing a call to ' + expectation.name +
'\nExpected: ' + expectation.minCalls + ' but was: ' +
expectation.actualCalls);
} else {
// Don't need to check max, that's handled when the call is made
this.$expectations_.shift();
}
}
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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.
goog.provide('goog.testing.benchmark');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.testing.PerformanceTable');
goog.require('goog.testing.PerformanceTimer');
goog.require('goog.testing.TestCase');
/**
* Run the benchmarks.
* @private
*/
goog.testing.benchmark.run_ = function() {
// Parse the 'times' query parameter if it's set.
var times = 200;
var search = window.location.search;
var timesMatch = search.match(/(?:\?|&)times=([^?&]+)/i);
if (timesMatch) {
times = Number(timesMatch[1]);
}
var prefix = 'benchmark';
// First, get the functions.
var testSource = goog.testing.TestCase.getGlobals(prefix);
var benchmarks = {};
var names = [];
for (var name in testSource) {
try {
var ref = testSource[name];
} catch (ex) {
// NOTE(brenneman): When running tests from a file:// URL on Firefox 3.5
// for Windows, any reference to window.sessionStorage raises
// an "Operation is not supported" exception. Ignore any exceptions raised
// by simply accessing global properties.
}
if ((new RegExp('^' + prefix)).test(name) && goog.isFunction(ref)) {
benchmarks[name] = ref;
names.push(name);
}
}
document.body.appendChild(
goog.dom.createTextNode(
'Running ' + names.length + ' benchmarks ' + times + ' times each.'));
document.body.appendChild(goog.dom.createElement(goog.dom.TagName.BR));
names.sort();
// Build a table and timer.
var performanceTimer = new goog.testing.PerformanceTimer(times);
performanceTimer.setDiscardOutliers(true);
var performanceTable = new goog.testing.PerformanceTable(document.body,
performanceTimer, 2);
// Next, run the benchmarks.
for (var i = 0; i < names.length; i++) {
performanceTable.run(benchmarks[names[i]], names[i]);
}
};
/**
* Onload handler that runs the benchmarks.
* @param {Event} e The event object.
*/
window.onload = function(e) {
goog.testing.benchmark.run_();
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 MockControl holds a set of mocks for a particular test.
* It consolidates calls to $replay, $verify, and $tearDown, which simplifies
* the test and helps avoid omissions.
*
* You can create and control a mock:
* var mockFoo = mockControl.addMock(new MyMock(Foo));
*
* MockControl also exposes some convenience functions that create
* controlled mocks for common mocks: StrictMock, LooseMock,
* FunctionMock, MethodMock, and GlobalFunctionMock.
*
*/
goog.provide('goog.testing.MockControl');
goog.require('goog.array');
goog.require('goog.testing');
goog.require('goog.testing.LooseMock');
goog.require('goog.testing.MockInterface');
goog.require('goog.testing.StrictMock');
/**
* Controls a set of mocks. Controlled mocks are replayed, verified, and
* cleaned-up at the same time.
* @constructor
*/
goog.testing.MockControl = function() {
/**
* The list of mocks being controlled.
* @type {Array.<goog.testing.MockInterface>}
* @private
*/
this.mocks_ = [];
};
/**
* Takes control of this mock.
* @param {goog.testing.MockInterface} mock Mock to be controlled.
* @return {goog.testing.MockInterface} The same mock passed in,
* for convenience.
*/
goog.testing.MockControl.prototype.addMock = function(mock) {
this.mocks_.push(mock);
return mock;
};
/**
* Calls replay on each controlled mock.
*/
goog.testing.MockControl.prototype.$replayAll = function() {
goog.array.forEach(this.mocks_, function(m) {
m.$replay();
});
};
/**
* Calls reset on each controlled mock.
*/
goog.testing.MockControl.prototype.$resetAll = function() {
goog.array.forEach(this.mocks_, function(m) {
m.$reset();
});
};
/**
* Calls verify on each controlled mock.
*/
goog.testing.MockControl.prototype.$verifyAll = function() {
goog.array.forEach(this.mocks_, function(m) {
m.$verify();
});
};
/**
* Calls tearDown on each controlled mock, if necesssary.
*/
goog.testing.MockControl.prototype.$tearDown = function() {
goog.array.forEach(this.mocks_, function(m) {
// $tearDown if defined.
if (m.$tearDown) {
m.$tearDown();
}
// TODO(user): Somehow determine if verifyAll should have been called
// but was not.
});
};
/**
* Creates a controlled StrictMock. Passes its arguments through to the
* StrictMock constructor.
* @param {Object} objectToMock The object to mock.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @return {goog.testing.StrictMock} The mock object.
*/
goog.testing.MockControl.prototype.createStrictMock = function(
objectToMock, opt_mockStaticMethods, opt_createProxy) {
var m = new goog.testing.StrictMock(objectToMock, opt_mockStaticMethods,
opt_createProxy);
this.addMock(m);
return m;
};
/**
* Creates a controlled LooseMock. Passes its arguments through to the
* LooseMock constructor.
* @param {Object} objectToMock The object to mock.
* @param {boolean=} opt_ignoreUnexpectedCalls Whether to ignore unexpected
* calls.
* @param {boolean=} opt_mockStaticMethods An optional argument denoting that
* a mock should be constructed from the static functions of a class.
* @param {boolean=} opt_createProxy An optional argument denoting that
* a proxy for the target mock should be created.
* @return {goog.testing.LooseMock} The mock object.
*/
goog.testing.MockControl.prototype.createLooseMock = function(
objectToMock, opt_ignoreUnexpectedCalls,
opt_mockStaticMethods, opt_createProxy) {
var m = new goog.testing.LooseMock(objectToMock, opt_ignoreUnexpectedCalls,
opt_mockStaticMethods, opt_createProxy);
this.addMock(m);
return m;
};
/**
* Creates a controlled FunctionMock. Passes its arguments through to the
* FunctionMock constructor.
* @param {string=} opt_functionName The optional name of the function to mock
* set to '[anonymous mocked function]' if not passed in.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked function.
*/
goog.testing.MockControl.prototype.createFunctionMock = function(
opt_functionName, opt_strictness) {
var m = goog.testing.createFunctionMock(opt_functionName, opt_strictness);
this.addMock(m);
return m;
};
/**
* Creates a controlled MethodMock. Passes its arguments through to the
* MethodMock constructor.
* @param {Object} scope The scope of the method to be mocked out.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked method.
*/
goog.testing.MockControl.prototype.createMethodMock = function(
scope, functionName, opt_strictness) {
var m = goog.testing.createMethodMock(scope, functionName, opt_strictness);
this.addMock(m);
return m;
};
/**
* Creates a controlled MethodMock for a constructor. Passes its arguments
* through to the MethodMock constructor. See
* {@link goog.testing.createConstructorMock} for details.
* @param {Object} scope The scope of the constructor to be mocked out.
* @param {string} constructorName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked method.
*/
goog.testing.MockControl.prototype.createConstructorMock = function(
scope, constructorName, opt_strictness) {
var m = goog.testing.createConstructorMock(scope, constructorName,
opt_strictness);
this.addMock(m);
return m;
};
/**
* Creates a controlled GlobalFunctionMock. Passes its arguments through to the
* GlobalFunctionMock constructor.
* @param {string} functionName The name of the function we're going to mock.
* @param {number=} opt_strictness One of goog.testing.Mock.LOOSE or
* goog.testing.Mock.STRICT. The default is STRICT.
* @return {goog.testing.MockInterface} The mocked function.
*/
goog.testing.MockControl.prototype.createGlobalFunctionMock = function(
functionName, opt_strictness) {
var m = goog.testing.createGlobalFunctionMock(functionName, opt_strictness);
this.addMock(m);
return m;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 class representing a set of test functions to be run.
*
* Testing code should not have dependencies outside of goog.testing so as to
* reduce the chance of masking missing dependencies.
*
* This file does not compile correctly with --collapse_properties. Use
* --property_renaming=ALL_UNQUOTED instead.
*
*/
goog.provide('goog.testing.TestCase');
goog.provide('goog.testing.TestCase.Error');
goog.provide('goog.testing.TestCase.Order');
goog.provide('goog.testing.TestCase.Result');
goog.provide('goog.testing.TestCase.Test');
goog.require('goog.object');
goog.require('goog.testing.asserts');
goog.require('goog.testing.stacktrace');
/**
* A class representing a JsUnit test case. A TestCase is made up of a number
* of test functions which can be run. Individual test cases can override the
* following functions to set up their test environment:
* - runTests - completely override the test's runner
* - setUpPage - called before any of the test functions are run
* - tearDownPage - called after all tests are finished
* - setUp - called before each of the test functions
* - tearDown - called after each of the test functions
* - shouldRunTests - called before a test run, all tests are skipped if it
* returns false. Can be used to disable tests on browsers
* where they aren't expected to pass.
*
* Use {@link #autoDiscoverTests}
*
* @param {string=} opt_name The name of the test case, defaults to
* 'Untitled Test Case'.
* @constructor
*/
goog.testing.TestCase = function(opt_name) {
/**
* A name for the test case.
* @type {string}
* @private
*/
this.name_ = opt_name || 'Untitled Test Case';
/**
* Array of test functions that can be executed.
* @type {Array.<goog.testing.TestCase.Test>}
* @private
*/
this.tests_ = [];
/**
* Set of test names and/or indices to execute, or null if all tests should
* be executed.
*
* Indices are included to allow automation tools to run a subset of the
* tests without knowing the exact contents of the test file.
*
* Indices should only be used with SORTED ordering.
*
* Example valid values:
* <ul>
* <li>[testName]
* <li>[testName1, testName2]
* <li>[2] - will run the 3rd test in the order specified
* <li>[1,3,5]
* <li>[testName1, testName2, 3, 5] - will work
* <ul>
* @type {Object}
* @private
*/
this.testsToRun_ = null;
var search = '';
if (goog.global.location) {
search = goog.global.location.search;
}
// Parse the 'runTests' query parameter into a set of test names and/or
// test indices.
var runTestsMatch = search.match(/(?:\?|&)runTests=([^?&]+)/i);
if (runTestsMatch) {
this.testsToRun_ = {};
var arr = runTestsMatch[1].split(',');
for (var i = 0, len = arr.length; i < len; i++) {
this.testsToRun_[arr[i]] = 1;
}
}
// Checks the URL for a valid order param.
var orderMatch = search.match(/(?:\?|&)order=(natural|random|sorted)/i);
if (orderMatch) {
this.order = orderMatch[1];
}
/**
* Object used to encapsulate the test results.
* @type {goog.testing.TestCase.Result}
* @protected
* @suppress {underscore}
*/
this.result_ = new goog.testing.TestCase.Result(this);
// This silences a compiler warning from the legacy property check, which
// is deprecated. It idly writes to testRunner properties that are used
// in this file.
var testRunnerMethods = {isFinished: true, hasErrors: true};
};
/**
* The order to run the auto-discovered tests.
* @enum {string}
*/
goog.testing.TestCase.Order = {
/**
* This is browser dependent and known to be different in FF and Safari
* compared to others.
*/
NATURAL: 'natural',
/** Random order. */
RANDOM: 'random',
/** Sorted based on the name. */
SORTED: 'sorted'
};
/**
* The maximum amount of time that the test can run before we force it to be
* async. This prevents the test runner from blocking the browser and
* potentially hurting the Selenium test harness.
* @type {number}
*/
goog.testing.TestCase.MAX_RUN_TIME = 200;
/**
* The order to run the auto-discovered tests in.
* @type {string}
*/
goog.testing.TestCase.prototype.order = goog.testing.TestCase.Order.SORTED;
/**
* Save a reference to {@code window.setTimeout}, so any code that overrides the
* default behavior (the MockClock, for example) doesn't affect our runner.
* @type {function((Function|string), number, *=): number}
* @private
*/
goog.testing.TestCase.protectedSetTimeout_ = goog.global.setTimeout;
/**
* Save a reference to {@code window.clearTimeout}, so any code that overrides
* the default behavior (e.g. MockClock) doesn't affect our runner.
* @type {function((null|number|undefined)): void}
* @private
*/
goog.testing.TestCase.protectedClearTimeout_ = goog.global.clearTimeout;
/**
* Saved string referencing goog.global.setTimeout's string serialization. IE
* sometimes fails to uphold equality for setTimeout, but the string version
* stays the same.
* @type {string}
* @private
*/
goog.testing.TestCase.setTimeoutAsString_ = String(goog.global.setTimeout);
/**
* TODO(user) replace this with prototype.currentTest.
* Name of the current test that is running, or null if none is running.
* @type {?string}
*/
goog.testing.TestCase.currentTestName = null;
/**
* Avoid a dependency on goog.userAgent and keep our own reference of whether
* the browser is IE.
* @type {boolean}
*/
goog.testing.TestCase.IS_IE = typeof opera == 'undefined' &&
!!goog.global.navigator &&
goog.global.navigator.userAgent.indexOf('MSIE') != -1;
/**
* Exception object that was detected before a test runs.
* @type {*}
* @protected
*/
goog.testing.TestCase.prototype.exceptionBeforeTest;
/**
* Whether the test case has ever tried to execute.
* @type {boolean}
*/
goog.testing.TestCase.prototype.started = false;
/**
* Whether the test case is running.
* @type {boolean}
*/
goog.testing.TestCase.prototype.running = false;
/**
* Timestamp for when the test was started.
* @type {number}
* @private
*/
goog.testing.TestCase.prototype.startTime_ = 0;
/**
* Time since the last batch of tests was started, if batchTime exceeds
* {@link #MAX_RUN_TIME} a timeout will be used to stop the tests blocking the
* browser and a new batch will be started.
* @type {number}
* @private
*/
goog.testing.TestCase.prototype.batchTime_ = 0;
/**
* Pointer to the current test.
* @type {number}
* @private
*/
goog.testing.TestCase.prototype.currentTestPointer_ = 0;
/**
* Optional callback that will be executed when the test has finalized.
* @type {Function}
* @private
*/
goog.testing.TestCase.prototype.onCompleteCallback_ = null;
/**
* The test runner that is running this case.
* @type {goog.testing.TestRunner?}
* @private
*/
goog.testing.TestCase.prototype.testRunner_ = null;
/**
* Adds a new test to the test case.
* @param {goog.testing.TestCase.Test} test The test to add.
*/
goog.testing.TestCase.prototype.add = function(test) {
this.tests_.push(test);
};
/**
* Sets the tests.
* @param {Array.<goog.testing.TestCase.Test>} tests A new test array.
* @protected
*/
goog.testing.TestCase.prototype.setTests = function(tests) {
this.tests_ = tests;
};
/**
* Gets the tests.
* @return {Array.<goog.testing.TestCase.Test>} The test array.
* @protected
*/
goog.testing.TestCase.prototype.getTests = function() {
return this.tests_;
};
/**
* Returns the number of tests contained in the test case.
* @return {number} The number of tests.
*/
goog.testing.TestCase.prototype.getCount = function() {
return this.tests_.length;
};
/**
* Returns the number of tests actually run in the test case, i.e. subtracting
* any which are skipped.
* @return {number} The number of un-ignored tests.
*/
goog.testing.TestCase.prototype.getActuallyRunCount = function() {
return this.testsToRun_ ? goog.object.getCount(this.testsToRun_) : 0;
};
/**
* Returns the current test and increments the pointer.
* @return {goog.testing.TestCase.Test?} The current test case.
*/
goog.testing.TestCase.prototype.next = function() {
var test;
while ((test = this.tests_[this.currentTestPointer_++])) {
if (!this.testsToRun_ || this.testsToRun_[test.name] ||
this.testsToRun_[this.currentTestPointer_ - 1]) {
return test;
}
}
return null;
};
/**
* Resets the test case pointer, so that next returns the first test.
*/
goog.testing.TestCase.prototype.reset = function() {
this.currentTestPointer_ = 0;
this.result_ = new goog.testing.TestCase.Result(this);
};
/**
* Sets the callback function that should be executed when the tests have
* completed.
* @param {Function} fn The callback function.
*/
goog.testing.TestCase.prototype.setCompletedCallback = function(fn) {
this.onCompleteCallback_ = fn;
};
/**
* Sets the test runner that is running this test case.
* @param {goog.testing.TestRunner} tr The test runner.
*/
goog.testing.TestCase.prototype.setTestRunner = function(tr) {
this.testRunner_ = tr;
};
/**
* Can be overridden in test classes to indicate whether the tests in a case
* should be run in that particular situation. For example, this could be used
* to stop tests running in a particular browser, where browser support for
* the class under test was absent.
* @return {boolean} Whether any of the tests in the case should be run.
*/
goog.testing.TestCase.prototype.shouldRunTests = function() {
return true;
};
/**
* Executes each of the tests.
*/
goog.testing.TestCase.prototype.execute = function() {
this.started = true;
this.reset();
this.startTime_ = this.now();
this.running = true;
this.result_.totalCount = this.getCount();
if (!this.shouldRunTests()) {
this.log('shouldRunTests() returned false, skipping these tests.');
this.result_.testSuppressed = true;
this.finalize();
return;
}
this.log('Starting tests: ' + this.name_);
this.cycleTests();
};
/**
* Finalizes the test case, called when the tests have finished executing.
*/
goog.testing.TestCase.prototype.finalize = function() {
this.saveMessage('Done');
this.tearDownPage();
var restoredSetTimeout =
goog.testing.TestCase.protectedSetTimeout_ == goog.global.setTimeout &&
goog.testing.TestCase.protectedClearTimeout_ == goog.global.clearTimeout;
if (!restoredSetTimeout && goog.testing.TestCase.IS_IE &&
String(goog.global.setTimeout) ==
goog.testing.TestCase.setTimeoutAsString_) {
// In strange cases, IE's value of setTimeout *appears* to change, but
// the string representation stays stable.
restoredSetTimeout = true;
}
if (!restoredSetTimeout) {
var message = 'ERROR: Test did not restore setTimeout and clearTimeout';
this.saveMessage(message);
var err = new goog.testing.TestCase.Error(this.name_, message);
this.result_.errors.push(err);
}
goog.global.clearTimeout = goog.testing.TestCase.protectedClearTimeout_;
goog.global.setTimeout = goog.testing.TestCase.protectedSetTimeout_;
this.endTime_ = this.now();
this.running = false;
this.result_.runTime = this.endTime_ - this.startTime_;
this.result_.numFilesLoaded = this.countNumFilesLoaded_();
this.log(this.result_.getSummary());
if (this.result_.isSuccess()) {
this.log('Tests complete');
} else {
this.log('Tests Failed');
}
if (this.onCompleteCallback_) {
var fn = this.onCompleteCallback_;
// Execute's the completed callback in the context of the global object.
fn();
this.onCompleteCallback_ = null;
}
};
/**
* Saves a message to the result set.
* @param {string} message The message to save.
*/
goog.testing.TestCase.prototype.saveMessage = function(message) {
this.result_.messages.push(this.getTimeStamp_() + ' ' + message);
};
/**
* @return {boolean} Whether the test case is running inside the multi test
* runner.
*/
goog.testing.TestCase.prototype.isInsideMultiTestRunner = function() {
var top = goog.global['top'];
return top && typeof top['_allTests'] != 'undefined';
};
/**
* Logs an object to the console, if available.
* @param {*} val The value to log. Will be ToString'd.
*/
goog.testing.TestCase.prototype.log = function(val) {
if (!this.isInsideMultiTestRunner() && goog.global.console) {
if (typeof val == 'string') {
val = this.getTimeStamp_() + ' : ' + val;
}
if (val instanceof Error && val.stack) {
// Chrome does console.log asynchronously in a different process
// (http://code.google.com/p/chromium/issues/detail?id=50316).
// This is an acute problem for Errors, which almost never survive.
// Grab references to the immutable strings so they survive.
goog.global.console.log(val, val.message, val.stack);
// TODO(gboyer): Consider for Chrome cloning any object if we can ensure
// there are no circular references.
} else {
goog.global.console.log(val);
}
}
};
/**
* @return {boolean} Whether the test was a success.
*/
goog.testing.TestCase.prototype.isSuccess = function() {
return !!this.result_ && this.result_.isSuccess();
};
/**
* Returns a string detailing the results from the test.
* @param {boolean=} opt_verbose If true results will include data about all
* tests, not just what failed.
* @return {string} The results from the test.
*/
goog.testing.TestCase.prototype.getReport = function(opt_verbose) {
var rv = [];
if (this.testRunner_ && !this.testRunner_.isFinished()) {
rv.push(this.name_ + ' [RUNNING]');
} else {
var success = this.result_.isSuccess() && !this.testRunner_.hasErrors();
rv.push(this.name_ + ' [' + (success ? 'PASSED' : 'FAILED') + ']');
}
if (goog.global.location) {
rv.push(this.trimPath_(goog.global.location.href));
}
rv.push(this.result_.getSummary());
if (opt_verbose) {
rv.push('.', this.result_.messages.join('\n'));
} else if (!this.result_.isSuccess()) {
rv.push(this.result_.errors.join('\n'));
}
rv.push(' ');
return rv.join('\n');
};
/**
* Returns the amount of time it took for the test to run.
* @return {number} The run time, in milliseconds.
*/
goog.testing.TestCase.prototype.getRunTime = function() {
return this.result_.runTime;
};
/**
* Returns the number of script files that were loaded in order to run the test.
* @return {number} The number of script files.
*/
goog.testing.TestCase.prototype.getNumFilesLoaded = function() {
return this.result_.numFilesLoaded;
};
/**
* Executes each of the tests.
* Overridable by the individual test case. This allows test cases to defer
* when the test is actually started. If overridden, finalize must be called
* by the test to indicate it has finished.
*/
goog.testing.TestCase.prototype.runTests = function() {
try {
this.setUpPage();
} catch (e) {
this.exceptionBeforeTest = e;
}
this.execute();
};
/**
* Reorders the tests depending on the {@code order} field.
* @param {Array.<goog.testing.TestCase.Test>} tests An array of tests to
* reorder.
* @private
*/
goog.testing.TestCase.prototype.orderTests_ = function(tests) {
switch (this.order) {
case goog.testing.TestCase.Order.RANDOM:
// Fisher-Yates shuffle
var i = tests.length;
while (i > 1) {
// goog.math.randomInt is inlined to reduce dependencies.
var j = Math.floor(Math.random() * i); // exclusive
i--;
var tmp = tests[i];
tests[i] = tests[j];
tests[j] = tmp;
}
break;
case goog.testing.TestCase.Order.SORTED:
tests.sort(function(t1, t2) {
if (t1.name == t2.name) {
return 0;
}
return t1.name < t2.name ? -1 : 1;
});
break;
// Do nothing for NATURAL.
}
};
/**
* Gets the object with all globals.
* @param {string=} opt_prefix An optional prefix. If specified, only get things
* under this prefix. Note that the prefix is only honored in IE, since it
* supports the RuntimeObject:
* http://msdn.microsoft.com/en-us/library/ff521039%28VS.85%29.aspx
* TODO: Fix this method to honor the prefix in all browsers.
* @return {Object} An object with all globals starting with the prefix.
*/
goog.testing.TestCase.prototype.getGlobals = function(opt_prefix) {
return goog.testing.TestCase.getGlobals(opt_prefix);
};
/**
* Gets the object with all globals.
* @param {string=} opt_prefix An optional prefix. If specified, only get things
* under this prefix. Note that the prefix is only honored in IE, since it
* supports the RuntimeObject:
* http://msdn.microsoft.com/en-us/library/ff521039%28VS.85%29.aspx
* TODO: Fix this method to honor the prefix in all browsers.
* @return {Object} An object with all globals starting with the prefix.
*/
goog.testing.TestCase.getGlobals = function(opt_prefix) {
// Look in the global scope for most browsers, on IE we use the little known
// RuntimeObject which holds references to all globals. We reference this
// via goog.global so that there isn't an aliasing that throws an exception
// in Firefox.
return typeof goog.global['RuntimeObject'] != 'undefined' ?
goog.global['RuntimeObject']((opt_prefix || '') + '*') : goog.global;
};
/**
* Gets called before any tests are executed. Can be overridden to set up the
* environment for the whole test case.
*/
goog.testing.TestCase.prototype.setUpPage = function() {};
/**
* Gets called after all tests have been executed. Can be overridden to tear
* down the entire test case.
*/
goog.testing.TestCase.prototype.tearDownPage = function() {};
/**
* Gets called before every goog.testing.TestCase.Test is been executed. Can be
* overridden to add set up functionality to each test.
*/
goog.testing.TestCase.prototype.setUp = function() {};
/**
* Gets called after every goog.testing.TestCase.Test has been executed. Can be
* overriden to add tear down functionality to each test.
*/
goog.testing.TestCase.prototype.tearDown = function() {};
/**
* @return {string} The function name prefix used to auto-discover tests.
* @protected
*/
goog.testing.TestCase.prototype.getAutoDiscoveryPrefix = function() {
return 'test';
};
/**
* @return {number} Time since the last batch of tests was started.
* @protected
*/
goog.testing.TestCase.prototype.getBatchTime = function() {
return this.batchTime_;
};
/**
* @param {number} batchTime Time since the last batch of tests was started.
* @protected
*/
goog.testing.TestCase.prototype.setBatchTime = function(batchTime) {
this.batchTime_ = batchTime;
};
/**
* Creates a {@code goog.testing.TestCase.Test} from an auto-discovered
* function.
* @param {string} name The name of the function.
* @param {function() : void} ref The auto-discovered function.
* @return {goog.testing.TestCase.Test} The newly created test.
* @protected
*/
goog.testing.TestCase.prototype.createTestFromAutoDiscoveredFunction =
function(name, ref) {
return new goog.testing.TestCase.Test(name, ref, goog.global);
};
/**
* Adds any functions defined in the global scope that are prefixed with "test"
* to the test case. Also overrides setUp, tearDown, setUpPage, tearDownPage
* and runTests if they are defined.
*/
goog.testing.TestCase.prototype.autoDiscoverTests = function() {
var prefix = this.getAutoDiscoveryPrefix();
var testSource = this.getGlobals(prefix);
var foundTests = [];
for (var name in testSource) {
try {
var ref = testSource[name];
} catch (ex) {
// NOTE(brenneman): When running tests from a file:// URL on Firefox 3.5
// for Windows, any reference to goog.global.sessionStorage raises
// an "Operation is not supported" exception. Ignore any exceptions raised
// by simply accessing global properties.
}
if ((new RegExp('^' + prefix)).test(name) && goog.isFunction(ref)) {
foundTests.push(this.createTestFromAutoDiscoveredFunction(name, ref));
}
}
this.orderTests_(foundTests);
for (var i = 0; i < foundTests.length; i++) {
this.add(foundTests[i]);
}
this.log(this.getCount() + ' tests auto-discovered');
if (goog.global['setUp']) {
this.setUp = goog.bind(goog.global['setUp'], goog.global);
}
if (goog.global['tearDown']) {
this.tearDown = goog.bind(goog.global['tearDown'], goog.global);
}
if (goog.global['setUpPage']) {
this.setUpPage = goog.bind(goog.global['setUpPage'], goog.global);
}
if (goog.global['tearDownPage']) {
this.tearDownPage = goog.bind(goog.global['tearDownPage'], goog.global);
}
if (goog.global['runTests']) {
this.runTests = goog.bind(goog.global['runTests'], goog.global);
}
if (goog.global['shouldRunTests']) {
this.shouldRunTests = goog.bind(goog.global['shouldRunTests'], goog.global);
}
};
/**
* Checks to see if the test should be marked as failed before it is run.
*
* If there was an error in setUpPage, we treat that as a failure for all tests
* and mark them all as having failed.
*
* @param {goog.testing.TestCase.Test} testCase The current test case.
* @return {boolean} Whether the test was marked as failed.
* @protected
*/
goog.testing.TestCase.prototype.maybeFailTestEarly = function(testCase) {
if (this.exceptionBeforeTest) {
// We just use the first error to report an error on a failed test.
testCase.name = 'setUpPage for ' + testCase.name;
this.doError(testCase, this.exceptionBeforeTest);
return true;
}
return false;
};
/**
* Cycles through the tests, breaking out using a setTimeout if the execution
* time has execeeded {@link #MAX_RUN_TIME}.
*/
goog.testing.TestCase.prototype.cycleTests = function() {
this.saveMessage('Start');
this.batchTime_ = this.now();
var nextTest;
while ((nextTest = this.next()) && this.running) {
this.result_.runCount++;
// Execute the test and handle the error, we execute all tests rather than
// stopping after a single error.
var cleanedUp = false;
try {
this.log('Running test: ' + nextTest.name);
if (this.maybeFailTestEarly(nextTest)) {
cleanedUp = true;
} else {
goog.testing.TestCase.currentTestName = nextTest.name;
this.setUp();
nextTest.execute();
this.tearDown();
goog.testing.TestCase.currentTestName = null;
cleanedUp = true;
this.doSuccess(nextTest);
}
} catch (e) {
this.doError(nextTest, e);
if (!cleanedUp) {
try {
this.tearDown();
} catch (e2) {} // Fail silently if tearDown is throwing the errors.
}
}
// If the max run time is exceeded call this function again async so as not
// to block the browser.
if (this.currentTestPointer_ < this.tests_.length &&
this.now() - this.batchTime_ > goog.testing.TestCase.MAX_RUN_TIME) {
this.saveMessage('Breaking async');
this.timeout(goog.bind(this.cycleTests, this), 100);
return;
}
}
// Tests are done.
this.finalize();
};
/**
* Counts the number of files that were loaded for dependencies that are
* required to run the test.
* @return {number} The number of files loaded.
* @private
*/
goog.testing.TestCase.prototype.countNumFilesLoaded_ = function() {
var scripts = document.getElementsByTagName('script');
var count = 0;
for (var i = 0, n = scripts.length; i < n; i++) {
if (scripts[i].src) {
count++;
}
}
return count;
};
/**
* Calls a function after a delay, using the protected timeout.
* @param {Function} fn The function to call.
* @param {number} time Delay in milliseconds.
* @return {number} The timeout id.
* @protected
*/
goog.testing.TestCase.prototype.timeout = function(fn, time) {
// NOTE: invoking protectedSetTimeout_ as a member of goog.testing.TestCase
// would result in an Illegal Invocation error. The method must be executed
// with the global context.
var protectedSetTimeout = goog.testing.TestCase.protectedSetTimeout_;
return protectedSetTimeout(fn, time);
};
/**
* Clears a timeout created by {@code this.timeout()}.
* @param {number} id A timeout id.
* @protected
*/
goog.testing.TestCase.prototype.clearTimeout = function(id) {
// NOTE: see execution note for protectedSetTimeout above.
var protectedClearTimeout = goog.testing.TestCase.protectedClearTimeout_;
protectedClearTimeout(id);
};
/**
* @return {number} The current time in milliseconds, don't use goog.now as some
* tests override it.
* @protected
*/
goog.testing.TestCase.prototype.now = function() {
return new Date().getTime();
};
/**
* Returns the current time.
* @return {string} HH:MM:SS.
* @private
*/
goog.testing.TestCase.prototype.getTimeStamp_ = function() {
var d = new Date;
// Ensure millis are always 3-digits
var millis = '00' + d.getMilliseconds();
millis = millis.substr(millis.length - 3);
return this.pad_(d.getHours()) + ':' + this.pad_(d.getMinutes()) + ':' +
this.pad_(d.getSeconds()) + '.' + millis;
};
/**
* Pads a number to make it have a leading zero if it's less than 10.
* @param {number} number The number to pad.
* @return {string} The resulting string.
* @private
*/
goog.testing.TestCase.prototype.pad_ = function(number) {
return number < 10 ? '0' + number : String(number);
};
/**
* Trims a path to be only that after google3.
* @param {string} path The path to trim.
* @return {string} The resulting string.
* @private
*/
goog.testing.TestCase.prototype.trimPath_ = function(path) {
return path.substring(path.indexOf('google3') + 8);
};
/**
* Handles a test that passed.
* @param {goog.testing.TestCase.Test} test The test that passed.
* @protected
*/
goog.testing.TestCase.prototype.doSuccess = function(test) {
this.result_.successCount++;
var message = test.name + ' : PASSED';
this.saveMessage(message);
this.log(message);
};
/**
* Handles a test that failed.
* @param {goog.testing.TestCase.Test} test The test that failed.
* @param {*=} opt_e The exception object associated with the
* failure or a string.
* @protected
*/
goog.testing.TestCase.prototype.doError = function(test, opt_e) {
var message = test.name + ' : FAILED';
this.log(message);
this.saveMessage(message);
var err = this.logError(test.name, opt_e);
this.result_.errors.push(err);
};
/**
* @param {string} name Failed test name.
* @param {*=} opt_e The exception object associated with the
* failure or a string.
* @return {goog.testing.TestCase.Error} Error object.
*/
goog.testing.TestCase.prototype.logError = function(name, opt_e) {
var errMsg = null;
var stack = null;
if (opt_e) {
this.log(opt_e);
if (goog.isString(opt_e)) {
errMsg = opt_e;
} else {
errMsg = opt_e.message || opt_e.description || opt_e.toString();
stack = opt_e.stack ? goog.testing.stacktrace.canonicalize(opt_e.stack) :
opt_e['stackTrace'];
}
} else {
errMsg = 'An unknown error occurred';
}
var err = new goog.testing.TestCase.Error(name, errMsg, stack);
// Avoid double logging.
if (!opt_e || !opt_e['isJsUnitException'] ||
!opt_e['loggedJsUnitException']) {
this.saveMessage(err.toString());
}
if (opt_e && opt_e['isJsUnitException']) {
opt_e['loggedJsUnitException'] = true;
}
return err;
};
/**
* A class representing a single test function.
* @param {string} name The test name.
* @param {Function} ref Reference to the test function.
* @param {Object=} opt_scope Optional scope that the test function should be
* called in.
* @constructor
*/
goog.testing.TestCase.Test = function(name, ref, opt_scope) {
/**
* The name of the test.
* @type {string}
*/
this.name = name;
/**
* Reference to the test function.
* @type {Function}
*/
this.ref = ref;
/**
* Scope that the test function should be called in.
* @type {Object}
*/
this.scope = opt_scope || null;
};
/**
* Executes the test function.
*/
goog.testing.TestCase.Test.prototype.execute = function() {
this.ref.call(this.scope);
};
/**
* A class for representing test results. A bag of public properties.
* @param {goog.testing.TestCase} testCase The test case that owns this result.
* @constructor
*/
goog.testing.TestCase.Result = function(testCase) {
/**
* The test case that owns this result.
* @type {goog.testing.TestCase}
* @private
*/
this.testCase_ = testCase;
/**
* Total number of tests that should have been run.
* @type {number}
*/
this.totalCount = 0;
/**
* Total number of tests that were actually run.
* @type {number}
*/
this.runCount = 0;
/**
* Number of successful tests.
* @type {number}
*/
this.successCount = 0;
/**
* The amount of time the tests took to run.
* @type {number}
*/
this.runTime = 0;
/**
* The number of files loaded to run this test.
* @type {number}
*/
this.numFilesLoaded = 0;
/**
* Whether this test case was suppressed by shouldRunTests() returning false.
* @type {boolean}
*/
this.testSuppressed = false;
/**
* Errors encountered while running the test.
* @type {Array.<goog.testing.TestCase.Error>}
*/
this.errors = [];
/**
* Messages to show the user after running the test.
* @type {Array.<string>}
*/
this.messages = [];
};
/**
* @return {boolean} Whether the test was successful.
*/
goog.testing.TestCase.Result.prototype.isSuccess = function() {
var noErrors = this.runCount == this.successCount && this.errors.length == 0;
if (noErrors && !this.testSuppressed && this.isStrict()) {
return this.runCount > 0;
}
return noErrors;
};
/**
* @return {string} A summary of the tests, including total number of tests that
* passed, failed, and the time taken.
*/
goog.testing.TestCase.Result.prototype.getSummary = function() {
var summary = this.runCount + ' of ' + this.totalCount + ' tests run in ' +
this.runTime + 'ms.\n';
if (this.testSuppressed) {
summary += 'Tests not run because shouldRunTests() returned false.';
} else if (this.runCount == 0) {
summary += 'No tests found. ';
if (this.isStrict()) {
summary +=
'Call G_testRunner.setStrict(false) if this is expected behavior. ';
}
} else {
var failures = this.totalCount - this.successCount;
var suppressionMessage = '';
var countOfRunTests = this.testCase_.getActuallyRunCount();
if (countOfRunTests) {
failures = countOfRunTests - this.successCount;
suppressionMessage = ', ' +
(this.totalCount - countOfRunTests) + ' suppressed by querystring';
}
summary += this.successCount + ' passed, ' +
failures + ' failed' + suppressionMessage + '.\n' +
Math.round(this.runTime / this.runCount) + ' ms/test. ' +
this.numFilesLoaded + ' files loaded.';
}
return summary;
};
/**
* Initializes the given test case with the global test runner 'G_testRunner'.
* @param {goog.testing.TestCase} testCase The test case to install.
*/
goog.testing.TestCase.initializeTestRunner = function(testCase) {
testCase.autoDiscoverTests();
var gTestRunner = goog.global['G_testRunner'];
if (gTestRunner) {
gTestRunner['initialize'](testCase);
} else {
throw Error('G_testRunner is undefined. Please ensure goog.testing.jsunit' +
' is included.');
}
};
/**
* Determines whether the test result should report failure if no tests are run.
* @return {boolean} Whether this is strict.
*/
goog.testing.TestCase.Result.prototype.isStrict = function() {
return this.testCase_.testRunner_.isStrict();
};
/**
* A class representing an error thrown by the test
* @param {string} source The name of the test which threw the error.
* @param {string} message The error message.
* @param {string=} opt_stack A string showing the execution stack.
* @constructor
*/
goog.testing.TestCase.Error = function(source, message, opt_stack) {
/**
* The name of the test which threw the error.
* @type {string}
*/
this.source = source;
/**
* Reference to the test function.
* @type {string}
*/
this.message = message;
/**
* Scope that the test function should be called in.
* @type {?string}
*/
this.stack = opt_stack || null;
};
/**
* Returns a string representing the error object.
* @return {string} A string representation of the error.
* @override
*/
goog.testing.TestCase.Error.prototype.toString = function() {
return 'ERROR in ' + this.source + '\n' +
this.message + (this.stack ? '\n' + this.stack : '');
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 Utilities for inspecting page layout. This is a port of
* http://go/layoutbot.java
* See {@link http://go/layouttesting}.
*/
goog.provide('goog.testing.style');
goog.require('goog.dom');
goog.require('goog.math.Rect');
goog.require('goog.style');
/**
* Determines whether the bounding rectangles of the given elements intersect.
* @param {Element} element The first element.
* @param {Element} otherElement The second element.
* @return {boolean} Whether the bounding rectangles of the given elements
* intersect.
*/
goog.testing.style.intersects = function(element, otherElement) {
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
return goog.math.Rect.intersects(elementRect, otherElementRect);
};
/**
* Determines whether the element has visible dimensions, i.e. x > 0 && y > 0.
* @param {Element} element The element to check.
* @return {boolean} Whether the element has visible dimensions.
*/
goog.testing.style.hasVisibleDimensions = function(element) {
var elSize = goog.style.getSize(element);
var shortest = elSize.getShortest();
if (shortest <= 0) {
return false;
}
return true;
};
/**
* Determines whether the CSS style of the element renders it visible.
* @param {!Element} element The element to check.
* @return {boolean} Whether the CSS style of the element renders it visible.
*/
goog.testing.style.isVisible = function(element) {
var visibilityStyle =
goog.testing.style.getAvailableStyle_(element, 'visibility');
var displayStyle =
goog.testing.style.getAvailableStyle_(element, 'display');
return (visibilityStyle != 'hidden' && displayStyle != 'none');
};
/**
* Test whether the given element is on screen.
* @param {!Element} el The element to test.
* @return {boolean} Whether the element is on the screen.
*/
goog.testing.style.isOnScreen = function(el) {
var doc = goog.dom.getDomHelper(el).getDocument();
var viewport = goog.style.getVisibleRectForElement(doc.body);
var viewportRect = goog.math.Rect.createFromBox(viewport);
return goog.dom.contains(doc, el) &&
goog.style.getBounds(el).intersects(viewportRect);
};
/**
* This is essentially goog.style.getStyle_. goog.style.getStyle_ is private
* and is not a recommended way for general purpose style extractor. For the
* purposes of layout testing, we only use this function for retrieving
* 'visiblity' and 'display' style.
* @param {!Element} element The element to retrieve the style from.
* @param {string} style Style property name.
* @return {string} Style value.
* @private
*/
goog.testing.style.getAvailableStyle_ = function(element, style) {
return goog.style.getComputedStyle(element, style) ||
goog.style.getCascadedStyle(element, style) ||
goog.style.getStyle(element, style);
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 utility class for making layout assertions. This is a port
* of http://go/layoutbot.java
* See {@link http://go/layouttesting}.
*/
goog.provide('goog.testing.style.layoutasserts');
goog.require('goog.style');
goog.require('goog.testing.asserts');
goog.require('goog.testing.style');
/**
* Asserts that an element has:
* 1 - a CSS rendering the makes the element visible.
* 2 - a non-zero width and height.
* @param {Element|string} a The element or optionally the comment string.
* @param {Element=} opt_b The element when a comment string is present.
*/
var assertIsVisible = function(a, opt_b) {
_validateArguments(1, arguments);
var element = nonCommentArg(1, 1, arguments);
_assert(commentArg(1, arguments),
goog.testing.style.isVisible(element) &&
goog.testing.style.hasVisibleDimensions(element),
'Specified element should be visible.');
};
/**
* The counter assertion of assertIsVisible().
* @param {Element|string} a The element or optionally the comment string.
* @param {Element=} opt_b The element when a comment string is present.
*/
var assertNotVisible = function(a, opt_b) {
_validateArguments(1, arguments);
var element = nonCommentArg(1, 1, arguments);
if (!element) {
return;
}
_assert(commentArg(1, arguments),
!goog.testing.style.isVisible(element) ||
!goog.testing.style.hasVisibleDimensions(element),
'Specified element should not be visible.');
};
/**
* Asserts that the two specified elements intersect.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertIntersect = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
_assert(commentArg(1, arguments),
goog.testing.style.intersects(element, otherElement),
'Elements should intersect.');
};
/**
* Asserts that the two specified elements do not intersect.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertNoIntersect = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
_assert(commentArg(1, arguments),
!goog.testing.style.intersects(element, otherElement),
'Elements should not intersect.');
};
/**
* Asserts that the element must have the specified width.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertWidth = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var width = nonCommentArg(2, 2, arguments);
var size = goog.style.getSize(element);
var elementWidth = size.width;
_assert(commentArg(1, arguments),
goog.testing.style.layoutasserts.isWithinThreshold_(
width, elementWidth, 0 /* tolerance */),
'Element should have width ' + width + ' but was ' + elementWidth + '.');
};
/**
* Asserts that the element must have the specified width within the specified
* tolerance.
* @param {Element|string} a The element or optionally the comment string.
* @param {number|Element} b The height or the element if comment string is
* present.
* @param {number} c The tolerance or the height if comment string is
* present.
* @param {number=} opt_d The tolerance if comment string is present.
*/
var assertWidthWithinTolerance = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var element = nonCommentArg(1, 3, arguments);
var width = nonCommentArg(2, 3, arguments);
var tolerance = nonCommentArg(3, 3, arguments);
var size = goog.style.getSize(element);
var elementWidth = size.width;
_assert(commentArg(1, arguments),
goog.testing.style.layoutasserts.isWithinThreshold_(
width, elementWidth, tolerance),
'Element width(' + elementWidth + ') should be within given width(' +
width + ') with tolerance value of ' + tolerance + '.');
};
/**
* Asserts that the element must have the specified height.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertHeight = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var height = nonCommentArg(2, 2, arguments);
var size = goog.style.getSize(element);
var elementHeight = size.height;
_assert(commentArg(1, arguments),
goog.testing.style.layoutasserts.isWithinThreshold_(
height, elementHeight, 0 /* tolerance */),
'Element should have height ' + height + '.');
};
/**
* Asserts that the element must have the specified height within the specified
* tolerance.
* @param {Element|string} a The element or optionally the comment string.
* @param {number|Element} b The height or the element if comment string is
* present.
* @param {number} c The tolerance or the height if comment string is
* present.
* @param {number=} opt_d The tolerance if comment string is present.
*/
var assertHeightWithinTolerance = function(a, b, c, opt_d) {
_validateArguments(3, arguments);
var element = nonCommentArg(1, 3, arguments);
var height = nonCommentArg(2, 3, arguments);
var tolerance = nonCommentArg(3, 3, arguments);
var size = goog.style.getSize(element);
var elementHeight = size.height;
_assert(commentArg(1, arguments),
goog.testing.style.layoutasserts.isWithinThreshold_(
height, elementHeight, tolerance),
'Element width(' + elementHeight + ') should be within given width(' +
height + ') with tolerance value of ' + tolerance + '.');
};
/**
* Asserts that the first element is to the left of the second element.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertIsLeftOf = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
_assert(commentArg(1, arguments),
elementRect.left < otherElementRect.left,
'Elements should be left to right.');
};
/**
* Asserts that the first element is strictly left of the second element.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertIsStrictlyLeftOf = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
_assert(commentArg(1, arguments),
elementRect.left + elementRect.width < otherElementRect.left,
'Elements should be strictly left to right.');
};
/**
* Asserts that the first element is higher than the second element.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertIsAbove = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
_assert(commentArg(1, arguments),
elementRect.top < otherElementRect.top,
'Elements should be top to bottom.');
};
/**
* Asserts that the first element is strictly higher than the second element.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertIsStrictlyAbove = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
_assert(commentArg(1, arguments),
elementRect.top + elementRect.height < otherElementRect.top,
'Elements should be strictly top to bottom.');
};
/**
* Asserts that the first element's bounds contain the bounds of the second
* element.
* @param {Element|string} a The first element or optionally the comment string.
* @param {Element} b The second element or the first element if comment string
* is present.
* @param {Element=} opt_c The second element if comment string is present.
*/
var assertContained = function(a, b, opt_c) {
_validateArguments(2, arguments);
var element = nonCommentArg(1, 2, arguments);
var otherElement = nonCommentArg(2, 2, arguments);
var elementRect = goog.style.getBounds(element);
var otherElementRect = goog.style.getBounds(otherElement);
_assert(commentArg(1, arguments),
elementRect.contains(otherElementRect),
'Element should be contained within the other element.');
};
/**
* Returns true if the difference between val1 and val2 is less than or equal to
* the threashold.
* @param {number} val1 The first value.
* @param {number} val2 The second value.
* @param {number} threshold The threshold value.
* @return {boolean} Whether or not the the values are within the threshold.
* @private
*/
goog.testing.style.layoutasserts.isWithinThreshold_ = function(
val1, val2, threshold) {
return Math.abs(val1 - val2) <= threshold;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Testing utilities for DOM related tests.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.testing.dom');
goog.require('goog.dom');
goog.require('goog.dom.NodeIterator');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagIterator');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.iter');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.testing.asserts');
goog.require('goog.userAgent');
/**
* A unique object to use as an end tag marker.
* @type {Object}
* @private
*/
goog.testing.dom.END_TAG_MARKER_ = {};
/**
* Tests if the given iterator over nodes matches the given Array of node
* descriptors. Throws an error if any match fails.
* @param {goog.iter.Iterator} it An iterator over nodes.
* @param {Array.<Node|number|string>} array Array of node descriptors to match
* against. Node descriptors can be any of the following:
* Node: Test if the two nodes are equal.
* number: Test node.nodeType == number.
* string starting with '#': Match the node's id with the text
* after "#".
* other string: Match the text node's contents.
*/
goog.testing.dom.assertNodesMatch = function(it, array) {
var i = 0;
goog.iter.forEach(it, function(node) {
if (array.length <= i) {
fail('Got more nodes than expected: ' + goog.testing.dom.describeNode_(
node));
}
var expected = array[i];
if (goog.dom.isNodeLike(expected)) {
assertEquals('Nodes should match at position ' + i, expected, node);
} else if (goog.isNumber(expected)) {
assertEquals('Node types should match at position ' + i, expected,
node.nodeType);
} else if (expected.charAt(0) == '#') {
assertEquals('Expected element at position ' + i,
goog.dom.NodeType.ELEMENT, node.nodeType);
var expectedId = expected.substr(1);
assertEquals('IDs should match at position ' + i,
expectedId, node.id);
} else {
assertEquals('Expected text node at position ' + i,
goog.dom.NodeType.TEXT, node.nodeType);
assertEquals('Node contents should match at position ' + i,
expected, node.nodeValue);
}
i++;
});
assertEquals('Used entire match array', array.length, i);
};
/**
* Exposes a node as a string.
* @param {Node} node A node.
* @return {string} A string representation of the node.
*/
goog.testing.dom.exposeNode = function(node) {
return (node.tagName || node.nodeValue) + (node.id ? '#' + node.id : '') +
':"' + (node.innerHTML || '') + '"';
};
/**
* Exposes the nodes of a range wrapper as a string.
* @param {goog.dom.AbstractRange} range A range.
* @return {string} A string representation of the range.
*/
goog.testing.dom.exposeRange = function(range) {
// This is deliberately not implemented as
// goog.dom.AbstractRange.prototype.toString, because it is non-authoritative.
// Two equivalent ranges may have very different exposeRange values, and
// two different ranges may have equal exposeRange values.
// (The mapping of ranges to DOM nodes/offsets is a many-to-many mapping).
if (!range) {
return 'null';
}
return goog.testing.dom.exposeNode(range.getStartNode()) + ':' +
range.getStartOffset() + ' to ' +
goog.testing.dom.exposeNode(range.getEndNode()) + ':' +
range.getEndOffset();
};
/**
* Determines if the current user agent matches the specified string. Returns
* false if the string does specify at least one user agent but does not match
* the running agent.
* @param {string} userAgents Space delimited string of user agents.
* @return {boolean} Whether the user agent was matched. Also true if no user
* agent was listed in the expectation string.
* @private
*/
goog.testing.dom.checkUserAgents_ = function(userAgents) {
if (goog.string.startsWith(userAgents, '!')) {
if (goog.string.contains(userAgents, ' ')) {
throw new Error('Only a single negative user agent may be specified');
}
return !goog.userAgent[userAgents.substr(1)];
}
var agents = userAgents.split(' ');
var hasUserAgent = false;
for (var i = 0, len = agents.length; i < len; i++) {
var cls = agents[i];
if (cls in goog.userAgent) {
hasUserAgent = true;
if (goog.userAgent[cls]) {
return true;
}
}
}
// If we got here, there was a user agent listed but we didn't match it.
return !hasUserAgent;
};
/**
* Map function that converts end tags to a specific object.
* @param {Node} node The node to map.
* @param {undefined} ignore Always undefined.
* @param {goog.dom.TagIterator} iterator The iterator.
* @return {Node|Object} The resulting iteration item.
* @private
*/
goog.testing.dom.endTagMap_ = function(node, ignore, iterator) {
return iterator.isEndTag() ? goog.testing.dom.END_TAG_MARKER_ : node;
};
/**
* Check if the given node is important. A node is important if it is a
* non-empty text node, a non-annotated element, or an element annotated to
* match on this user agent.
* @param {Node} node The node to test.
* @return {boolean} Whether this node should be included for iteration.
* @private
*/
goog.testing.dom.nodeFilter_ = function(node) {
if (node.nodeType == goog.dom.NodeType.TEXT) {
// If a node is part of a string of text nodes and it has spaces in it,
// we allow it since it's going to affect the merging of nodes done below.
if (goog.string.isBreakingWhitespace(node.nodeValue) &&
(!node.previousSibling ||
node.previousSibling.nodeType != goog.dom.NodeType.TEXT) &&
(!node.nextSibling ||
node.nextSibling.nodeType != goog.dom.NodeType.TEXT)) {
return false;
}
// Allow optional text to be specified as [[BROWSER1 BROWSER2]]Text
var match = node.nodeValue.match(/^\[\[(.+)\]\]/);
if (match) {
return goog.testing.dom.checkUserAgents_(match[1]);
}
} else if (node.className) {
return goog.testing.dom.checkUserAgents_(node.className);
}
return true;
};
/**
* Determines the text to match from the given node, removing browser
* specification strings.
* @param {Node} node The node expected to match.
* @return {string} The text, stripped of browser specification strings.
* @private
*/
goog.testing.dom.getExpectedText_ = function(node) {
// Strip off the browser specifications.
return node.nodeValue.match(/^(\[\[.+\]\])?(.*)/)[2];
};
/**
* Describes the given node.
* @param {Node} node The node to describe.
* @return {string} A description of the node.
* @private
*/
goog.testing.dom.describeNode_ = function(node) {
if (node.nodeType == goog.dom.NodeType.TEXT) {
return '[Text: ' + node.nodeValue + ']';
} else {
return '<' + node.tagName + (node.id ? ' #' + node.id : '') + ' .../>';
}
};
/**
* Assert that the html in {@code actual} is substantially similar to
* htmlPattern. This method tests for the same set of styles, for the same
* order of nodes, and the presence of attributes. Breaking whitespace nodes
* are ignored. Elements can be
* annotated with classnames corresponding to keys in goog.userAgent and will be
* expected to show up in that user agent and expected not to show up in
* others.
* @param {string} htmlPattern The pattern to match.
* @param {!Element} actual The element to check: its contents are matched
* against the HTML pattern.
* @param {boolean=} opt_strictAttributes If false, attributes that appear in
* htmlPattern must be in actual, but actual can have attributes not
* present in htmlPattern. If true, htmlPattern and actual must have the
* same set of attributes. Default is false.
*/
goog.testing.dom.assertHtmlContentsMatch = function(htmlPattern, actual,
opt_strictAttributes) {
var div = goog.dom.createDom(goog.dom.TagName.DIV);
div.innerHTML = htmlPattern;
var errorSuffix = '\nExpected\n' + htmlPattern + '\nActual\n' +
actual.innerHTML;
var actualIt = goog.iter.filter(
goog.iter.map(new goog.dom.TagIterator(actual),
goog.testing.dom.endTagMap_),
goog.testing.dom.nodeFilter_);
var expectedIt = goog.iter.filter(new goog.dom.NodeIterator(div),
goog.testing.dom.nodeFilter_);
var actualNode;
var preIterated = false;
var advanceActualNode = function() {
// If the iterator has already been advanced, don't advance it again.
if (!preIterated) {
actualNode = /** @type {Node} */ (goog.iter.nextOrValue(actualIt, null));
}
preIterated = false;
// Advance the iterator so long as it is return end tags.
while (actualNode == goog.testing.dom.END_TAG_MARKER_) {
actualNode = /** @type {Node} */ (goog.iter.nextOrValue(actualIt, null));
}
};
// HACK(brenneman): IE has unique ideas about whitespace handling when setting
// innerHTML. This results in elision of leading whitespace in the expected
// nodes where doing so doesn't affect visible rendering. As a workaround, we
// remove the leading whitespace in the actual nodes where necessary.
//
// The collapsible variable tracks whether we should collapse the whitespace
// in the next Text node we encounter.
var IE_TEXT_COLLAPSE = goog.userAgent.IE && !goog.userAgent.isVersion('9');
var collapsible = true;
var number = 0;
goog.iter.forEach(expectedIt, function(expectedNode) {
expectedNode = /** @type {Node} */ (expectedNode);
advanceActualNode();
assertNotNull('Finished actual HTML before finishing expected HTML at ' +
'node number ' + number + ': ' +
goog.testing.dom.describeNode_(expectedNode) + errorSuffix,
actualNode);
// Do no processing for expectedNode == div.
if (expectedNode == div) {
return;
}
assertEquals('Should have the same node type, got ' +
goog.testing.dom.describeNode_(actualNode) + ' but expected ' +
goog.testing.dom.describeNode_(expectedNode) + '.' + errorSuffix,
expectedNode.nodeType, actualNode.nodeType);
if (expectedNode.nodeType == goog.dom.NodeType.ELEMENT) {
assertEquals('Tag names should match' + errorSuffix,
expectedNode.tagName, actualNode.tagName);
assertObjectEquals('Should have same styles' + errorSuffix,
goog.style.parseStyleAttribute(expectedNode.style.cssText),
goog.style.parseStyleAttribute(actualNode.style.cssText));
goog.testing.dom.assertAttributesEqual_(errorSuffix, expectedNode,
actualNode, !!opt_strictAttributes);
if (IE_TEXT_COLLAPSE &&
goog.style.getCascadedStyle(
/** @type {Element} */ (actualNode), 'display') != 'inline') {
// Text may be collapsed after any non-inline element.
collapsible = true;
}
} else {
// Concatenate text nodes until we reach a non text node.
var actualText = actualNode.nodeValue;
preIterated = true;
while ((actualNode = /** @type {Node} */
(goog.iter.nextOrValue(actualIt, null))) &&
actualNode.nodeType == goog.dom.NodeType.TEXT) {
actualText += actualNode.nodeValue;
}
if (IE_TEXT_COLLAPSE) {
// Collapse the leading whitespace, unless the string consists entirely
// of whitespace.
if (collapsible && !goog.string.isEmpty(actualText)) {
actualText = goog.string.trimLeft(actualText);
}
// Prepare to collapse whitespace in the next Text node if this one does
// not end in a whitespace character.
collapsible = /\s$/.test(actualText);
}
var expectedText = goog.testing.dom.getExpectedText_(expectedNode);
if ((actualText && !goog.string.isBreakingWhitespace(actualText)) ||
(expectedText && !goog.string.isBreakingWhitespace(expectedText))) {
var normalizedActual = actualText.replace(/\s+/g, ' ');
var normalizedExpected = expectedText.replace(/\s+/g, ' ');
assertEquals('Text should match' + errorSuffix, normalizedExpected,
normalizedActual);
}
}
number++;
});
advanceActualNode();
assertNull('Finished expected HTML before finishing actual HTML' +
errorSuffix, goog.iter.nextOrValue(actualIt, null));
};
/**
* Assert that the html in {@code actual} is substantially similar to
* htmlPattern. This method tests for the same set of styles, and for the same
* order of nodes. Breaking whitespace nodes are ignored. Elements can be
* annotated with classnames corresponding to keys in goog.userAgent and will be
* expected to show up in that user agent and expected not to show up in
* others.
* @param {string} htmlPattern The pattern to match.
* @param {string} actual The html to check.
*/
goog.testing.dom.assertHtmlMatches = function(htmlPattern, actual) {
var div = goog.dom.createDom(goog.dom.TagName.DIV);
div.innerHTML = actual;
goog.testing.dom.assertHtmlContentsMatch(htmlPattern, div);
};
/**
* Finds the first text node descendant of root with the given content. Note
* that this operates on a text node level, so if text nodes get split this
* may not match the user visible text. Using normalize() may help here.
* @param {string|RegExp} textOrRegexp The text to find, or a regular
* expression to find a match of.
* @param {Element} root The element to search in.
* @return {Node} The first text node that matches, or null if none is found.
*/
goog.testing.dom.findTextNode = function(textOrRegexp, root) {
var it = new goog.dom.NodeIterator(root);
var ret = goog.iter.nextOrValue(goog.iter.filter(it, function(node) {
if (node.nodeType == goog.dom.NodeType.TEXT) {
if (goog.isString(textOrRegexp)) {
return node.nodeValue == textOrRegexp;
} else {
return !!node.nodeValue.match(textOrRegexp);
}
} else {
return false;
}
}), null);
return /** @type {Node} */ (ret);
};
/**
* Assert the end points of a range.
*
* Notice that "Are two ranges visually identical?" and "Do two ranges have
* the same endpoint?" are independent questions. Two visually identical ranges
* may have different endpoints. And two ranges with the same endpoints may
* be visually different.
*
* @param {Node} start The expected start node.
* @param {number} startOffset The expected start offset.
* @param {Node} end The expected end node.
* @param {number} endOffset The expected end offset.
* @param {goog.dom.AbstractRange} range The actual range.
*/
goog.testing.dom.assertRangeEquals = function(start, startOffset, end,
endOffset, range) {
assertEquals('Unexpected start node', start, range.getStartNode());
assertEquals('Unexpected end node', end, range.getEndNode());
assertEquals('Unexpected start offset', startOffset, range.getStartOffset());
assertEquals('Unexpected end offset', endOffset, range.getEndOffset());
};
/**
* Gets the value of a DOM attribute in deterministic way.
* @param {!Node} node A node.
* @param {string} name Attribute name.
* @return {*} Attribute value.
* @private
*/
goog.testing.dom.getAttributeValue_ = function(node, name) {
// These hacks avoid nondetermistic results in the following cases:
// IE7: document.createElement('input').height returns a random number.
// FF3: getAttribute('disabled') returns different value for <div disabled="">
// and <div disabled="disabled">
// WebKit: Two radio buttons with the same name can't be checked at the same
// time, even if only one of them is in the document.
if (goog.userAgent.WEBKIT && node.tagName == 'INPUT' &&
node['type'] == 'radio' && name == 'checked') {
return false;
}
return goog.isDef(node[name]) &&
typeof node.getAttribute(name) != typeof node[name] ?
node[name] : node.getAttribute(name);
};
/**
* Assert that the attributes of two Nodes are the same (ignoring any
* instances of the style attribute).
* @param {string} errorSuffix String to add to end of error messages.
* @param {Node} expectedNode The node whose attributes we are expecting.
* @param {Node} actualNode The node with the actual attributes.
* @param {boolean} strictAttributes If false, attributes that appear in
* expectedNode must also be in actualNode, but actualNode can have
* attributes not present in expectedNode. If true, expectedNode and
* actualNode must have the same set of attributes.
* @private
*/
goog.testing.dom.assertAttributesEqual_ = function(errorSuffix,
expectedNode, actualNode, strictAttributes) {
if (strictAttributes) {
goog.testing.dom.compareClassAttribute_(expectedNode, actualNode);
}
var expectedAttributes = expectedNode.attributes;
var actualAttributes = actualNode.attributes;
for (var i = 0, len = expectedAttributes.length; i < len; i++) {
var expectedName = expectedAttributes[i].name;
var expectedValue = goog.testing.dom.getAttributeValue_(expectedNode,
expectedName);
var actualAttribute = actualAttributes[expectedName];
var actualValue = goog.testing.dom.getAttributeValue_(actualNode,
expectedName);
// IE enumerates attribute names in the expected node that are not present,
// causing an undefined actualAttribute.
if (!expectedValue && !actualValue) {
continue;
}
if (expectedName == 'id' && goog.userAgent.IE) {
goog.testing.dom.compareIdAttributeForIe_(
/** @type {string} */ (expectedValue), actualAttribute,
strictAttributes, errorSuffix);
continue;
}
if (goog.testing.dom.ignoreAttribute_(expectedName)) {
continue;
}
assertNotUndefined('Expected to find attribute with name ' +
expectedName + ', in element ' +
goog.testing.dom.describeNode_(actualNode) + errorSuffix,
actualAttribute);
assertEquals('Expected attribute ' + expectedName +
' has a different value ' + errorSuffix,
expectedValue,
goog.testing.dom.getAttributeValue_(actualNode, actualAttribute.name));
}
if (strictAttributes) {
for (i = 0; i < actualAttributes.length; i++) {
var actualName = actualAttributes[i].name;
var actualAttribute = actualAttributes.getNamedItem(actualName);
if (!actualAttribute || goog.testing.dom.ignoreAttribute_(actualName)) {
continue;
}
assertNotUndefined('Unexpected attribute with name ' +
actualName + ' in element ' +
goog.testing.dom.describeNode_(actualNode) + errorSuffix,
expectedAttributes[actualName]);
}
}
};
/**
* Assert the class attribute of actualNode is the same as the one in
* expectedNode, ignoring classes that are useragents.
* @param {Node} expectedNode The DOM node whose class we expect.
* @param {Node} actualNode The DOM node with the actual class.
* @private
*/
goog.testing.dom.compareClassAttribute_ = function(expectedNode,
actualNode) {
var classes = goog.dom.classes.get(expectedNode);
var expectedClasses = [];
for (var i = 0, len = classes.length; i < len; i++) {
if (!(classes[i] in goog.userAgent)) {
expectedClasses.push(classes[i]);
}
}
expectedClasses.sort();
var actualClasses = goog.dom.classes.get(actualNode);
actualClasses.sort();
assertArrayEquals(
'Expected class was: ' + expectedClasses.join(' ') +
', but actual class was: ' + actualNode.className,
expectedClasses, actualClasses);
};
/**
* Set of attributes IE adds to elements randomly.
* @type {Object}
* @private
*/
goog.testing.dom.BAD_IE_ATTRIBUTES_ = goog.object.createSet(
'methods', 'CHECKED', 'dataFld', 'dataFormatAs', 'dataSrc');
/**
* Whether to ignore the attribute.
* @param {string} name Name of the attribute.
* @return {boolean} True if the attribute should be ignored.
* @private
*/
goog.testing.dom.ignoreAttribute_ = function(name) {
if (name == 'style' || name == 'class') {
return true;
}
return goog.userAgent.IE && goog.testing.dom.BAD_IE_ATTRIBUTES_[name];
};
/**
* Compare id attributes for IE. In IE, if an element lacks an id attribute
* in the original HTML, the element object will still have such an attribute,
* but its value will be the empty string.
* @param {string} expectedValue The expected value of the id attribute.
* @param {Attr} actualAttribute The actual id attribute.
* @param {boolean} strictAttributes Whether strict attribute checking should be
* done.
* @param {string} errorSuffix String to append to error messages.
* @private
*/
goog.testing.dom.compareIdAttributeForIe_ = function(expectedValue,
actualAttribute, strictAttributes, errorSuffix) {
if (expectedValue === '') {
if (strictAttributes) {
assertTrue('Unexpected attribute with name id in element ' +
errorSuffix, actualAttribute.value == '');
}
} else {
assertNotUndefined('Expected to find attribute with name id, in element ' +
errorSuffix, actualAttribute);
assertNotEquals('Expected to find attribute with name id, in element ' +
errorSuffix, '', actualAttribute.value);
assertEquals('Expected attribute has a different value ' + errorSuffix,
expectedValue, actualAttribute.value);
}
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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.
// All Rights Reserved.
/**
* @fileoverview A class representing a set of test functions that use
* asynchronous functions that cannot be meaningfully mocked.
*
* To create a Google-compatable JsUnit test using this test case, put the
* following snippet in your test:
*
* var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
*
* To make the test runner wait for your asynchronous behaviour, use:
*
* asyncTestCase.waitForAsync('Waiting for xhr to respond');
*
* The next test will not start until the following call is made, or a
* timeout occurs:
*
* asyncTestCase.continueTesting();
*
* There does NOT need to be a 1:1 mapping of waitForAsync calls and
* continueTesting calls. The next test will be run after a single call to
* continueTesting is made, as long as there is no subsequent call to
* waitForAsync in the same thread.
*
* Example:
* // Returning here would cause the next test to be run.
* asyncTestCase.waitForAsync('description 1');
* // Returning here would *not* cause the next test to be run.
* // Only effect of additional waitForAsync() calls is an updated
* // description in the case of a timeout.
* asyncTestCase.waitForAsync('updated description');
* asyncTestCase.continueTesting();
* // Returning here would cause the next test to be run.
* asyncTestCase.waitForAsync('just kidding, still running.');
* // Returning here would *not* cause the next test to be run.
*
* This class supports asynchronous behaviour in all test functions except for
* tearDownPage. If such support is needed, it can be added.
*
* Example Usage:
*
* var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall();
* // Optionally, set a longer-than-normal step timeout.
* asyncTestCase.stepTimeout = 30 * 1000;
*
* function testSetTimeout() {
* var step = 0;
* function stepCallback() {
* step++;
* switch (step) {
* case 1:
* var startTime = goog.now();
* asyncTestCase.waitForAsync('step 1');
* window.setTimeout(stepCallback, 100);
* break;
* case 2:
* assertTrue('Timeout fired too soon',
* goog.now() - startTime >= 100);
* asyncTestCase.waitForAsync('step 2');
* window.setTimeout(stepCallback, 100);
* break;
* case 3:
* assertTrue('Timeout fired too soon',
* goog.now() - startTime >= 200);
* asyncTestCase.continueTesting();
* break;
* default:
* fail('Unexpected call to stepCallback');
* }
* }
* stepCallback();
* }
*
* Known Issues:
* IE7 Exceptions:
* As the failingtest.html will show, it appears as though ie7 does not
* propagate an exception past a function called using the func.call()
* syntax. This causes case 3 of the failing tests (exceptions) to show up
* as timeouts in IE.
* window.onerror:
* This seems to catch errors only in ff2/ff3. It does not work in Safari or
* IE7. The consequence of this is that exceptions that would have been
* caught by window.onerror show up as timeouts.
*
* @author agrieve@google.com (Andrew Grieve)
*/
goog.provide('goog.testing.AsyncTestCase');
goog.provide('goog.testing.AsyncTestCase.ControlBreakingException');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.TestCase.Test');
goog.require('goog.testing.asserts');
/**
* A test case that is capable of running tests the contain asynchronous logic.
* @param {string=} opt_name A descriptive name for the test case.
* @extends {goog.testing.TestCase}
* @constructor
*/
goog.testing.AsyncTestCase = function(opt_name) {
goog.testing.TestCase.call(this, opt_name);
};
goog.inherits(goog.testing.AsyncTestCase, goog.testing.TestCase);
/**
* Represents result of top stack function call.
* @typedef {{controlBreakingExceptionThrown: boolean, message: string}}
* @private
*/
goog.testing.AsyncTestCase.TopStackFuncResult_;
/**
* An exception class used solely for control flow.
* @param {string=} opt_message Error message.
* @constructor
*/
goog.testing.AsyncTestCase.ControlBreakingException = function(opt_message) {
/**
* The exception message.
* @type {string}
*/
this.message = opt_message || '';
};
/**
* Return value for .toString().
* @type {string}
*/
goog.testing.AsyncTestCase.ControlBreakingException.TO_STRING =
'[AsyncTestCase.ControlBreakingException]';
/**
* Marks this object as a ControlBreakingException
* @type {boolean}
*/
goog.testing.AsyncTestCase.ControlBreakingException.prototype.
isControlBreakingException = true;
/** @override */
goog.testing.AsyncTestCase.ControlBreakingException.prototype.toString =
function() {
// This shows up in the console when the exception is not caught.
return goog.testing.AsyncTestCase.ControlBreakingException.TO_STRING;
};
/**
* How long to wait for a single step of a test to complete in milliseconds.
* A step starts when a call to waitForAsync() is made.
* @type {number}
*/
goog.testing.AsyncTestCase.prototype.stepTimeout = 1000;
/**
* How long to wait after a failed test before moving onto the next one.
* The purpose of this is to allow any pending async callbacks from the failing
* test to finish up and not cause the next test to fail.
* @type {number}
*/
goog.testing.AsyncTestCase.prototype.timeToSleepAfterFailure = 500;
/**
* Turn on extra logging to help debug failing async. tests.
* @type {boolean}
* @private
*/
goog.testing.AsyncTestCase.prototype.enableDebugLogs_ = false;
/**
* A reference to the original asserts.js assert_() function.
* @private
*/
goog.testing.AsyncTestCase.prototype.origAssert_;
/**
* A reference to the original asserts.js fail() function.
* @private
*/
goog.testing.AsyncTestCase.prototype.origFail_;
/**
* A reference to the original window.onerror function.
* @type {Function|undefined}
* @private
*/
goog.testing.AsyncTestCase.prototype.origOnError_;
/**
* The stage of the test we are currently on.
* @type {Function|undefined}}
* @private
*/
goog.testing.AsyncTestCase.prototype.curStepFunc_;
/**
* The name of the stage of the test we are currently on.
* @type {string}
* @private
*/
goog.testing.AsyncTestCase.prototype.curStepName_ = '';
/**
* The stage of the test we should run next.
* @type {Function|undefined}
* @private
*/
goog.testing.AsyncTestCase.prototype.nextStepFunc;
/**
* The name of the stage of the test we should run next.
* @type {string}
* @private
*/
goog.testing.AsyncTestCase.prototype.nextStepName_ = '';
/**
* The handle to the current setTimeout timer.
* @type {number}
* @private
*/
goog.testing.AsyncTestCase.prototype.timeoutHandle_ = 0;
/**
* Marks if the cleanUp() function has been called for the currently running
* test.
* @type {boolean}
* @private
*/
goog.testing.AsyncTestCase.prototype.cleanedUp_ = false;
/**
* The currently active test.
* @type {goog.testing.TestCase.Test|undefined}
* @protected
*/
goog.testing.AsyncTestCase.prototype.activeTest;
/**
* A flag to prevent recursive exception handling.
* @type {boolean}
* @private
*/
goog.testing.AsyncTestCase.prototype.inException_ = false;
/**
* Flag used to determine if we can move to the next step in the testing loop.
* @type {boolean}
* @private
*/
goog.testing.AsyncTestCase.prototype.isReady_ = true;
/**
* Flag that tells us if there is a function in the call stack that will make
* a call to pump_().
* @type {boolean}
* @private
*/
goog.testing.AsyncTestCase.prototype.returnWillPump_ = false;
/**
* The number of times we have thrown a ControlBreakingException so that we
* know not to complain in our window.onerror handler. In Webkit, window.onerror
* is not supported, and so this counter will keep going up but we won't care
* about it.
* @type {number}
* @private
*/
goog.testing.AsyncTestCase.prototype.numControlExceptionsExpected_ = 0;
/**
* The current step name.
* @return {!string} Step name.
* @protected
*/
goog.testing.AsyncTestCase.prototype.getCurrentStepName = function() {
return this.curStepName_;
};
/**
* Preferred way of creating an AsyncTestCase. Creates one and initializes it
* with the G_testRunner.
* @param {string=} opt_name A descriptive name for the test case.
* @return {!goog.testing.AsyncTestCase} The created AsyncTestCase.
*/
goog.testing.AsyncTestCase.createAndInstall = function(opt_name) {
var asyncTestCase = new goog.testing.AsyncTestCase(opt_name);
goog.testing.TestCase.initializeTestRunner(asyncTestCase);
return asyncTestCase;
};
/**
* Informs the testcase not to continue to the next step in the test cycle
* until continueTesting is called.
* @param {string=} opt_name A description of what we are waiting for.
*/
goog.testing.AsyncTestCase.prototype.waitForAsync = function(opt_name) {
this.isReady_ = false;
this.curStepName_ = opt_name || this.curStepName_;
// Reset the timer that tracks if the async test takes too long.
this.stopTimeoutTimer_();
this.startTimeoutTimer_();
};
/**
* Continue with the next step in the test cycle.
*/
goog.testing.AsyncTestCase.prototype.continueTesting = function() {
if (!this.isReady_) {
// We are a potential entry point, so we pump.
this.isReady_ = true;
this.stopTimeoutTimer_();
// Run this in a setTimeout so that the caller has a chance to call
// waitForAsync() again before we continue.
this.timeout(goog.bind(this.pump_, this, null), 0);
}
};
/**
* Handles an exception thrown by a test.
* @param {*=} opt_e The exception object associated with the failure
* or a string.
* @throws Always throws a ControlBreakingException.
*/
goog.testing.AsyncTestCase.prototype.doAsyncError = function(opt_e) {
// If we've caught an exception that we threw, then just pass it along. This
// can happen if doAsyncError() was called from a call to assert and then
// again by pump_().
if (opt_e && opt_e.isControlBreakingException) {
throw opt_e;
}
// Prevent another timeout error from triggering for this test step.
this.stopTimeoutTimer_();
// doError() uses test.name. Here, we create a dummy test and give it a more
// helpful name based on the step we're currently on.
var fakeTestObj = new goog.testing.TestCase.Test(this.curStepName_,
goog.nullFunction);
if (this.activeTest) {
fakeTestObj.name = this.activeTest.name + ' [' + fakeTestObj.name + ']';
}
if (this.activeTest) {
// Note: if the test has an error, and then tearDown has an error, they will
// both be reported.
this.doError(fakeTestObj, opt_e);
} else {
this.exceptionBeforeTest = opt_e;
}
// This is a potential entry point, so we pump. We also add in a bit of a
// delay to try and prevent any async behavior from the failed test from
// causing the next test to fail.
this.timeout(goog.bind(this.pump_, this, this.doAsyncErrorTearDown_),
this.timeToSleepAfterFailure);
// We just caught an exception, so we do not want the code above us on the
// stack to continue executing. If pump_ is in our call-stack, then it will
// batch together multiple errors, so we only increment the count if pump_ is
// not in the stack and let pump_ increment the count when it batches them.
if (!this.returnWillPump_) {
this.numControlExceptionsExpected_ += 1;
this.dbgLog_('doAsynError: numControlExceptionsExpected_ = ' +
this.numControlExceptionsExpected_ + ' and throwing exception.');
}
// Copy the error message to ControlBreakingException.
var message = '';
if (typeof opt_e == 'string') {
message = opt_e;
} else if (opt_e && opt_e.message) {
message = opt_e.message;
}
throw new goog.testing.AsyncTestCase.ControlBreakingException(message);
};
/**
* Sets up the test page and then waits until the test case has been marked
* as ready before executing the tests.
* @override
*/
goog.testing.AsyncTestCase.prototype.runTests = function() {
this.hookAssert_();
this.hookOnError_();
this.setNextStep_(this.doSetUpPage_, 'setUpPage');
// We are an entry point, so we pump.
this.pump_();
};
/**
* Starts the tests.
* @override
*/
goog.testing.AsyncTestCase.prototype.cycleTests = function() {
// We are an entry point, so we pump.
this.saveMessage('Start');
this.setNextStep_(this.doIteration_, 'doIteration');
this.pump_();
};
/**
* Finalizes the test case, called when the tests have finished executing.
* @override
*/
goog.testing.AsyncTestCase.prototype.finalize = function() {
this.unhookAll_();
this.setNextStep_(null, 'finalized');
goog.testing.AsyncTestCase.superClass_.finalize.call(this);
};
/**
* Enables verbose logging of what is happening inside of the AsyncTestCase.
*/
goog.testing.AsyncTestCase.prototype.enableDebugLogging = function() {
this.enableDebugLogs_ = true;
};
/**
* Logs the given debug message to the console (when enabled).
* @param {string} message The message to log.
* @private
*/
goog.testing.AsyncTestCase.prototype.dbgLog_ = function(message) {
if (this.enableDebugLogs_) {
this.log('AsyncTestCase - ' + message);
}
};
/**
* Wraps doAsyncError() for when we are sure that the test runner has no user
* code above it in the stack.
* @param {string|Error=} opt_e The exception object associated with the
* failure or a string.
* @private
*/
goog.testing.AsyncTestCase.prototype.doTopOfStackAsyncError_ =
function(opt_e) {
/** @preserveTry */
try {
this.doAsyncError(opt_e);
} catch (e) {
// We know that we are on the top of the stack, so there is no need to
// throw this exception in this case.
if (e.isControlBreakingException) {
this.numControlExceptionsExpected_ -= 1;
this.dbgLog_('doTopOfStackAsyncError_: numControlExceptionsExpected_ = ' +
this.numControlExceptionsExpected_ + ' and catching exception.');
} else {
throw e;
}
}
};
/**
* Calls the tearDown function, catching any errors, and then moves on to
* the next step in the testing cycle.
* @private
*/
goog.testing.AsyncTestCase.prototype.doAsyncErrorTearDown_ = function() {
if (this.inException_) {
// We get here if tearDown is throwing the error.
// Upon calling continueTesting, the inline function 'doAsyncError' (set
// below) is run.
this.continueTesting();
} else {
this.inException_ = true;
this.isReady_ = true;
// The continue point is different depending on if the error happened in
// setUpPage() or in setUp()/test*()/tearDown().
var stepFuncAfterError = this.nextStepFunc_;
var stepNameAfterError = 'TestCase.execute (after error)';
if (this.activeTest) {
stepFuncAfterError = this.doIteration_;
stepNameAfterError = 'doIteration (after error)';
}
// We must set the next step before calling tearDown.
this.setNextStep_(function() {
this.inException_ = false;
// This is null when an error happens in setUpPage.
this.setNextStep_(stepFuncAfterError, stepNameAfterError);
}, 'doAsyncError');
// Call the test's tearDown().
if (!this.cleanedUp_) {
this.cleanedUp_ = true;
this.tearDown();
}
}
};
/**
* Replaces the asserts.js assert_() and fail() functions with a wrappers to
* catch the exceptions.
* @private
*/
goog.testing.AsyncTestCase.prototype.hookAssert_ = function() {
if (!this.origAssert_) {
this.origAssert_ = _assert;
this.origFail_ = fail;
var self = this;
_assert = function() {
/** @preserveTry */
try {
self.origAssert_.apply(this, arguments);
} catch (e) {
self.dbgLog_('Wrapping failed assert()');
self.doAsyncError(e);
}
};
fail = function() {
/** @preserveTry */
try {
self.origFail_.apply(this, arguments);
} catch (e) {
self.dbgLog_('Wrapping fail()');
self.doAsyncError(e);
}
};
}
};
/**
* Sets a window.onerror handler for catching exceptions that happen in async
* callbacks. Note that as of Safari 3.1, Safari does not support this.
* @private
*/
goog.testing.AsyncTestCase.prototype.hookOnError_ = function() {
if (!this.origOnError_) {
this.origOnError_ = window.onerror;
var self = this;
window.onerror = function(error, url, line) {
// Ignore exceptions that we threw on purpose.
var cbe =
goog.testing.AsyncTestCase.ControlBreakingException.TO_STRING;
if (String(error).indexOf(cbe) != -1 &&
self.numControlExceptionsExpected_) {
self.numControlExceptionsExpected_ -= 1;
self.dbgLog_('window.onerror: numControlExceptionsExpected_ = ' +
self.numControlExceptionsExpected_ + ' and ignoring exception. ' +
error);
// Tell the browser not to compain about the error.
return true;
} else {
self.dbgLog_('window.onerror caught exception.');
var message = error + '\nURL: ' + url + '\nLine: ' + line;
self.doTopOfStackAsyncError_(message);
// Tell the browser to complain about the error.
return false;
}
};
}
};
/**
* Unhooks window.onerror and _assert.
* @private
*/
goog.testing.AsyncTestCase.prototype.unhookAll_ = function() {
if (this.origOnError_) {
window.onerror = this.origOnError_;
this.origOnError_ = null;
_assert = this.origAssert_;
this.origAssert_ = null;
fail = this.origFail_;
this.origFail_ = null;
}
};
/**
* Enables the timeout timer. This timer fires unless continueTesting is
* called.
* @private
*/
goog.testing.AsyncTestCase.prototype.startTimeoutTimer_ = function() {
if (!this.timeoutHandle_ && this.stepTimeout > 0) {
this.timeoutHandle_ = this.timeout(goog.bind(function() {
this.dbgLog_('Timeout timer fired with id ' + this.timeoutHandle_);
this.timeoutHandle_ = 0;
this.doTopOfStackAsyncError_('Timed out while waiting for ' +
'continueTesting() to be called.');
}, this, null), this.stepTimeout);
this.dbgLog_('Started timeout timer with id ' + this.timeoutHandle_);
}
};
/**
* Disables the timeout timer.
* @private
*/
goog.testing.AsyncTestCase.prototype.stopTimeoutTimer_ = function() {
if (this.timeoutHandle_) {
this.dbgLog_('Clearing timeout timer with id ' + this.timeoutHandle_);
this.clearTimeout(this.timeoutHandle_);
this.timeoutHandle_ = 0;
}
};
/**
* Sets the next function to call in our sequence of async callbacks.
* @param {Function} func The function that executes the next step.
* @param {string} name A description of the next step.
* @private
*/
goog.testing.AsyncTestCase.prototype.setNextStep_ = function(func, name) {
this.nextStepFunc_ = func && goog.bind(func, this);
this.nextStepName_ = name;
};
/**
* Calls the given function, redirecting any exceptions to doAsyncError.
* @param {Function} func The function to call.
* @return {!goog.testing.AsyncTestCase.TopStackFuncResult_} Returns a
* TopStackFuncResult_.
* @private
*/
goog.testing.AsyncTestCase.prototype.callTopOfStackFunc_ = function(func) {
/** @preserveTry */
try {
func.call(this);
return {controlBreakingExceptionThrown: false, message: ''};
} catch (e) {
this.dbgLog_('Caught exception in callTopOfStackFunc_');
/** @preserveTry */
try {
this.doAsyncError(e);
return {controlBreakingExceptionThrown: false, message: ''};
} catch (e2) {
if (!e2.isControlBreakingException) {
throw e2;
}
return {controlBreakingExceptionThrown: true, message: e2.message};
}
}
};
/**
* Calls the next callback when the isReady_ flag is true.
* @param {Function=} opt_doFirst A function to call before pumping.
* @private
* @throws Throws a ControlBreakingException if there were any failing steps.
*/
goog.testing.AsyncTestCase.prototype.pump_ = function(opt_doFirst) {
// If this function is already above us in the call-stack, then we should
// return rather than pumping in order to minimize call-stack depth.
if (!this.returnWillPump_) {
this.setBatchTime(this.now());
this.returnWillPump_ = true;
var topFuncResult = {};
if (opt_doFirst) {
topFuncResult = this.callTopOfStackFunc_(opt_doFirst);
}
// Note: we don't check for this.running here because it is not set to true
// while executing setUpPage and tearDownPage.
// Also, if isReady_ is false, then one of two things will happen:
// 1. Our timeout callback will be called.
// 2. The tests will call continueTesting(), which will call pump_() again.
while (this.isReady_ && this.nextStepFunc_ &&
!topFuncResult.controlBreakingExceptionThrown) {
this.curStepFunc_ = this.nextStepFunc_;
this.curStepName_ = this.nextStepName_;
this.nextStepFunc_ = null;
this.nextStepName_ = '';
this.dbgLog_('Performing step: ' + this.curStepName_);
topFuncResult =
this.callTopOfStackFunc_(/** @type {Function} */(this.curStepFunc_));
// If the max run time is exceeded call this function again async so as
// not to block the browser.
var delta = this.now() - this.getBatchTime();
if (delta > goog.testing.TestCase.MAX_RUN_TIME &&
!topFuncResult.controlBreakingExceptionThrown) {
this.saveMessage('Breaking async');
var self = this;
this.timeout(function() { self.pump_(); }, 100);
break;
}
}
this.returnWillPump_ = false;
} else if (opt_doFirst) {
opt_doFirst.call(this);
}
};
/**
* Sets up the test page and then waits untill the test case has been marked
* as ready before executing the tests.
* @private
*/
goog.testing.AsyncTestCase.prototype.doSetUpPage_ = function() {
this.setNextStep_(this.execute, 'TestCase.execute');
this.setUpPage();
};
/**
* Step 1: Move to the next test.
* @private
*/
goog.testing.AsyncTestCase.prototype.doIteration_ = function() {
this.activeTest = this.next();
if (this.activeTest && this.running) {
this.result_.runCount++;
// If this test should be marked as having failed, doIteration will go
// straight to the next test.
if (this.maybeFailTestEarly(this.activeTest)) {
this.setNextStep_(this.doIteration_, 'doIteration');
} else {
this.setNextStep_(this.doSetUp_, 'setUp');
}
} else {
// All tests done.
this.finalize();
}
};
/**
* Step 2: Call setUp().
* @private
*/
goog.testing.AsyncTestCase.prototype.doSetUp_ = function() {
this.log('Running test: ' + this.activeTest.name);
this.cleanedUp_ = false;
this.setNextStep_(this.doExecute_, this.activeTest.name);
this.setUp();
};
/**
* Step 3: Call test.execute().
* @private
*/
goog.testing.AsyncTestCase.prototype.doExecute_ = function() {
this.setNextStep_(this.doTearDown_, 'tearDown');
this.activeTest.execute();
};
/**
* Step 4: Call tearDown().
* @private
*/
goog.testing.AsyncTestCase.prototype.doTearDown_ = function() {
this.cleanedUp_ = true;
this.setNextStep_(this.doNext_, 'doNext');
this.tearDown();
};
/**
* Step 5: Call doSuccess()
* @private
*/
goog.testing.AsyncTestCase.prototype.doNext_ = function() {
this.setNextStep_(this.doIteration_, 'doIteration');
this.doSuccess(/** @type {goog.testing.TestCase.Test} */(this.activeTest));
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Utility for running multiple test files that utilize the same
* interface as goog.testing.TestRunner. Each test is run in series and their
* results aggregated. The main usecase for the MultiTestRunner is to allow
* the testing of all tests in a project locally.
*
*/
goog.provide('goog.testing.MultiTestRunner');
goog.provide('goog.testing.MultiTestRunner.TestFrame');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.events.EventHandler');
goog.require('goog.functions');
goog.require('goog.string');
goog.require('goog.ui.Component');
goog.require('goog.ui.ServerChart');
goog.require('goog.ui.TableSorter');
/**
* A component for running multiple tests within the browser.
* @param {goog.dom.DomHelper=} opt_domHelper A DOM helper.
* @extends {goog.ui.Component}
* @constructor
*/
goog.testing.MultiTestRunner = function(opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Array of tests to execute, when combined with the base path this should be
* a relative path to the test from the page containing the multi testrunner.
* @type {Array.<string>}
* @private
*/
this.allTests_ = [];
/**
* Tests that match the filter function.
* @type {Array.<string>}
* @private
*/
this.activeTests_ = [];
/**
* An event handler for handling events.
* @type {goog.events.EventHandler}
* @private
*/
this.eh_ = new goog.events.EventHandler(this);
/**
* A table sorter for the stats.
* @type {goog.ui.TableSorter}
* @private
*/
this.tableSorter_ = new goog.ui.TableSorter(this.dom_);
};
goog.inherits(goog.testing.MultiTestRunner, goog.ui.Component);
/**
* Default maximimum amount of time to spend at each stage of the test.
* @type {number}
*/
goog.testing.MultiTestRunner.DEFAULT_TIMEOUT_MS = 45 * 1000;
/**
* Messages corresponding to the numeric states.
* @type {Array.<string>}
*/
goog.testing.MultiTestRunner.STATES = [
'waiting for test runner',
'initializing tests',
'waiting for tests to finish'
];
/**
* The test suite's name.
* @type {string} name
* @private
*/
goog.testing.MultiTestRunner.prototype.name_ = '';
/**
* The base path used to resolve files within the allTests_ array.
* @type {string}
* @private
*/
goog.testing.MultiTestRunner.prototype.basePath_ = '';
/**
* A set of tests that have finished. All extant keys map to true.
* @type {Object.<boolean>}
* @private
*/
goog.testing.MultiTestRunner.prototype.finished_ = null;
/**
* Whether the report should contain verbose information about the passes.
* @type {boolean}
* @private
*/
goog.testing.MultiTestRunner.prototype.verbosePasses_ = false;
/**
* Whether to hide passing tests completely in the report, makes verbosePasses_
* obsolete.
* @type {boolean}
* @private
*/
goog.testing.MultiTestRunner.prototype.hidePasses_ = false;
/**
* Flag used to tell the test runner to stop after the current test.
* @type {boolean}
* @private
*/
goog.testing.MultiTestRunner.prototype.stopped_ = false;
/**
* Flag indicating whether the test runner is active.
* @type {boolean}
* @private
*/
goog.testing.MultiTestRunner.prototype.active_ = false;
/**
* Index of the next test to run.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.startedCount_ = 0;
/**
* Count of the results received so far.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.resultCount_ = 0;
/**
* Number of passes so far.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.passes_ = 0;
/**
* Timestamp for the current start time.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.startTime_ = 0;
/**
* Only tests whose paths patch this filter function will be
* executed.
* @type {function(string): boolean}
* @private
*/
goog.testing.MultiTestRunner.prototype.filterFn_ = goog.functions.TRUE;
/**
* Number of milliseconds to wait for loading and initialization steps.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.timeoutMs_ =
goog.testing.MultiTestRunner.DEFAULT_TIMEOUT_MS;
/**
* An array of objects containing stats about the tests.
* @type {Array.<Object>?}
* @private
*/
goog.testing.MultiTestRunner.prototype.stats_ = null;
/**
* Reference to the start button element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.startButtonEl_ = null;
/**
* Reference to the stop button element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.stopButtonEl_ = null;
/**
* Reference to the log element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.logEl_ = null;
/**
* Reference to the report element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.reportEl_ = null;
/**
* Reference to the stats element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.statsEl_ = null;
/**
* Reference to the progress bar's element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.progressEl_ = null;
/**
* Reference to the progress bar's inner row element.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.progressRow_ = null;
/**
* Reference to the log tab.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.logTabEl_ = null;
/**
* Reference to the report tab.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.reportTabEl_ = null;
/**
* Reference to the stats tab.
* @type {Element}
* @private
*/
goog.testing.MultiTestRunner.prototype.statsTabEl_ = null;
/**
* The number of tests to run at a time.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.poolSize_ = 1;
/**
* The size of the stats bucket for the number of files loaded histogram.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.numFilesStatsBucketSize_ = 20;
/**
* The size of the stats bucket in ms for the run time histogram.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.prototype.runTimeStatsBucketSize_ = 500;
/**
* Sets the name for the test suite.
* @param {string} name The suite's name.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setName = function(name) {
this.name_ = name;
return this;
};
/**
* Returns the name for the test suite.
* @return {string} The name for the test suite.
*/
goog.testing.MultiTestRunner.prototype.getName = function() {
return this.name_;
};
/**
* Sets the basepath that tests added using addTests are resolved with.
* @param {string} path The relative basepath.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setBasePath = function(path) {
this.basePath_ = path;
return this;
};
/**
* Returns the basepath that tests added using addTests are resolved with.
* @return {string} The basepath that tests added using addTests are resolved
* with.
*/
goog.testing.MultiTestRunner.prototype.getBasePath = function() {
return this.basePath_;
};
/**
* Sets whether the report should contain verbose information for tests that
* pass.
* @param {boolean} verbose Whether report should be verbose.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setVerbosePasses = function(verbose) {
this.verbosePasses_ = verbose;
return this;
};
/**
* Returns whether the report should contain verbose information for tests that
* pass.
* @return {boolean} Whether the report should contain verbose information for
* tests that pass.
*/
goog.testing.MultiTestRunner.prototype.getVerbosePasses = function() {
return this.verbosePasses_;
};
/**
* Sets whether the report should contain passing tests at all, makes
* setVerbosePasses obsolete.
* @param {boolean} hide Whether report should not contain passing tests.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setHidePasses = function(hide) {
this.hidePasses_ = hide;
return this;
};
/**
* Returns whether the report should contain passing tests at all, makes
* setVerbosePasses obsolete.
* @return {boolean} Whether the report should contain passing tests at all,
* makes setVerbosePasses obsolete.
*/
goog.testing.MultiTestRunner.prototype.getHidePasses = function() {
return this.hidePasses_;
};
/**
* Sets the bucket sizes for the histograms.
* @param {number} f Bucket size for num files loaded histogram.
* @param {number} t Bucket size for run time histogram.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setStatsBucketSizes = function(f, t) {
this.numFilesStatsBucketSize_ = f;
this.runTimeStatsBucketSize_ = t;
return this;
};
/**
* Sets the number of milliseconds to wait for the page to load, initialize and
* run the tests.
* @param {number} timeout Time in milliseconds.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setTimeout = function(timeout) {
this.timeoutMs_ = timeout;
return this;
};
/**
* Returns the number of milliseconds to wait for the page to load, initialize
* and run the tests.
* @return {number} The number of milliseconds to wait for the page to load,
* initialize and run the tests.
*/
goog.testing.MultiTestRunner.prototype.getTimeout = function() {
return this.timeoutMs_;
};
/**
* Sets the number of tests that can be run at the same time. This only improves
* performance due to the amount of time spent loading the tests.
* @param {number} size The number of tests to run at a time.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setPoolSize = function(size) {
this.poolSize_ = size;
return this;
};
/**
* Returns the number of tests that can be run at the same time. This only
* improves performance due to the amount of time spent loading the tests.
* @return {number} The number of tests that can be run at the same time. This
* only improves performance due to the amount of time spent loading the
* tests.
*/
goog.testing.MultiTestRunner.prototype.getPoolSize = function() {
return this.poolSize_;
};
/**
* Sets a filter function. Only test paths that match the filter function
* will be executed.
* @param {function(string): boolean} filterFn Filters test paths.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.setFilterFunction = function(filterFn) {
this.filterFn_ = filterFn;
return this;
};
/**
* Returns a filter function. Only test paths that match the filter function
* will be executed.
* @return {function(string): boolean} A filter function. Only test paths that
* match the filter function will be executed.
*/
goog.testing.MultiTestRunner.prototype.getFilterFunction = function() {
return this.filterFn_;
};
/**
* Adds an array of tests to the tests that the test runner should execute.
* @param {Array.<string>} tests Adds tests to the test runner.
* @return {goog.testing.MultiTestRunner} Instance for chaining.
*/
goog.testing.MultiTestRunner.prototype.addTests = function(tests) {
goog.array.extend(this.allTests_, tests);
return this;
};
/**
* Returns the list of all tests added to the runner.
* @return {Array.<string>} The list of all tests added to the runner.
*/
goog.testing.MultiTestRunner.prototype.getAllTests = function() {
return this.allTests_;
};
/**
* Returns the list of tests that will be run when start() is called.
* @return {Array.<string>} The list of tests that will be run when start() is
* called.
*/
goog.testing.MultiTestRunner.prototype.getTestsToRun = function() {
return goog.array.filter(this.allTests_, this.filterFn_);
};
/**
* Returns a list of tests from runner that have been marked as failed.
* @return {Array.<string>} A list of tests from runner that have been marked as
* failed.
*/
goog.testing.MultiTestRunner.prototype.getTestsThatFailed = function() {
var stats = this.stats_;
var failedTests = [];
if (stats) {
for (var i = 0, stat; stat = stats[i]; i++) {
if (!stat.success) {
failedTests.push(stat.testFile);
}
}
}
return failedTests;
};
/**
* Deletes and re-creates the progress table inside the progess element.
* @private
*/
goog.testing.MultiTestRunner.prototype.resetProgressDom_ = function() {
goog.dom.removeChildren(this.progressEl_);
var progressTable = this.dom_.createDom('table');
var progressTBody = this.dom_.createDom('tbody');
this.progressRow_ = this.dom_.createDom('tr');
for (var i = 0; i < this.activeTests_.length; i++) {
var progressCell = this.dom_.createDom('td');
this.progressRow_.appendChild(progressCell);
}
progressTBody.appendChild(this.progressRow_);
progressTable.appendChild(progressTBody);
this.progressEl_.appendChild(progressTable);
};
/** @override */
goog.testing.MultiTestRunner.prototype.createDom = function() {
goog.testing.MultiTestRunner.superClass_.createDom.call(this);
var el = this.getElement();
el.className = goog.getCssName('goog-testrunner');
this.progressEl_ = this.dom_.createDom('div');
this.progressEl_.className = goog.getCssName('goog-testrunner-progress');
el.appendChild(this.progressEl_);
var buttons = this.dom_.createDom('div');
buttons.className = goog.getCssName('goog-testrunner-buttons');
this.startButtonEl_ = this.dom_.createDom('button', null, 'Start');
this.stopButtonEl_ =
this.dom_.createDom('button', {'disabled': true}, 'Stop');
buttons.appendChild(this.startButtonEl_);
buttons.appendChild(this.stopButtonEl_);
el.appendChild(buttons);
this.eh_.listen(this.startButtonEl_, 'click',
this.onStartClicked_);
this.eh_.listen(this.stopButtonEl_, 'click',
this.onStopClicked_);
this.logEl_ = this.dom_.createElement('div');
this.logEl_.className = goog.getCssName('goog-testrunner-log');
el.appendChild(this.logEl_);
this.reportEl_ = this.dom_.createElement('div');
this.reportEl_.className = goog.getCssName('goog-testrunner-report');
this.reportEl_.style.display = 'none';
el.appendChild(this.reportEl_);
this.statsEl_ = this.dom_.createElement('div');
this.statsEl_.className = goog.getCssName('goog-testrunner-stats');
this.statsEl_.style.display = 'none';
el.appendChild(this.statsEl_);
this.logTabEl_ = this.dom_.createDom('div', null, 'Log');
this.logTabEl_.className = goog.getCssName('goog-testrunner-logtab') + ' ' +
goog.getCssName('goog-testrunner-activetab');
el.appendChild(this.logTabEl_);
this.reportTabEl_ = this.dom_.createDom('div', null, 'Report');
this.reportTabEl_.className = goog.getCssName('goog-testrunner-reporttab');
el.appendChild(this.reportTabEl_);
this.statsTabEl_ = this.dom_.createDom('div', null, 'Stats');
this.statsTabEl_.className = goog.getCssName('goog-testrunner-statstab');
el.appendChild(this.statsTabEl_);
this.eh_.listen(this.logTabEl_, 'click', this.onLogTabClicked_);
this.eh_.listen(this.reportTabEl_, 'click', this.onReportTabClicked_);
this.eh_.listen(this.statsTabEl_, 'click', this.onStatsTabClicked_);
};
/** @override */
goog.testing.MultiTestRunner.prototype.disposeInternal = function() {
goog.testing.MultiTestRunner.superClass_.disposeInternal.call(this);
this.tableSorter_.dispose();
this.eh_.dispose();
this.startButtonEl_ = null;
this.stopButtonEl_ = null;
this.logEl_ = null;
this.reportEl_ = null;
this.progressEl_ = null;
this.logTabEl_ = null;
this.reportTabEl_ = null;
this.statsTabEl_ = null;
this.statsEl_ = null;
};
/**
* Starts executing the tests.
*/
goog.testing.MultiTestRunner.prototype.start = function() {
this.startButtonEl_.disabled = true;
this.stopButtonEl_.disabled = false;
this.stopped_ = false;
this.active_ = true;
this.finished_ = {};
this.activeTests_ = this.getTestsToRun();
this.startedCount_ = 0;
this.resultCount_ = 0;
this.passes_ = 0;
this.stats_ = [];
this.startTime_ = goog.now();
this.resetProgressDom_();
goog.dom.removeChildren(this.logEl_);
this.resetReport_();
this.clearStats_();
this.showTab_(0);
// Ensure the pool isn't too big.
while (this.getChildCount() > this.poolSize_) {
this.removeChildAt(0, true).dispose();
}
// Start a test in each runner.
for (var i = 0; i < this.poolSize_; i++) {
if (i >= this.getChildCount()) {
var testFrame = new goog.testing.MultiTestRunner.TestFrame(
this.basePath_, this.timeoutMs_, this.verbosePasses_, this.dom_);
this.addChild(testFrame, true);
}
this.runNextTest_(
/** @type {goog.testing.MultiTestRunner.TestFrame} */
(this.getChildAt(i)));
}
};
/**
* Logs a message to the log window.
* @param {string} msg A message to log.
*/
goog.testing.MultiTestRunner.prototype.log = function(msg) {
if (msg != '.') {
msg = this.getTimeStamp_() + ' : ' + msg;
}
this.logEl_.appendChild(this.dom_.createDom('div', null, msg));
// Autoscroll if we're near the bottom.
var top = this.logEl_.scrollTop;
var height = this.logEl_.scrollHeight - this.logEl_.offsetHeight;
if (top == 0 || top > height - 50) {
this.logEl_.scrollTop = height;
}
};
/**
* Processes a result returned from a TestFrame. If there are tests remaining
* it will trigger the next one to be run, otherwise if there are no tests and
* all results have been recieved then it will call finish.
* @param {goog.testing.MultiTestRunner.TestFrame} frame The frame that just
* finished.
*/
goog.testing.MultiTestRunner.prototype.processResult = function(frame) {
var success = frame.isSuccess();
var report = frame.getReport();
var test = frame.getTestFile();
this.stats_.push(frame.getStats());
this.finished_[test] = true;
var prefix = success ? '' : '*** FAILURE *** ';
this.log(prefix +
this.trimFileName_(test) + ' : ' + (success ? 'Passed' : 'Failed'));
this.resultCount_++;
if (success) {
this.passes_++;
}
this.drawProgressSegment_(test, success);
this.writeCurrentSummary_();
if (!(success && this.hidePasses_)) {
this.drawTestResult_(test, success, report);
}
if (!this.stopped_ && this.startedCount_ < this.activeTests_.length) {
this.runNextTest_(frame);
} else if (this.resultCount_ == this.activeTests_.length) {
this.finish_();
}
};
/**
* Runs the next available test, if there are any left.
* @param {goog.testing.MultiTestRunner.TestFrame} frame Where to run the test.
* @private
*/
goog.testing.MultiTestRunner.prototype.runNextTest_ = function(frame) {
if (this.startedCount_ < this.activeTests_.length) {
var nextTest = this.activeTests_[this.startedCount_++];
this.log(this.trimFileName_(nextTest) + ' : Loading');
frame.runTest(nextTest);
}
};
/**
* Handles the test finishing, processing the results and rendering the report.
* @private
*/
goog.testing.MultiTestRunner.prototype.finish_ = function() {
if (this.stopped_) {
this.log('Stopped');
} else {
this.log('Finished');
}
this.startButtonEl_.disabled = false;
this.stopButtonEl_.disabled = true;
this.active_ = false;
this.showTab_(1);
this.drawStats_();
// Remove all the test frames
while (this.getChildCount() > 0) {
this.removeChildAt(0, true).dispose();
}
// Compute tests that did not finish before the stop button was hit.
var unfinished = [];
for (var i = 0; i < this.activeTests_.length; i++) {
var test = this.activeTests_[i];
if (!this.finished_[test]) {
unfinished.push(test);
}
}
if (unfinished.length) {
this.reportEl_.appendChild(goog.dom.createDom('pre', undefined,
'Theses tests did not finish:\n' + unfinished.join('\n')));
}
};
/**
* Resets the report, clearing out all children and drawing the initial summary.
* @private
*/
goog.testing.MultiTestRunner.prototype.resetReport_ = function() {
goog.dom.removeChildren(this.reportEl_);
var summary = this.dom_.createDom('div');
summary.className = goog.getCssName('goog-testrunner-progress-summary');
this.reportEl_.appendChild(summary);
this.writeCurrentSummary_();
};
/**
* Draws the stats for the test run.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawStats_ = function() {
this.drawFilesHistogram_();
// Only show time stats if pool size is 1, otherwise times are wrong.
if (this.poolSize_ == 1) {
this.drawRunTimePie_();
this.drawTimeHistogram_();
}
this.drawWorstTestsTable_();
};
/**
* Draws the histogram showing number of files loaded.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawFilesHistogram_ = function() {
this.drawStatsHistogram_(
'numFilesLoaded',
this.numFilesStatsBucketSize_,
goog.functions.identity,
500,
'Histogram showing distribution of\nnumber of files loaded per test');
};
/**
* Draws the histogram showing how long each test took to complete.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawTimeHistogram_ = function() {
this.drawStatsHistogram_(
'totalTime',
this.runTimeStatsBucketSize_,
function(x) { return x / 1000; },
500,
'Histogram showing distribution of\ntime spent running tests in s');
};
/**
* Draws a stats histogram.
* @param {string} statsField Field of the stats object to graph.
* @param {number} bucketSize The size for the histogram's buckets.
* @param {function(number, ...[*]): *} valueTransformFn Function for
* transforming the x-labels value for display.
* @param {number} width The width in pixels of the graph.
* @param {string} title The graph's title.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawStatsHistogram_ = function(
statsField, bucketSize, valueTransformFn, width, title) {
var hist = {}, data = [], xlabels = [], ylabels = [];
var max = 0;
for (var i = 0; i < this.stats_.length; i++) {
var num = this.stats_[i][statsField];
var bucket = Math.floor(num / bucketSize) * bucketSize;
if (bucket > max) {
max = bucket;
}
if (!hist[bucket]) {
hist[bucket] = 1;
} else {
hist[bucket]++;
}
}
var maxBucketSize = 0;
for (var i = 0; i <= max; i += bucketSize) {
xlabels.push(valueTransformFn(i));
var count = hist[i] || 0;
if (count > maxBucketSize) {
maxBucketSize = count;
}
data.push(count);
}
var diff = Math.max(1, Math.ceil(maxBucketSize / 10));
for (var i = 0; i <= maxBucketSize; i += diff) {
ylabels.push(i);
}
var chart = new goog.ui.ServerChart(
goog.ui.ServerChart.ChartType.VERTICAL_STACKED_BAR, width, 250);
chart.setTitle(title);
chart.addDataSet(data, 'ff9900');
chart.setLeftLabels(ylabels);
chart.setGridY(ylabels.length - 1);
chart.setXLabels(xlabels);
chart.render(this.statsEl_);
};
/**
* Draws a pie chart showing the percentage of time spent running the tests
* compared to loading them etc.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawRunTimePie_ = function() {
var totalTime = 0, runTime = 0;
for (var i = 0; i < this.stats_.length; i++) {
var stat = this.stats_[i];
totalTime += stat.totalTime;
runTime += stat.runTime;
}
var loadTime = totalTime - runTime;
var pie = new goog.ui.ServerChart(
goog.ui.ServerChart.ChartType.PIE, 500, 250);
pie.setMinValue(0);
pie.setMaxValue(totalTime);
pie.addDataSet([runTime, loadTime], 'ff9900');
pie.setXLabels([
'Test execution (' + runTime + 'ms)',
'Loading (' + loadTime + 'ms)']);
pie.render(this.statsEl_);
};
/**
* Draws a pie chart showing the percentage of time spent running the tests
* compared to loading them etc.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawWorstTestsTable_ = function() {
this.stats_.sort(function(a, b) {
return b['numFilesLoaded'] - a['numFilesLoaded'];
});
var tbody = goog.bind(this.dom_.createDom, this.dom_, 'tbody');
var thead = goog.bind(this.dom_.createDom, this.dom_, 'thead');
var tr = goog.bind(this.dom_.createDom, this.dom_, 'tr');
var th = goog.bind(this.dom_.createDom, this.dom_, 'th');
var td = goog.bind(this.dom_.createDom, this.dom_, 'td');
var a = goog.bind(this.dom_.createDom, this.dom_, 'a');
var head = thead({'style': 'cursor: pointer'},
tr(null,
th(null, ' '),
th(null, 'Test file'),
th('center', 'Num files loaded'),
th('center', 'Run time (ms)'),
th('center', 'Total time (ms)')));
var body = tbody();
var table = this.dom_.createDom('table', null, head, body);
for (var i = 0; i < this.stats_.length; i++) {
var stat = this.stats_[i];
body.appendChild(tr(null,
td('center', String(i + 1)),
td(null, a(
{'href': this.basePath_ + stat['testFile'], 'target': '_blank'},
stat['testFile'])),
td('center', String(stat['numFilesLoaded'])),
td('center', String(stat['runTime'])),
td('center', String(stat['totalTime']))));
}
this.statsEl_.appendChild(table);
this.tableSorter_.setDefaultSortFunction(goog.ui.TableSorter.numericSort);
this.tableSorter_.setSortFunction(
1 /* test file name */, goog.ui.TableSorter.alphaSort);
this.tableSorter_.decorate(table);
};
/**
* Clears the stats page.
* @private
*/
goog.testing.MultiTestRunner.prototype.clearStats_ = function() {
goog.dom.removeChildren(this.statsEl_);
};
/**
* Updates the report's summary.
* @private
*/
goog.testing.MultiTestRunner.prototype.writeCurrentSummary_ = function() {
var total = this.activeTests_.length;
var executed = this.resultCount_;
var passes = this.passes_;
var duration = Math.round((goog.now() - this.startTime_) / 1000);
var text = executed + ' of ' + total + ' tests executed.<br>' +
passes + ' passed, ' + (executed - passes) + ' failed.<br>' +
'Duration: ' + duration + 's.';
this.reportEl_.firstChild.innerHTML = text;
};
/**
* Adds a segment to the progress bar.
* @param {string} title Title for the segment.
* @param {*} success Whether the segment should indicate a success.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawProgressSegment_ =
function(title, success) {
var part = this.progressRow_.cells[this.resultCount_ - 1];
part.title = title + ' : ' + (success ? 'SUCCESS' : 'FAILURE');
part.style.backgroundColor = success ? '#090' : '#900';
};
/**
* Draws a test result in the report pane.
* @param {string} test Test name.
* @param {*} success Whether the test succeeded.
* @param {string} report The report.
* @private
*/
goog.testing.MultiTestRunner.prototype.drawTestResult_ = function(
test, success, report) {
var text = goog.string.isEmpty(report) ?
'No report for ' + test + '\n' : report;
var el = this.dom_.createDom('div');
text = goog.string.htmlEscape(text).replace(/\n/g, '<br>');
if (success) {
el.className = goog.getCssName('goog-testrunner-report-success');
} else {
text += '<a href="' + this.basePath_ + test +
'">Run individually »</a><br> ';
el.className = goog.getCssName('goog-testrunner-report-failure');
}
el.innerHTML = text;
this.reportEl_.appendChild(el);
};
/**
* Returns the current timestamp.
* @return {string} HH:MM:SS.
* @private
*/
goog.testing.MultiTestRunner.prototype.getTimeStamp_ = function() {
var d = new Date;
return goog.string.padNumber(d.getHours(), 2) + ':' +
goog.string.padNumber(d.getMinutes(), 2) + ':' +
goog.string.padNumber(d.getSeconds(), 2);
};
/**
* Trims a filename to be less than 35-characters, ensuring that we do not break
* a path part.
* @param {string} name The file name.
* @return {string} The shortened name.
* @private
*/
goog.testing.MultiTestRunner.prototype.trimFileName_ = function(name) {
if (name.length < 35) {
return name;
}
var parts = name.split('/');
var result = '';
while (result.length < 35 && parts.length > 0) {
result = '/' + parts.pop() + result;
}
return '...' + result;
};
/**
* Shows the report and hides the log if the argument is true.
* @param {number} tab Which tab to show.
* @private
*/
goog.testing.MultiTestRunner.prototype.showTab_ = function(tab) {
var activeTabCssClass = goog.getCssName('goog-testrunner-activetab');
if (tab == 0) {
this.logEl_.style.display = '';
goog.dom.classes.add(this.logTabEl_, activeTabCssClass);
} else {
this.logEl_.style.display = 'none';
goog.dom.classes.remove(this.logTabEl_, activeTabCssClass);
}
if (tab == 1) {
this.reportEl_.style.display = '';
goog.dom.classes.add(this.reportTabEl_, activeTabCssClass);
} else {
this.reportEl_.style.display = 'none';
goog.dom.classes.remove(this.reportTabEl_, activeTabCssClass);
}
if (tab == 2) {
this.statsEl_.style.display = '';
goog.dom.classes.add(this.statsTabEl_, activeTabCssClass);
} else {
this.statsEl_.style.display = 'none';
goog.dom.classes.remove(this.statsTabEl_, activeTabCssClass);
}
};
/**
* Handles the start button being clicked.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.testing.MultiTestRunner.prototype.onStartClicked_ = function(e) {
this.start();
};
/**
* Handles the stop button being clicked.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.testing.MultiTestRunner.prototype.onStopClicked_ = function(e) {
this.stopped_ = true;
this.finish_();
};
/**
* Handles the log tab being clicked.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.testing.MultiTestRunner.prototype.onLogTabClicked_ = function(e) {
this.showTab_(0);
};
/**
* Handles the log tab being clicked.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.testing.MultiTestRunner.prototype.onReportTabClicked_ = function(e) {
this.showTab_(1);
};
/**
* Handles the stats tab being clicked.
* @param {goog.events.BrowserEvent} e The click event.
* @private
*/
goog.testing.MultiTestRunner.prototype.onStatsTabClicked_ = function(e) {
this.showTab_(2);
};
/**
* Class used to manage the interaction with a single iframe.
* @param {string} basePath The base path for tests.
* @param {number} timeoutMs The time to wait for the test to load and run.
* @param {boolean} verbosePasses Whether to show results for passes.
* @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper.
* @constructor
* @extends {goog.ui.Component}
*/
goog.testing.MultiTestRunner.TestFrame = function(
basePath, timeoutMs, verbosePasses, opt_domHelper) {
goog.ui.Component.call(this, opt_domHelper);
/**
* Base path where tests should be resolved from.
* @type {string}
* @private
*/
this.basePath_ = basePath;
/**
* The timeout for the test.
* @type {number}
* @private
*/
this.timeoutMs_ = timeoutMs;
/**
* Whether to show a summary for passing tests.
* @type {boolean}
* @private
*/
this.verbosePasses_ = verbosePasses;
/**
* An event handler for handling events.
* @type {goog.events.EventHandler}
* @private
*/
this.eh_ = new goog.events.EventHandler(this);
};
goog.inherits(goog.testing.MultiTestRunner.TestFrame, goog.ui.Component);
/**
* Reference to the iframe.
* @type {HTMLIFrameElement}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.iframeEl_ = null;
/**
* Whether the iframe for the current test has loaded.
* @type {boolean}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.iframeLoaded_ = false;
/**
* The test file being run.
* @type {string}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.testFile_ = '';
/**
* The report returned from the test.
* @type {string}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.report_ = '';
/**
* The total time loading and running the test in milliseconds.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.totalTime_ = 0;
/**
* The actual runtime of the test in milliseconds.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.runTime_ = 0;
/**
* The number of files loaded by the test.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.numFilesLoaded_ = 0;
/**
* Whether the test was successful, null if no result has been returned yet.
* @type {?boolean}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.isSuccess_ = null;
/**
* Timestamp for the when the test was started.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.startTime_ = 0;
/**
* Timestamp for the last state, used to determine timeouts.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.lastStateTime_ = 0;
/**
* The state of the active test.
* @type {number}
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.currentState_ = 0;
/** @override */
goog.testing.MultiTestRunner.TestFrame.prototype.disposeInternal = function() {
goog.testing.MultiTestRunner.TestFrame.superClass_.disposeInternal.call(this);
this.dom_.removeNode(this.iframeEl_);
this.eh_.dispose();
this.iframeEl_ = null;
};
/**
* Runs a test file in this test frame.
* @param {string} testFile The test to run.
*/
goog.testing.MultiTestRunner.TestFrame.prototype.runTest = function(testFile) {
this.lastStateTime_ = this.startTime_ = goog.now();
if (!this.iframeEl_) {
this.createIframe_();
}
this.iframeLoaded_ = false;
this.currentState_ = 0;
this.isSuccess_ = null;
this.report_ = '';
this.testFile_ = testFile;
try {
this.iframeEl_.src = this.basePath_ + testFile;
} catch (e) {
// Failures will trigger a JS exception on the local file system.
this.report_ = this.testFile_ + ' failed to load : ' + e.message;
this.isSuccess_ = false;
this.finish_();
return;
}
this.checkForCompletion_();
};
/**
* @return {string} The test file the TestFrame is running.
*/
goog.testing.MultiTestRunner.TestFrame.prototype.getTestFile = function() {
return this.testFile_;
};
/**
* @return {Object} Stats about the test run.
*/
goog.testing.MultiTestRunner.TestFrame.prototype.getStats = function() {
return {
'testFile': this.testFile_,
'success': this.isSuccess_,
'runTime': this.runTime_,
'totalTime': this.totalTime_,
'numFilesLoaded': this.numFilesLoaded_
};
};
/**
* @return {string} The report for the test run.
*/
goog.testing.MultiTestRunner.TestFrame.prototype.getReport = function() {
return this.report_;
};
/**
* @return {?boolean} Whether the test frame had a success.
*/
goog.testing.MultiTestRunner.TestFrame.prototype.isSuccess = function() {
return this.isSuccess_;
};
/**
* Handles the TestFrame finishing a single test.
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.finish_ = function() {
this.totalTime_ = goog.now() - this.startTime_;
// TODO(user): Fire an event instead?
if (this.getParent() && this.getParent().processResult) {
this.getParent().processResult(this);
}
};
/**
* Creates an iframe to run the tests in. For overriding in unit tests.
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.createIframe_ = function() {
this.iframeEl_ =
/** @type {HTMLIFrameElement} */ (this.dom_.createDom('iframe'));
this.getElement().appendChild(this.iframeEl_);
this.eh_.listen(this.iframeEl_, 'load', this.onIframeLoaded_);
};
/**
* Handles the iframe loading.
* @param {goog.events.BrowserEvent} e The load event.
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.onIframeLoaded_ = function(e) {
this.iframeLoaded_ = true;
};
/**
* Checks the active test for completion, keeping track of the tests' various
* execution stages.
* @private
*/
goog.testing.MultiTestRunner.TestFrame.prototype.checkForCompletion_ =
function() {
var js = goog.dom.getFrameContentWindow(this.iframeEl_);
switch (this.currentState_) {
case 0:
if (this.iframeLoaded_ && js['G_testRunner']) {
this.lastStateTime_ = goog.now();
this.currentState_++;
}
break;
case 1:
if (js['G_testRunner']['isInitialized']()) {
this.lastStateTime_ = goog.now();
this.currentState_++;
}
break;
case 2:
if (js['G_testRunner']['isFinished']()) {
var tr = js['G_testRunner'];
this.isSuccess_ = tr['isSuccess']();
this.report_ = tr['getReport'](this.verbosePasses_);
this.runTime_ = tr['getRunTime']();
this.numFilesLoaded_ = tr['getNumFilesLoaded']();
this.finish_();
return;
}
}
// Check to see if the test has timed out.
if (goog.now() - this.lastStateTime_ > this.timeoutMs_) {
this.report_ = this.testFile_ + ' timed out ' +
goog.testing.MultiTestRunner.STATES[this.currentState_];
this.isSuccess_ = false;
this.finish_();
return;
}
// Check again in 100ms.
goog.Timer.callOnce(this.checkForCompletion_, 100, this);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Utilities for adding, removing and setting ARIA roles
* as defined by W3C ARIA Working Draft:
* http://www.w3.org/TR/2010/WD-wai-aria-20100916/
* All modern browsers have some form of ARIA support, so no browser checks are
* performed when adding ARIA to components.
*
*
* @deprecated Use {@link goog.a11y.aria} instead.
* This file will be removed on 1 Apr 2013.
*
*/
goog.provide('goog.dom.a11y');
goog.provide('goog.dom.a11y.Announcer');
goog.provide('goog.dom.a11y.LivePriority');
goog.provide('goog.dom.a11y.Role');
goog.provide('goog.dom.a11y.State');
goog.require('goog.a11y.aria');
goog.require('goog.a11y.aria.Announcer');
goog.require('goog.a11y.aria.LivePriority');
goog.require('goog.a11y.aria.Role');
goog.require('goog.a11y.aria.State');
/**
* Enumeration of ARIA states and properties.
* @enum {string}
* @deprecated Use {@link goog.a11y.aria.State} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.State = goog.a11y.aria.State;
/**
* Enumeration of ARIA roles.
* @enum {string}
* @deprecated Use {@link goog.a11y.aria.Role} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.Role = goog.a11y.aria.Role;
/**
* Enumeration of ARIA state values for live regions.
*
* See http://www.w3.org/TR/wai-aria/states_and_properties#aria-live
* for more information.
* @enum {string}
* @deprecated Use {@link goog.a11y.aria.LivePriority} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.LivePriority = goog.a11y.aria.LivePriority;
/**
* Sets the role of an element.
* @param {Element} element DOM node to set role of.
* @param {goog.dom.a11y.Role|string} roleName role name(s).
* @deprecated Use {@link goog.a11y.aria.setRole} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.setRole = function(element, roleName) {
goog.a11y.aria.setRole(
/** @type {!Element} */ (element),
/** @type {!goog.dom.a11y.Role} */ (roleName));
};
/**
* Gets role of an element.
* @param {Element} element DOM node to get role of.
* @return {?(goog.dom.a11y.Role|string)} rolename.
* @deprecated Use {@link goog.a11y.aria.getRole} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.getRole = function(element) {
return /** @type {?(goog.dom.a11y.Role|string)} */ (
goog.a11y.aria.getRole(/** @type {!Element} */ (element)));
};
/**
* Sets the state or property of an element.
* @param {Element} element DOM node where we set state.
* @param {goog.dom.a11y.State|string} state State attribute being set.
* Automatically adds prefix 'aria-' to the state name.
* @param {boolean|number|string} value Value for the
* state attribute.
* @deprecated Use {@link goog.a11y.aria.setState} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.setState = function(element, state, value) {
goog.a11y.aria.setState(
/** @type {!Element} */ (element),
/** @type {!goog.dom.a11y.State} */ (state),
/** @type {boolean|number|string} */ (value));
};
/**
* Gets value of specified state or property.
* @param {Element} element DOM node to get state from.
* @param {goog.dom.a11y.State|string} stateName State name.
* @return {string} Value of the state attribute.
* @deprecated Use {@link goog.a11y.aria.getState} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.getState = function(element, stateName) {
return goog.a11y.aria.getState(
/** @type {!Element} */ (element),
/** @type {!goog.dom.a11y.State} */ (stateName));
};
/**
* Gets the activedescendant of the given element.
* @param {Element} element DOM node to get activedescendant from.
* @return {Element} DOM node of the activedescendant.
* @deprecated Use {@link goog.a11y.aria.getActiveDescendant} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.getActiveDescendant = function(element) {
return goog.a11y.aria.getActiveDescendant(
/** @type {!Element} */ (element));
};
/**
* Sets the activedescendant value for an element.
* @param {Element} element DOM node to set activedescendant to.
* @param {Element} activeElement DOM node being set as activedescendant.
* @deprecated Use {@link goog.a11y.aria.setActiveDescendant} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.setActiveDescendant = function(element, activeElement) {
goog.a11y.aria.setActiveDescendant(
/** @type {!Element} */ (element),
activeElement);
};
/**
* Class that allows messages to be spoken by assistive technologies that the
* user may have active.
*
* @param {goog.dom.DomHelper} domHelper DOM helper.
* @constructor
* @extends {goog.Disposable}
* @deprecated Use {@link goog.a11y.aria.Announcer} instead.
* This alias will be removed on 1 Apr 2013.
*/
goog.dom.a11y.Announcer = goog.a11y.aria.Announcer;
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 An API for saving and restoring ranges as HTML carets.
*
* @author nicksantos@google.com (Nick Santos)
*/
goog.provide('goog.dom.SavedCaretRange');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.SavedRange');
goog.require('goog.dom.TagName');
goog.require('goog.string');
/**
* A struct for holding context about saved selections.
* This can be used to preserve the selection and restore while the DOM is
* manipulated, or through an asynchronous call. Use goog.dom.Range factory
* methods to obtain an {@see goog.dom.AbstractRange} instance, and use
* {@see goog.dom.AbstractRange#saveUsingCarets} to obtain a SavedCaretRange.
* For editor ranges under content-editable elements or design-mode iframes,
* prefer using {@see goog.editor.range.saveUsingNormalizedCarets}.
* @param {goog.dom.AbstractRange} range The range being saved.
* @constructor
* @extends {goog.dom.SavedRange}
*/
goog.dom.SavedCaretRange = function(range) {
goog.dom.SavedRange.call(this);
/**
* The DOM id of the caret at the start of the range.
* @type {string}
* @private
*/
this.startCaretId_ = goog.string.createUniqueString();
/**
* The DOM id of the caret at the end of the range.
* @type {string}
* @private
*/
this.endCaretId_ = goog.string.createUniqueString();
/**
* A DOM helper for storing the current document context.
* @type {goog.dom.DomHelper}
* @private
*/
this.dom_ = goog.dom.getDomHelper(range.getDocument());
range.surroundWithNodes(this.createCaret_(true), this.createCaret_(false));
};
goog.inherits(goog.dom.SavedCaretRange, goog.dom.SavedRange);
/**
* Gets the range that this SavedCaretRage represents, without selecting it
* or removing the carets from the DOM.
* @return {goog.dom.AbstractRange?} An abstract range.
*/
goog.dom.SavedCaretRange.prototype.toAbstractRange = function() {
var range = null;
var startCaret = this.getCaret(true);
var endCaret = this.getCaret(false);
if (startCaret && endCaret) {
range = goog.dom.Range.createFromNodes(startCaret, 0, endCaret, 0);
}
return range;
};
/**
* Gets carets.
* @param {boolean} start If true, returns the start caret. Otherwise, get the
* end caret.
* @return {Element} The start or end caret in the given document.
*/
goog.dom.SavedCaretRange.prototype.getCaret = function(start) {
return this.dom_.getElement(start ? this.startCaretId_ : this.endCaretId_);
};
/**
* Removes the carets from the current restoration document.
* @param {goog.dom.AbstractRange=} opt_range A range whose offsets have already
* been adjusted for caret removal; it will be adjusted if it is also
* affected by post-removal operations, such as text node normalization.
* @return {goog.dom.AbstractRange|undefined} The adjusted range, if opt_range
* was provided.
*/
goog.dom.SavedCaretRange.prototype.removeCarets = function(opt_range) {
goog.dom.removeNode(this.getCaret(true));
goog.dom.removeNode(this.getCaret(false));
return opt_range;
};
/**
* Sets the document where the range will be restored.
* @param {!Document} doc An HTML document.
*/
goog.dom.SavedCaretRange.prototype.setRestorationDocument = function(doc) {
this.dom_.setDocument(doc);
};
/**
* Reconstruct the selection from the given saved range. Removes carets after
* restoring the selection. If restore does not dispose this saved range, it may
* only be restored a second time if innerHTML or some other mechanism is used
* to restore the carets to the dom.
* @return {goog.dom.AbstractRange?} Restored selection.
* @override
* @protected
*/
goog.dom.SavedCaretRange.prototype.restoreInternal = function() {
var range = null;
var startCaret = this.getCaret(true);
var endCaret = this.getCaret(false);
if (startCaret && endCaret) {
var startNode = startCaret.parentNode;
var startOffset = goog.array.indexOf(startNode.childNodes, startCaret);
var endNode = endCaret.parentNode;
var endOffset = goog.array.indexOf(endNode.childNodes, endCaret);
if (endNode == startNode) {
// Compensate for the start caret being removed.
endOffset -= 1;
}
range = goog.dom.Range.createFromNodes(startNode, startOffset,
endNode, endOffset);
range = this.removeCarets(range);
range.select();
} else {
// If only one caret was found, remove it.
this.removeCarets();
}
return range;
};
/**
* Dispose the saved range and remove the carets from the DOM.
* @override
* @protected
*/
goog.dom.SavedCaretRange.prototype.disposeInternal = function() {
this.removeCarets();
this.dom_ = null;
};
/**
* Creates a caret element.
* @param {boolean} start If true, creates the start caret. Otherwise,
* creates the end caret.
* @return {Element} The new caret element.
* @private
*/
goog.dom.SavedCaretRange.prototype.createCaret_ = function(start) {
return this.dom_.createDom(goog.dom.TagName.SPAN,
{'id': start ? this.startCaretId_ : this.endCaretId_});
};
/**
* A regex that will match all saved range carets in a string.
* @type {RegExp}
*/
goog.dom.SavedCaretRange.CARET_REGEX = /<span\s+id="?goog_\d+"?><\/span>/ig;
/**
* Returns whether two strings of html are equal, ignoring any saved carets.
* Thus two strings of html whose only difference is the id of their saved
* carets will be considered equal, since they represent html with the
* same selection.
* @param {string} str1 The first string.
* @param {string} str2 The second string.
* @return {boolean} Whether two strings of html are equal, ignoring any
* saved carets.
*/
goog.dom.SavedCaretRange.htmlEqual = function(str1, str2) {
return str1 == str2 ||
str1.replace(goog.dom.SavedCaretRange.CARET_REGEX, '') ==
str2.replace(goog.dom.SavedCaretRange.CARET_REGEX, '');
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Iterator subclass for DOM tree traversal.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.TagIterator');
goog.provide('goog.dom.TagWalkType');
goog.require('goog.dom.NodeType');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
/**
* There are three types of token:
* <ol>
* <li>{@code START_TAG} - The beginning of a tag.
* <li>{@code OTHER} - Any non-element node position.
* <li>{@code END_TAG} - The end of a tag.
* </ol>
* Users of this enumeration can rely on {@code START_TAG + END_TAG = 0} and
* that {@code OTHER = 0}.
*
* @enum {number}
*/
goog.dom.TagWalkType = {
START_TAG: 1,
OTHER: 0,
END_TAG: -1
};
/**
* A DOM tree traversal iterator.
*
* Starting with the given node, the iterator walks the DOM in order, reporting
* events for the start and end of Elements, and the presence of text nodes. For
* example:
*
* <pre>
* <div>1<span>2</span>3</div>
* </pre>
*
* Will return the following nodes:
*
* <code>[div, 1, span, 2, span, 3, div]</code>
*
* With the following states:
*
* <code>[START, OTHER, START, OTHER, END, OTHER, END]</code>
*
* And the following depths
*
* <code>[1, 1, 2, 2, 1, 1, 0]</code>
*
* Imagining <code>|</code> represents iterator position, the traversal stops at
* each of the following locations:
*
* <pre>
* <div>|1|<span>|2|</span>|3|</div>|
* </pre>
*
* The iterator can also be used in reverse mode, which will return the nodes
* and states in the opposite order. The depths will be slightly different
* since, like in normal mode, the depth is computed *after* the given node.
*
* Lastly, it is possible to create an iterator that is unconstrained, meaning
* that it will continue iterating until the end of the document instead of
* until exiting the start node.
*
* @param {Node=} opt_node The start node. If unspecified or null, defaults to
* an empty iterator.
* @param {boolean=} opt_reversed Whether to traverse the tree in reverse.
* @param {boolean=} opt_unconstrained Whether the iterator is not constrained
* to the starting node and its children.
* @param {goog.dom.TagWalkType?=} opt_tagType The type of the position.
* Defaults to the start of the given node for forward iterators, and
* the end of the node for reverse iterators.
* @param {number=} opt_depth The starting tree depth.
* @constructor
* @extends {goog.iter.Iterator}
*/
goog.dom.TagIterator = function(opt_node, opt_reversed,
opt_unconstrained, opt_tagType, opt_depth) {
this.reversed = !!opt_reversed;
if (opt_node) {
this.setPosition(opt_node, opt_tagType);
}
this.depth = opt_depth != undefined ? opt_depth : this.tagType || 0;
if (this.reversed) {
this.depth *= -1;
}
this.constrained = !opt_unconstrained;
};
goog.inherits(goog.dom.TagIterator, goog.iter.Iterator);
/**
* The node this position is located on.
* @type {Node}
*/
goog.dom.TagIterator.prototype.node = null;
/**
* The type of this position.
* @type {goog.dom.TagWalkType}
*/
goog.dom.TagIterator.prototype.tagType = goog.dom.TagWalkType.OTHER;
/**
* The tree depth of this position relative to where the iterator started. The
* depth is considered to be the tree depth just past the current node, so if an
* iterator is at position <pre>
* <div>|</div>
* </pre>
* (i.e. the node is the div and the type is START_TAG) its depth will be 1.
* @type {number}
*/
goog.dom.TagIterator.prototype.depth;
/**
* Whether the node iterator is moving in reverse.
* @type {boolean}
*/
goog.dom.TagIterator.prototype.reversed;
/**
* Whether the iterator is constrained to the starting node and its children.
* @type {boolean}
*/
goog.dom.TagIterator.prototype.constrained;
/**
* Whether iteration has started.
* @type {boolean}
* @private
*/
goog.dom.TagIterator.prototype.started_ = false;
/**
* Set the position of the iterator. Overwrite the tree node and the position
* type which can be one of the {@link goog.dom.TagWalkType} token types.
* Only overwrites the tree depth when the parameter is specified.
* @param {Node} node The node to set the position to.
* @param {goog.dom.TagWalkType?=} opt_tagType The type of the position
* Defaults to the start of the given node.
* @param {number=} opt_depth The tree depth.
*/
goog.dom.TagIterator.prototype.setPosition = function(node,
opt_tagType, opt_depth) {
this.node = node;
if (node) {
if (goog.isNumber(opt_tagType)) {
this.tagType = opt_tagType;
} else {
// Auto-determine the proper type
this.tagType = this.node.nodeType != goog.dom.NodeType.ELEMENT ?
goog.dom.TagWalkType.OTHER :
this.reversed ? goog.dom.TagWalkType.END_TAG :
goog.dom.TagWalkType.START_TAG;
}
}
if (goog.isNumber(opt_depth)) {
this.depth = opt_depth;
}
};
/**
* Replace this iterator's values with values from another. The two iterators
* must be of the same type.
* @param {goog.dom.TagIterator} other The iterator to copy.
* @protected
*/
goog.dom.TagIterator.prototype.copyFrom = function(other) {
this.node = other.node;
this.tagType = other.tagType;
this.depth = other.depth;
this.reversed = other.reversed;
this.constrained = other.constrained;
};
/**
* @return {goog.dom.TagIterator} A copy of this iterator.
*/
goog.dom.TagIterator.prototype.clone = function() {
return new goog.dom.TagIterator(this.node, this.reversed,
!this.constrained, this.tagType, this.depth);
};
/**
* Skip the current tag.
*/
goog.dom.TagIterator.prototype.skipTag = function() {
var check = this.reversed ? goog.dom.TagWalkType.END_TAG :
goog.dom.TagWalkType.START_TAG;
if (this.tagType == check) {
this.tagType = /** @type {goog.dom.TagWalkType} */ (check * -1);
this.depth += this.tagType * (this.reversed ? -1 : 1);
}
};
/**
* Restart the current tag.
*/
goog.dom.TagIterator.prototype.restartTag = function() {
var check = this.reversed ? goog.dom.TagWalkType.START_TAG :
goog.dom.TagWalkType.END_TAG;
if (this.tagType == check) {
this.tagType = /** @type {goog.dom.TagWalkType} */ (check * -1);
this.depth += this.tagType * (this.reversed ? -1 : 1);
}
};
/**
* Move to the next position in the DOM tree.
* @return {Node} Returns the next node, or throws a goog.iter.StopIteration
* exception if the end of the iterator's range has been reached.
* @override
*/
goog.dom.TagIterator.prototype.next = function() {
var node;
if (this.started_) {
if (!this.node || this.constrained && this.depth == 0) {
throw goog.iter.StopIteration;
}
node = this.node;
var startType = this.reversed ? goog.dom.TagWalkType.END_TAG :
goog.dom.TagWalkType.START_TAG;
if (this.tagType == startType) {
// If we have entered the tag, test if there are any children to move to.
var child = this.reversed ? node.lastChild : node.firstChild;
if (child) {
this.setPosition(child);
} else {
// If not, move on to exiting this tag.
this.setPosition(node,
/** @type {goog.dom.TagWalkType} */ (startType * -1));
}
} else {
var sibling = this.reversed ? node.previousSibling : node.nextSibling;
if (sibling) {
// Try to move to the next node.
this.setPosition(sibling);
} else {
// If no such node exists, exit our parent.
this.setPosition(node.parentNode,
/** @type {goog.dom.TagWalkType} */ (startType * -1));
}
}
this.depth += this.tagType * (this.reversed ? -1 : 1);
} else {
this.started_ = true;
}
// Check the new position for being last, and return it if it's not.
node = this.node;
if (!this.node) {
throw goog.iter.StopIteration;
}
return node;
};
/**
* @return {boolean} Whether next has ever been called on this iterator.
* @protected
*/
goog.dom.TagIterator.prototype.isStarted = function() {
return this.started_;
};
/**
* @return {boolean} Whether this iterator's position is a start tag position.
*/
goog.dom.TagIterator.prototype.isStartTag = function() {
return this.tagType == goog.dom.TagWalkType.START_TAG;
};
/**
* @return {boolean} Whether this iterator's position is an end tag position.
*/
goog.dom.TagIterator.prototype.isEndTag = function() {
return this.tagType == goog.dom.TagWalkType.END_TAG;
};
/**
* @return {boolean} Whether this iterator's position is not at an element node.
*/
goog.dom.TagIterator.prototype.isNonElement = function() {
return this.tagType == goog.dom.TagWalkType.OTHER;
};
/**
* Test if two iterators are at the same position - i.e. if the node and tagType
* is the same. This will still return true if the two iterators are moving in
* opposite directions or have different constraints.
* @param {goog.dom.TagIterator} other The iterator to compare to.
* @return {boolean} Whether the two iterators are at the same position.
*/
goog.dom.TagIterator.prototype.equals = function(other) {
// Nodes must be equal, and we must either have reached the end of our tree
// or be at the same position.
return other.node == this.node && (!this.node ||
other.tagType == this.tagType);
};
/**
* Replace the current node with the list of nodes. Reset the iterator so that
* it visits the first of the nodes next.
* @param {...Object} var_args A list of nodes to replace the current node with.
* If the first argument is array-like, it will be used, otherwise all the
* arguments are assumed to be nodes.
*/
goog.dom.TagIterator.prototype.splice = function(var_args) {
// Reset the iterator so that it iterates over the first replacement node in
// the arguments on the next iteration.
var node = this.node;
this.restartTag();
this.reversed = !this.reversed;
goog.dom.TagIterator.prototype.next.call(this);
this.reversed = !this.reversed;
// Replace the node with the arguments.
var arr = goog.isArrayLike(arguments[0]) ? arguments[0] : arguments;
for (var i = arr.length - 1; i >= 0; i--) {
goog.dom.insertSiblingAfter(arr[i], node);
}
goog.dom.removeNode(node);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Iterators over DOM nodes.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.iter.AncestorIterator');
goog.provide('goog.dom.iter.ChildIterator');
goog.provide('goog.dom.iter.SiblingIterator');
goog.require('goog.iter.Iterator');
goog.require('goog.iter.StopIteration');
/**
* Iterator over a Node's siblings.
* @param {Node} node The node to start with.
* @param {boolean=} opt_includeNode Whether to return the given node as the
* first return value from next.
* @param {boolean=} opt_reverse Whether to traverse siblings in reverse
* document order.
* @constructor
* @extends {goog.iter.Iterator}
*/
goog.dom.iter.SiblingIterator = function(node, opt_includeNode, opt_reverse) {
/**
* The current node, or null if iteration is finished.
* @type {Node}
* @private
*/
this.node_ = node;
/**
* Whether to iterate in reverse.
* @type {boolean}
* @private
*/
this.reverse_ = !!opt_reverse;
if (node && !opt_includeNode) {
this.next();
}
};
goog.inherits(goog.dom.iter.SiblingIterator, goog.iter.Iterator);
/** @override */
goog.dom.iter.SiblingIterator.prototype.next = function() {
var node = this.node_;
if (!node) {
throw goog.iter.StopIteration;
}
this.node_ = this.reverse_ ? node.previousSibling : node.nextSibling;
return node;
};
/**
* Iterator over an Element's children.
* @param {Element} element The element to iterate over.
* @param {boolean=} opt_reverse Optionally traverse children from last to
* first.
* @param {number=} opt_startIndex Optional starting index.
* @constructor
* @extends {goog.dom.iter.SiblingIterator}
*/
goog.dom.iter.ChildIterator = function(element, opt_reverse, opt_startIndex) {
if (!goog.isDef(opt_startIndex)) {
opt_startIndex = opt_reverse && element.childNodes.length ?
element.childNodes.length - 1 : 0;
}
goog.dom.iter.SiblingIterator.call(this, element.childNodes[opt_startIndex],
true, opt_reverse);
};
goog.inherits(goog.dom.iter.ChildIterator, goog.dom.iter.SiblingIterator);
/**
* Iterator over a Node's ancestors, stopping after the document body.
* @param {Node} node The node to start with.
* @param {boolean=} opt_includeNode Whether to return the given node as the
* first return value from next.
* @constructor
* @extends {goog.iter.Iterator}
*/
goog.dom.iter.AncestorIterator = function(node, opt_includeNode) {
/**
* The current node, or null if iteration is finished.
* @type {Node}
* @private
*/
this.node_ = node;
if (node && !opt_includeNode) {
this.next();
}
};
goog.inherits(goog.dom.iter.AncestorIterator, goog.iter.Iterator);
/** @override */
goog.dom.iter.AncestorIterator.prototype.next = function() {
var node = this.node_;
if (!node) {
throw goog.iter.StopIteration;
}
this.node_ = node.parentNode;
return node;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 DOM pattern to match a node of the given type.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.NodeType');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches any node of the given type.
* @param {goog.dom.NodeType} nodeType The node type to match.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.NodeType = function(nodeType) {
/**
* The node type to match.
* @type {goog.dom.NodeType}
* @private
*/
this.nodeType_ = nodeType;
};
goog.inherits(goog.dom.pattern.NodeType, goog.dom.pattern.AbstractPattern);
/**
* Test whether the given token is a text token which matches the string or
* regular expression provided in the constructor.
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>NO_MATCH</code> otherwise.
* @override
*/
goog.dom.pattern.NodeType.prototype.matchToken = function(token, type) {
return token.nodeType == this.nodeType_ ?
goog.dom.pattern.MatchType.MATCH :
goog.dom.pattern.MatchType.NO_MATCH;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match a tag.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.Tag');
goog.require('goog.dom.pattern');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
goog.require('goog.object');
/**
* Pattern object that matches an tag.
*
* @param {string|RegExp} tag Name of the tag. Also will accept a regular
* expression to match against the tag name.
* @param {goog.dom.TagWalkType} type Type of token to match.
* @param {Object=} opt_attrs Optional map of attribute names to desired values.
* This pattern will only match when all attributes are present and match
* the string or regular expression value provided here.
* @param {Object=} opt_styles Optional map of CSS style names to desired
* values. This pattern will only match when all styles are present and
* match the string or regular expression value provided here.
* @param {Function=} opt_test Optional function that takes the element as a
* parameter and returns true if this pattern should match it.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.Tag = function(tag, type, opt_attrs, opt_styles, opt_test) {
if (goog.isString(tag)) {
this.tag_ = tag.toUpperCase();
} else {
this.tag_ = tag;
}
this.type_ = type;
this.attrs_ = opt_attrs || null;
this.styles_ = opt_styles || null;
this.test_ = opt_test || null;
};
goog.inherits(goog.dom.pattern.Tag, goog.dom.pattern.AbstractPattern);
/**
* The tag to match.
*
* @type {string|RegExp}
* @private
*/
goog.dom.pattern.Tag.prototype.tag_;
/**
* The type of token to match.
*
* @type {goog.dom.TagWalkType}
* @private
*/
goog.dom.pattern.Tag.prototype.type_;
/**
* The attributes to test for.
*
* @type {Object}
* @private
*/
goog.dom.pattern.Tag.prototype.attrs_ = null;
/**
* The styles to test for.
*
* @type {Object}
* @private
*/
goog.dom.pattern.Tag.prototype.styles_ = null;
/**
* Function that takes the element as a parameter and returns true if this
* pattern should match it.
*
* @type {Function}
* @private
*/
goog.dom.pattern.Tag.prototype.test_ = null;
/**
* Test whether the given token is a tag token which matches the tag name,
* style, and attributes provided in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>NO_MATCH</code> otherwise.
* @override
*/
goog.dom.pattern.Tag.prototype.matchToken = function(token, type) {
// Check the direction and tag name.
if (type == this.type_ &&
goog.dom.pattern.matchStringOrRegex(this.tag_, token.nodeName)) {
// Check the attributes.
if (this.attrs_ &&
!goog.object.every(
this.attrs_,
goog.dom.pattern.matchStringOrRegexMap,
token)) {
return goog.dom.pattern.MatchType.NO_MATCH;
}
// Check the styles.
if (this.styles_ &&
!goog.object.every(
this.styles_,
goog.dom.pattern.matchStringOrRegexMap,
token.style)) {
return goog.dom.pattern.MatchType.NO_MATCH;
}
if (this.test_ && !this.test_(token)) {
return goog.dom.pattern.MatchType.NO_MATCH;
}
// If we reach this point, we have a match and should save it.
this.matchedNode = token;
return goog.dom.pattern.MatchType.MATCH;
}
return goog.dom.pattern.MatchType.NO_MATCH;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match the start of a tag.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.StartTag');
goog.require('goog.dom.TagWalkType');
goog.require('goog.dom.pattern.Tag');
/**
* Pattern object that matches an opening tag.
*
* @param {string|RegExp} tag Name of the tag. Also will accept a regular
* expression to match against the tag name.
* @param {Object=} opt_attrs Optional map of attribute names to desired values.
* This pattern will only match when all attributes are present and match
* the string or regular expression value provided here.
* @param {Object=} opt_styles Optional map of CSS style names to desired
* values. This pattern will only match when all styles are present and
* match the string or regular expression value provided here.
* @param {Function=} opt_test Optional function that takes the element as a
* parameter and returns true if this pattern should match it.
* @constructor
* @extends {goog.dom.pattern.Tag}
*/
goog.dom.pattern.StartTag = function(tag, opt_attrs, opt_styles, opt_test) {
goog.dom.pattern.Tag.call(
this,
tag,
goog.dom.TagWalkType.START_TAG,
opt_attrs,
opt_styles,
opt_test);
};
goog.inherits(goog.dom.pattern.StartTag, goog.dom.pattern.Tag);
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match the end of a tag.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.EndTag');
goog.require('goog.dom.TagWalkType');
goog.require('goog.dom.pattern.Tag');
/**
* Pattern object that matches a closing tag.
*
* @param {string|RegExp} tag Name of the tag. Also will accept a regular
* expression to match against the tag name.
* @param {Object=} opt_attrs Optional map of attribute names to desired values.
* This pattern will only match when all attributes are present and match
* the string or regular expression value provided here.
* @param {Object=} opt_styles Optional map of CSS style names to desired
* values. This pattern will only match when all styles are present and
* match the string or regular expression value provided here.
* @param {Function=} opt_test Optional function that takes the element as a
* parameter and returns true if this pattern should match it.
* @constructor
* @extends {goog.dom.pattern.Tag}
*/
goog.dom.pattern.EndTag = function(tag, opt_attrs, opt_styles, opt_test) {
goog.dom.pattern.Tag.call(
this,
tag,
goog.dom.TagWalkType.END_TAG,
opt_attrs,
opt_styles,
opt_test);
};
goog.inherits(goog.dom.pattern.EndTag, goog.dom.pattern.Tag);
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match a text node.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.Text');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.pattern');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches text by exact matching or regular expressions.
*
* @param {string|RegExp} match String or regular expression to match against.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.Text = function(match) {
this.match_ = match;
};
goog.inherits(goog.dom.pattern.Text, goog.dom.pattern.AbstractPattern);
/**
* The text or regular expression to match.
*
* @type {string|RegExp}
* @private
*/
goog.dom.pattern.Text.prototype.match_;
/**
* Test whether the given token is a text token which matches the string or
* regular expression provided in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>NO_MATCH</code> otherwise.
* @override
*/
goog.dom.pattern.Text.prototype.matchToken = function(token, type) {
if (token.nodeType == goog.dom.NodeType.TEXT &&
goog.dom.pattern.matchStringOrRegex(this.match_, token.nodeValue)) {
this.matchedNode = token;
return goog.dom.pattern.MatchType.MATCH;
}
return goog.dom.pattern.MatchType.NO_MATCH;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM patterns. Allows for description of complex DOM patterns
* using regular expression like constructs.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern');
goog.provide('goog.dom.pattern.MatchType');
/**
* Regular expression for breaking text nodes.
* @type {RegExp}
*/
goog.dom.pattern.BREAKING_TEXTNODE_RE = /^\s*$/;
/**
* Utility function to match a string against either a string or a regular
* expression.
*
* @param {string|RegExp} obj Either a string or a regular expression.
* @param {string} str The string to match.
* @return {boolean} Whether the strings are equal, or if the string matches
* the regular expression.
*/
goog.dom.pattern.matchStringOrRegex = function(obj, str) {
if (goog.isString(obj)) {
// Match a string
return str == obj;
} else {
// Match a regular expression
return !!(str && str.match(obj));
}
};
/**
* Utility function to match a DOM attribute against either a string or a
* regular expression. Conforms to the interface spec for
* {@link goog.object#every}.
*
* @param {string|RegExp} elem Either a string or a regular expression.
* @param {string} index The attribute name to match.
* @param {Object} orig The original map of matches to test.
* @return {boolean} Whether the strings are equal, or if the attribute matches
* the regular expression.
* @this {Element} Called using goog.object every on an Element.
*/
goog.dom.pattern.matchStringOrRegexMap = function(elem, index, orig) {
return goog.dom.pattern.matchStringOrRegex(elem,
index in this ? this[index] :
(this.getAttribute ? this.getAttribute(index) : null));
};
/**
* When matched to a token, a pattern may return any of the following statuses:
* <ol>
* <li><code>NO_MATCH</code> - The pattern does not match. This is the only
* value that evaluates to <code>false</code> in a boolean context.
* <li><code>MATCHING</code> - The token is part of an incomplete match.
* <li><code>MATCH</code> - The token completes a match.
* <li><code>BACKTRACK_MATCH</code> - The token does not match, but indicates
* the end of a repetitive match. For instance, in regular expressions,
* the pattern <code>/a+/</code> would match <code>'aaaaaaaab'</code>.
* Every <code>'a'</code> token would give a status of
* <code>MATCHING</code> while the <code>'b'</code> token would give a
* status of <code>BACKTRACK_MATCH</code>.
* </ol>
* @enum {number}
*/
goog.dom.pattern.MatchType = {
NO_MATCH: 0,
MATCHING: 1,
MATCH: 2,
BACKTRACK_MATCH: 3
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern base class.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Base pattern class for DOM matching.
*
* @constructor
*/
goog.dom.pattern.AbstractPattern = function() {
};
/**
* The first node matched by this pattern.
* @type {Node}
*/
goog.dom.pattern.AbstractPattern.prototype.matchedNode = null;
/**
* Reset any internal state this pattern keeps.
*/
goog.dom.pattern.AbstractPattern.prototype.reset = function() {
// The base implementation does nothing.
};
/**
* Test whether this pattern matches the given token.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} {@code MATCH} if the pattern matches.
*/
goog.dom.pattern.AbstractPattern.prototype.matchToken = function(token, type) {
return goog.dom.pattern.MatchType.NO_MATCH;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match any children of a tag, and
* specifically collect those that match a child pattern.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.ChildMatches');
goog.require('goog.dom.pattern.AllChildren');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches any nodes at or below the current tree depth.
*
* @param {goog.dom.pattern.AbstractPattern} childPattern Pattern to collect
* child matches of.
* @param {number=} opt_minimumMatches Enforce a minimum nuber of matches.
* Defaults to 0.
* @constructor
* @extends {goog.dom.pattern.AllChildren}
*/
goog.dom.pattern.ChildMatches = function(childPattern, opt_minimumMatches) {
this.childPattern_ = childPattern;
this.matches = [];
this.minimumMatches_ = opt_minimumMatches || 0;
goog.dom.pattern.AllChildren.call(this);
};
goog.inherits(goog.dom.pattern.ChildMatches, goog.dom.pattern.AllChildren);
/**
* Array of matched child nodes.
*
* @type {Array.<Node>}
*/
goog.dom.pattern.ChildMatches.prototype.matches;
/**
* Minimum number of matches.
*
* @type {number}
* @private
*/
goog.dom.pattern.ChildMatches.prototype.minimumMatches_ = 0;
/**
* The child pattern to collect matches from.
*
* @type {goog.dom.pattern.AbstractPattern}
* @private
*/
goog.dom.pattern.ChildMatches.prototype.childPattern_;
/**
* Whether the pattern has recently matched or failed to match and will need to
* be reset when starting a new round of matches.
*
* @type {boolean}
* @private
*/
goog.dom.pattern.ChildMatches.prototype.needsReset_ = false;
/**
* Test whether the given token is on the same level.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} {@code MATCHING} if the token is on the
* same level or deeper and {@code BACKTRACK_MATCH} if not.
* @override
*/
goog.dom.pattern.ChildMatches.prototype.matchToken = function(token, type) {
// Defer resets so we maintain our matches array until the last possible time.
if (this.needsReset_) {
this.reset();
}
// Call the super-method to ensure we stay in the child tree.
var status =
goog.dom.pattern.AllChildren.prototype.matchToken.apply(this, arguments);
switch (status) {
case goog.dom.pattern.MatchType.MATCHING:
var backtrack = false;
switch (this.childPattern_.matchToken(token, type)) {
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
backtrack = true;
case goog.dom.pattern.MatchType.MATCH:
// Collect the match.
this.matches.push(this.childPattern_.matchedNode);
break;
default:
// Keep trying if we haven't hit a terminal state.
break;
}
if (backtrack) {
// The only interesting result is a MATCH, since BACKTRACK_MATCH means
// we are hitting an infinite loop on something like a Repeat(0).
if (this.childPattern_.matchToken(token, type) ==
goog.dom.pattern.MatchType.MATCH) {
this.matches.push(this.childPattern_.matchedNode);
}
}
return goog.dom.pattern.MatchType.MATCHING;
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
// TODO(robbyw): this should return something like BACKTRACK_NO_MATCH
// when we don't meet our minimum.
this.needsReset_ = true;
return (this.matches.length >= this.minimumMatches_) ?
goog.dom.pattern.MatchType.BACKTRACK_MATCH :
goog.dom.pattern.MatchType.NO_MATCH;
default:
this.needsReset_ = true;
return status;
}
};
/**
* Reset any internal state this pattern keeps.
* @override
*/
goog.dom.pattern.ChildMatches.prototype.reset = function() {
this.needsReset_ = false;
this.matches.length = 0;
this.childPattern_.reset();
goog.dom.pattern.AllChildren.prototype.reset.call(this);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Useful callback functions for the DOM matcher.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.callback');
goog.require('goog.dom');
goog.require('goog.dom.TagWalkType');
goog.require('goog.iter');
/**
* Callback function for use in {@link goog.dom.pattern.Matcher.addPattern}
* that removes the matched node from the tree. Should be used in conjunciton
* with a {@link goog.dom.pattern.StartTag} pattern.
*
* @param {Node} node The node matched by the pattern.
* @param {goog.dom.TagIterator} position The position where the match
* finished.
* @return {boolean} Returns true to indicate tree changes were made.
*/
goog.dom.pattern.callback.removeNode = function(node, position) {
// Find out which position would be next.
position.setPosition(node, goog.dom.TagWalkType.END_TAG);
goog.iter.nextOrValue(position, null);
// Remove the node.
goog.dom.removeNode(node);
// Correct for the depth change.
position.depth -= 1;
// Indicate that we made position/tree changes.
return true;
};
/**
* Callback function for use in {@link goog.dom.pattern.Matcher.addPattern}
* that removes the matched node from the tree and replaces it with its
* children. Should be used in conjunction with a
* {@link goog.dom.pattern.StartTag} pattern.
*
* @param {Element} node The node matched by the pattern.
* @param {goog.dom.TagIterator} position The position where the match
* finished.
* @return {boolean} Returns true to indicate tree changes were made.
*/
goog.dom.pattern.callback.flattenElement = function(node, position) {
// Find out which position would be next.
position.setPosition(node, node.firstChild ?
goog.dom.TagWalkType.START_TAG :
goog.dom.TagWalkType.END_TAG);
goog.iter.nextOrValue(position, null);
// Flatten the node.
goog.dom.flattenElement(node);
// Correct for the depth change.
position.depth -= 1;
// Indicate that we made position/tree changes.
return true;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Callback object that counts matches.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.callback.Counter');
/**
* Callback class for counting matches.
* @constructor
*/
goog.dom.pattern.callback.Counter = function() {
};
/**
* The count of objects matched so far.
*
* @type {number}
*/
goog.dom.pattern.callback.Counter.prototype.count = 0;
/**
* The callback function. Suitable as a callback for
* {@link goog.dom.pattern.Matcher}.
* @type {Function}
* @private
*/
goog.dom.pattern.callback.Counter.prototype.callback_ = null;
/**
* Get a bound callback function that is suitable as a callback for
* {@link goog.dom.pattern.Matcher}.
*
* @return {Function} A callback function.
*/
goog.dom.pattern.callback.Counter.prototype.getCallback = function() {
if (!this.callback_) {
this.callback_ = goog.bind(function() {
this.count++;
return false;
}, this);
}
return this.callback_;
};
/**
* Reset the counter.
*/
goog.dom.pattern.callback.Counter.prototype.reset = function() {
this.count = 0;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Callback object that tests if a pattern matches at least once.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.callback.Test');
goog.require('goog.iter.StopIteration');
/**
* Callback class for testing for at least one match.
* @constructor
*/
goog.dom.pattern.callback.Test = function() {
};
/**
* Whether or not the pattern matched.
*
* @type {boolean}
*/
goog.dom.pattern.callback.Test.prototype.matched = false;
/**
* The callback function. Suitable as a callback for
* {@link goog.dom.pattern.Matcher}.
* @type {Function}
* @private
*/
goog.dom.pattern.callback.Test.prototype.callback_ = null;
/**
* Get a bound callback function that is suitable as a callback for
* {@link goog.dom.pattern.Matcher}.
*
* @return {Function} A callback function.
*/
goog.dom.pattern.callback.Test.prototype.getCallback = function() {
if (!this.callback_) {
this.callback_ = goog.bind(function(node, position) {
// Mark our match.
this.matched = true;
// Stop searching.
throw goog.iter.StopIteration;
}, this);
}
return this.callback_;
};
/**
* Reset the counter.
*/
goog.dom.pattern.callback.Test.prototype.reset = function() {
this.matched = false;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match a tag and all of its children.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.Repeat');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches a repetition of another pattern.
* @param {goog.dom.pattern.AbstractPattern} pattern The pattern to
* repetitively match.
* @param {number=} opt_minimum The minimum number of times to match. Defaults
* to 0.
* @param {number=} opt_maximum The maximum number of times to match. Defaults
* to unlimited.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.Repeat = function(pattern,
opt_minimum,
opt_maximum) {
this.pattern_ = pattern;
this.minimum_ = opt_minimum || 0;
this.maximum_ = opt_maximum || null;
this.matches = [];
};
goog.inherits(goog.dom.pattern.Repeat, goog.dom.pattern.AbstractPattern);
/**
* Pattern to repetitively match.
*
* @type {goog.dom.pattern.AbstractPattern}
* @private
*/
goog.dom.pattern.Repeat.prototype.pattern_;
/**
* Minimum number of times to match the pattern.
*
* @private
*/
goog.dom.pattern.Repeat.prototype.minimum_ = 0;
/**
* Optional maximum number of times to match the pattern. A {@code null} value
* will be treated as infinity.
*
* @type {?number}
* @private
*/
goog.dom.pattern.Repeat.prototype.maximum_ = 0;
/**
* Number of times the pattern has matched.
*
* @type {number}
*/
goog.dom.pattern.Repeat.prototype.count = 0;
/**
* Whether the pattern has recently matched or failed to match and will need to
* be reset when starting a new round of matches.
*
* @type {boolean}
* @private
*/
goog.dom.pattern.Repeat.prototype.needsReset_ = false;
/**
* The matched nodes.
*
* @type {Array.<Node>}
*/
goog.dom.pattern.Repeat.prototype.matches;
/**
* Test whether the given token continues a repeated series of matches of the
* pattern given in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>BACKTRACK_MATCH</code> if the pattern does not match
* but already had accumulated matches, <code>MATCHING</code> if the pattern
* starts a match, and <code>NO_MATCH</code> if the pattern does not match.
* @suppress {missingProperties} See the broken line below.
* @override
*/
goog.dom.pattern.Repeat.prototype.matchToken = function(token, type) {
// Reset if we're starting a new match
if (this.needsReset_) {
this.reset();
}
// If the option is set, ignore any whitespace only text nodes
if (token.nodeType == goog.dom.NodeType.TEXT &&
token.nodeValue.match(/^\s+$/)) {
return goog.dom.pattern.MatchType.MATCHING;
}
switch (this.pattern_.matchToken(token, type)) {
case goog.dom.pattern.MatchType.MATCH:
// Record the first token we match.
if (this.count == 0) {
this.matchedNode = token;
}
// Mark the match
this.count++;
// Add to the list
this.matches.push(this.pattern_.matchedNode);
// Check if this match hits our maximum
if (this.maximum_ !== null && this.count == this.maximum_) {
this.needsReset_ = true;
return goog.dom.pattern.MatchType.MATCH;
} else {
return goog.dom.pattern.MatchType.MATCHING;
}
case goog.dom.pattern.MatchType.MATCHING:
// This can happen when our child pattern is a sequence or a repetition.
return goog.dom.pattern.MatchType.MATCHING;
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
// This happens if our child pattern is repetitive too.
// TODO(robbyw): Backtrack further if necessary.
this.count++;
// NOTE(nicksantos): This line of code is broken. this.patterns_ doesn't
// exist, and this.currentPosition_ doesn't exit. When this is fixed,
// remove the missingProperties suppression above.
if (this.currentPosition_ == this.patterns_.length) {
this.needsReset_ = true;
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
// Retry the same token on the next iteration of the child pattern.
return this.matchToken(token, type);
}
default:
this.needsReset_ = true;
if (this.count >= this.minimum_) {
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
return goog.dom.pattern.MatchType.NO_MATCH;
}
}
};
/**
* Reset any internal state this pattern keeps.
* @override
*/
goog.dom.pattern.Repeat.prototype.reset = function() {
this.pattern_.reset();
this.count = 0;
this.needsReset_ = false;
this.matches.length = 0;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match a tag and all of its children.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.FullTag');
goog.require('goog.dom.pattern.MatchType');
goog.require('goog.dom.pattern.StartTag');
goog.require('goog.dom.pattern.Tag');
/**
* Pattern object that matches a full tag including all its children.
*
* @param {string|RegExp} tag Name of the tag. Also will accept a regular
* expression to match against the tag name.
* @param {Object=} opt_attrs Optional map of attribute names to desired values.
* This pattern will only match when all attributes are present and match
* the string or regular expression value provided here.
* @param {Object=} opt_styles Optional map of CSS style names to desired
* values. This pattern will only match when all styles are present and
* match the string or regular expression value provided here.
* @param {Function=} opt_test Optional function that takes the element as a
* parameter and returns true if this pattern should match it.
* @constructor
* @extends {goog.dom.pattern.StartTag}
*/
goog.dom.pattern.FullTag = function(tag, opt_attrs, opt_styles, opt_test) {
goog.dom.pattern.StartTag.call(
this,
tag,
opt_attrs,
opt_styles,
opt_test);
};
goog.inherits(goog.dom.pattern.FullTag, goog.dom.pattern.StartTag);
/**
* Tracks the matcher's depth to detect the end of the tag.
*
* @type {number}
* @private
*/
goog.dom.pattern.FullTag.prototype.depth_ = 0;
/**
* Test whether the given token is a start tag token which matches the tag name,
* style, and attributes provided in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> at the end of our
* tag, <code>MATCHING</code> if we are within the tag, and
* <code>NO_MATCH</code> if the starting tag does not match.
* @override
*/
goog.dom.pattern.FullTag.prototype.matchToken = function(token, type) {
if (!this.depth_) {
// If we have not yet started, make sure we match as a StartTag.
if (goog.dom.pattern.Tag.prototype.matchToken.call(this, token, type)) {
this.depth_ = type;
return goog.dom.pattern.MatchType.MATCHING;
} else {
return goog.dom.pattern.MatchType.NO_MATCH;
}
} else {
this.depth_ += type;
return this.depth_ ?
goog.dom.pattern.MatchType.MATCHING :
goog.dom.pattern.MatchType.MATCH;
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match a sequence of other patterns.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.Sequence');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches a sequence of other patterns.
*
* @param {Array.<goog.dom.pattern.AbstractPattern>} patterns Ordered array of
* patterns to match.
* @param {boolean=} opt_ignoreWhitespace Optional flag to ignore text nodes
* consisting entirely of whitespace. The default is to not ignore them.
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.Sequence = function(patterns, opt_ignoreWhitespace) {
this.patterns = patterns;
this.ignoreWhitespace_ = !!opt_ignoreWhitespace;
};
goog.inherits(goog.dom.pattern.Sequence, goog.dom.pattern.AbstractPattern);
/**
* Ordered array of patterns to match.
*
* @type {Array.<goog.dom.pattern.AbstractPattern>}
*/
goog.dom.pattern.Sequence.prototype.patterns;
/**
* Position in the patterns array we have reached by successful matches.
*
* @type {number}
* @private
*/
goog.dom.pattern.Sequence.prototype.currentPosition_ = 0;
/**
* Whether or not to ignore whitespace only Text nodes.
*
* @type {boolean}
* @private
*/
goog.dom.pattern.Sequence.prototype.ignoreWhitespace_ = false;
/**
* Test whether the given token starts, continues, or finishes the sequence
* of patterns given in the constructor.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} <code>MATCH</code> if the pattern
* matches, <code>MATCHING</code> if the pattern starts a match, and
* <code>NO_MATCH</code> if the pattern does not match.
* @override
*/
goog.dom.pattern.Sequence.prototype.matchToken = function(token, type) {
// If the option is set, ignore any whitespace only text nodes
if (this.ignoreWhitespace_ && token.nodeType == goog.dom.NodeType.TEXT &&
goog.dom.pattern.BREAKING_TEXTNODE_RE.test(token.nodeValue)) {
return goog.dom.pattern.MatchType.MATCHING;
}
switch (this.patterns[this.currentPosition_].matchToken(token, type)) {
case goog.dom.pattern.MatchType.MATCH:
// Record the first token we match.
if (this.currentPosition_ == 0) {
this.matchedNode = token;
}
// Move forward one position.
this.currentPosition_++;
// Check if this is the last position.
if (this.currentPosition_ == this.patterns.length) {
this.reset();
return goog.dom.pattern.MatchType.MATCH;
} else {
return goog.dom.pattern.MatchType.MATCHING;
}
case goog.dom.pattern.MatchType.MATCHING:
// This can happen when our child pattern is a sequence or a repetition.
return goog.dom.pattern.MatchType.MATCHING;
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
// This means a repetitive match succeeded 1 token ago.
// TODO(robbyw): Backtrack further if necessary.
this.currentPosition_++;
if (this.currentPosition_ == this.patterns.length) {
this.reset();
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
} else {
// Retry the same token on the next pattern.
return this.matchToken(token, type);
}
default:
this.reset();
return goog.dom.pattern.MatchType.NO_MATCH;
}
};
/**
* Reset any internal state this pattern keeps.
* @override
*/
goog.dom.pattern.Sequence.prototype.reset = function() {
if (this.patterns[this.currentPosition_]) {
this.patterns[this.currentPosition_].reset();
}
this.currentPosition_ = 0;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern matcher. Allows for simple searching of DOM
* using patterns descended from {@link goog.dom.pattern.AbstractPattern}.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.Matcher');
goog.require('goog.dom.TagIterator');
goog.require('goog.dom.pattern.MatchType');
goog.require('goog.iter');
// TODO(robbyw): Allow for backtracks of size > 1.
/**
* Given a set of patterns and a root node, this class tests the patterns in
* parallel.
*
* It is not (yet) a smart matcher - it doesn't do any advanced backtracking.
* Given the pattern <code>DIV, SPAN</code> the matcher will not match
* <code>DIV, DIV, SPAN</code> because it starts matching at the first
* <code>DIV</code>, fails to match <code>SPAN</code> at the second, and never
* backtracks to try again.
*
* It is also possible to have a set of complex patterns that when matched in
* parallel will miss some possible matches. Running multiple times will catch
* all matches eventually.
*
* @constructor
*/
goog.dom.pattern.Matcher = function() {
this.patterns_ = [];
this.callbacks_ = [];
};
/**
* Array of patterns to attempt to match in parallel.
*
* @type {Array.<goog.dom.pattern.AbstractPattern>}
* @private
*/
goog.dom.pattern.Matcher.prototype.patterns_;
/**
* Array of callbacks to call when a pattern is matched. The indexing is the
* same as the {@link #patterns_} array.
*
* @type {Array.<Function>}
* @private
*/
goog.dom.pattern.Matcher.prototype.callbacks_;
/**
* Adds a pattern to be matched. The callback can return an object whose keys
* are processing instructions.
*
* @param {goog.dom.pattern.AbstractPattern} pattern The pattern to add.
* @param {Function} callback Function to call when a match is found. Uses
* the above semantics.
*/
goog.dom.pattern.Matcher.prototype.addPattern = function(pattern, callback) {
this.patterns_.push(pattern);
this.callbacks_.push(callback);
};
/**
* Resets all the patterns.
*
* @private
*/
goog.dom.pattern.Matcher.prototype.reset_ = function() {
for (var i = 0, len = this.patterns_.length; i < len; i++) {
this.patterns_[i].reset();
}
};
/**
* Test the given node against all patterns.
*
* @param {goog.dom.TagIterator} position A position in a node walk that is
* located at the token to process.
* @return {boolean} Whether a pattern modified the position or tree
* and its callback resulted in DOM structure or position modification.
* @private
*/
goog.dom.pattern.Matcher.prototype.matchToken_ = function(position) {
for (var i = 0, len = this.patterns_.length; i < len; i++) {
var pattern = this.patterns_[i];
switch (pattern.matchToken(position.node, position.tagType)) {
case goog.dom.pattern.MatchType.MATCH:
case goog.dom.pattern.MatchType.BACKTRACK_MATCH:
var callback = this.callbacks_[i];
// Callbacks are allowed to modify the current position, but must
// return true if the do.
if (callback(pattern.matchedNode, position, pattern)) {
return true;
}
default:
// Do nothing.
break;
}
}
return false;
};
/**
* Match the set of patterns against a match tree.
*
* @param {Node} node The root node of the tree to match.
*/
goog.dom.pattern.Matcher.prototype.match = function(node) {
var position = new goog.dom.TagIterator(node);
this.reset_();
goog.iter.forEach(position, function() {
while (this.matchToken_(position)) {
// Since we've moved, our old pattern statuses don't make sense any more.
// Reset them.
this.reset_();
}
}, this);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 DOM pattern to match any children of a tag.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.pattern.AllChildren');
goog.require('goog.dom.pattern.AbstractPattern');
goog.require('goog.dom.pattern.MatchType');
/**
* Pattern object that matches any nodes at or below the current tree depth.
*
* @constructor
* @extends {goog.dom.pattern.AbstractPattern}
*/
goog.dom.pattern.AllChildren = function() {
};
goog.inherits(goog.dom.pattern.AllChildren, goog.dom.pattern.AbstractPattern);
/**
* Tracks the matcher's depth to detect the end of the tag.
*
* @type {number}
* @private
*/
goog.dom.pattern.AllChildren.prototype.depth_ = 0;
/**
* Test whether the given token is on the same level.
*
* @param {Node} token Token to match against.
* @param {goog.dom.TagWalkType} type The type of token.
* @return {goog.dom.pattern.MatchType} {@code MATCHING} if the token is on the
* same level or deeper and {@code BACKTRACK_MATCH} if not.
* @override
*/
goog.dom.pattern.AllChildren.prototype.matchToken = function(token, type) {
this.depth_ += type;
if (this.depth_ >= 0) {
return goog.dom.pattern.MatchType.MATCHING;
} else {
this.depth_ = 0;
return goog.dom.pattern.MatchType.BACKTRACK_MATCH;
}
};
/**
* Reset any internal state this pattern keeps.
* @override
*/
goog.dom.pattern.AllChildren.prototype.reset = function() {
this.depth_ = 0;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 Vendor prefix getters.
*/
goog.provide('goog.dom.vendor');
goog.require('goog.userAgent');
/**
* Returns the JS vendor prefix used in CSS properties. Different vendors
* use different methods of changing the case of the property names.
*
* @return {?string} The JS vendor prefix or null if there is none.
*/
goog.dom.vendor.getVendorJsPrefix = function() {
if (goog.userAgent.WEBKIT) {
return 'Webkit';
} else if (goog.userAgent.GECKO) {
return 'Moz';
} else if (goog.userAgent.IE) {
return 'ms';
} else if (goog.userAgent.OPERA) {
return 'O';
}
return null;
};
/**
* Returns the vendor prefix used in CSS properties.
*
* @return {?string} The vendor prefix or null if there is none.
*/
goog.dom.vendor.getVendorPrefix = function() {
if (goog.userAgent.WEBKIT) {
return '-webkit';
} else if (goog.userAgent.GECKO) {
return '-moz';
} else if (goog.userAgent.IE) {
return '-ms';
} else if (goog.userAgent.OPERA) {
return '-o';
}
return null;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Interface definitions for working with ranges
* in HTML documents.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.AbstractRange');
goog.provide('goog.dom.RangeIterator');
goog.provide('goog.dom.RangeType');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.SavedCaretRange');
goog.require('goog.dom.TagIterator');
goog.require('goog.userAgent');
/**
* Types of ranges.
* @enum {string}
*/
goog.dom.RangeType = {
TEXT: 'text',
CONTROL: 'control',
MULTI: 'mutli'
};
/**
* Creates a new selection with no properties. Do not use this constructor -
* use one of the goog.dom.Range.from* methods instead.
* @constructor
*/
goog.dom.AbstractRange = function() {
};
/**
* Gets the browser native selection object from the given window.
* @param {Window} win The window to get the selection object from.
* @return {Object} The browser native selection object, or null if it could
* not be retrieved.
*/
goog.dom.AbstractRange.getBrowserSelectionForWindow = function(win) {
if (win.getSelection) {
// W3C
return win.getSelection();
} else {
// IE
var doc = win.document;
var sel = doc.selection;
if (sel) {
// IE has a bug where it sometimes returns a selection from the wrong
// document. Catching these cases now helps us avoid problems later.
try {
var range = sel.createRange();
// Only TextRanges have a parentElement method.
if (range.parentElement) {
if (range.parentElement().document != doc) {
return null;
}
} else if (!range.length || range.item(0).document != doc) {
// For ControlRanges, check that the range has items, and that
// the first item in the range is in the correct document.
return null;
}
} catch (e) {
// If the selection is in the wrong document, and the wrong document is
// in a different domain, IE will throw an exception.
return null;
}
// TODO(user|robbyw) Sometimes IE 6 returns a selection instance
// when there is no selection. This object has a 'type' property equals
// to 'None' and a typeDetail property bound to undefined. Ideally this
// function should not return this instance.
return sel;
}
return null;
}
};
/**
* Tests if the given Object is a controlRange.
* @param {Object} range The range object to test.
* @return {boolean} Whether the given Object is a controlRange.
*/
goog.dom.AbstractRange.isNativeControlRange = function(range) {
// For now, tests for presence of a control range function.
return !!range && !!range.addElement;
};
/**
* @return {goog.dom.AbstractRange} A clone of this range.
*/
goog.dom.AbstractRange.prototype.clone = goog.abstractMethod;
/**
* @return {goog.dom.RangeType} The type of range represented by this object.
*/
goog.dom.AbstractRange.prototype.getType = goog.abstractMethod;
/**
* @return {Range|TextRange} The native browser range object.
*/
goog.dom.AbstractRange.prototype.getBrowserRangeObject = goog.abstractMethod;
/**
* Sets the native browser range object, overwriting any state this range was
* storing.
* @param {Range|TextRange} nativeRange The native browser range object.
* @return {boolean} Whether the given range was accepted. If not, the caller
* will need to call goog.dom.Range.createFromBrowserRange to create a new
* range object.
*/
goog.dom.AbstractRange.prototype.setBrowserRangeObject = function(nativeRange) {
return false;
};
/**
* @return {number} The number of text ranges in this range.
*/
goog.dom.AbstractRange.prototype.getTextRangeCount = goog.abstractMethod;
/**
* Get the i-th text range in this range. The behavior is undefined if
* i >= getTextRangeCount or i < 0.
* @param {number} i The range number to retrieve.
* @return {goog.dom.TextRange} The i-th text range.
*/
goog.dom.AbstractRange.prototype.getTextRange = goog.abstractMethod;
/**
* Gets an array of all text ranges this range is comprised of. For non-multi
* ranges, returns a single element array containing this.
* @return {Array.<goog.dom.TextRange>} Array of text ranges.
*/
goog.dom.AbstractRange.prototype.getTextRanges = function() {
var output = [];
for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
output.push(this.getTextRange(i));
}
return output;
};
/**
* @return {Node} The deepest node that contains the entire range.
*/
goog.dom.AbstractRange.prototype.getContainer = goog.abstractMethod;
/**
* Returns the deepest element in the tree that contains the entire range.
* @return {Element} The deepest element that contains the entire range.
*/
goog.dom.AbstractRange.prototype.getContainerElement = function() {
var node = this.getContainer();
return /** @type {Element} */ (
node.nodeType == goog.dom.NodeType.ELEMENT ? node : node.parentNode);
};
/**
* @return {Node} The element or text node the range starts in. For text
* ranges, the range comprises all text between the start and end position.
* For other types of range, start and end give bounds of the range but
* do not imply all nodes in those bounds are selected.
*/
goog.dom.AbstractRange.prototype.getStartNode = goog.abstractMethod;
/**
* @return {number} The offset into the node the range starts in. For text
* nodes, this is an offset into the node value. For elements, this is
* an offset into the childNodes array.
*/
goog.dom.AbstractRange.prototype.getStartOffset = goog.abstractMethod;
/**
* @return {goog.math.Coordinate} The coordinate of the selection start node
* and offset.
*/
goog.dom.AbstractRange.prototype.getStartPosition = goog.abstractMethod;
/**
* @return {Node} The element or text node the range ends in.
*/
goog.dom.AbstractRange.prototype.getEndNode = goog.abstractMethod;
/**
* @return {number} The offset into the node the range ends in. For text
* nodes, this is an offset into the node value. For elements, this is
* an offset into the childNodes array.
*/
goog.dom.AbstractRange.prototype.getEndOffset = goog.abstractMethod;
/**
* @return {goog.math.Coordinate} The coordinate of the selection end
* node and offset.
*/
goog.dom.AbstractRange.prototype.getEndPosition = goog.abstractMethod;
/**
* @return {Node} The element or text node the range is anchored at.
*/
goog.dom.AbstractRange.prototype.getAnchorNode = function() {
return this.isReversed() ? this.getEndNode() : this.getStartNode();
};
/**
* @return {number} The offset into the node the range is anchored at. For
* text nodes, this is an offset into the node value. For elements, this
* is an offset into the childNodes array.
*/
goog.dom.AbstractRange.prototype.getAnchorOffset = function() {
return this.isReversed() ? this.getEndOffset() : this.getStartOffset();
};
/**
* @return {Node} The element or text node the range is focused at - i.e. where
* the cursor is.
*/
goog.dom.AbstractRange.prototype.getFocusNode = function() {
return this.isReversed() ? this.getStartNode() : this.getEndNode();
};
/**
* @return {number} The offset into the node the range is focused at - i.e.
* where the cursor is. For text nodes, this is an offset into the node
* value. For elements, this is an offset into the childNodes array.
*/
goog.dom.AbstractRange.prototype.getFocusOffset = function() {
return this.isReversed() ? this.getStartOffset() : this.getEndOffset();
};
/**
* @return {boolean} Whether the selection is reversed.
*/
goog.dom.AbstractRange.prototype.isReversed = function() {
return false;
};
/**
* @return {Document} The document this selection is a part of.
*/
goog.dom.AbstractRange.prototype.getDocument = function() {
// Using start node in IE was crashing the browser in some cases so use
// getContainer for that browser. It's also faster for IE, but still slower
// than start node for other browsers so we continue to use getStartNode when
// it is not problematic. See bug 1687309.
return goog.dom.getOwnerDocument(goog.userAgent.IE ?
this.getContainer() : this.getStartNode());
};
/**
* @return {Window} The window this selection is a part of.
*/
goog.dom.AbstractRange.prototype.getWindow = function() {
return goog.dom.getWindow(this.getDocument());
};
/**
* Tests if this range contains the given range.
* @param {goog.dom.AbstractRange} range The range to test.
* @param {boolean=} opt_allowPartial If true, the range can be partially
* contained in the selection, otherwise the range must be entirely
* contained.
* @return {boolean} Whether this range contains the given range.
*/
goog.dom.AbstractRange.prototype.containsRange = goog.abstractMethod;
/**
* Tests if this range contains the given node.
* @param {Node} node The node to test for.
* @param {boolean=} opt_allowPartial If not set or false, the node must be
* entirely contained in the selection for this function to return true.
* @return {boolean} Whether this range contains the given node.
*/
goog.dom.AbstractRange.prototype.containsNode = function(node,
opt_allowPartial) {
return this.containsRange(goog.dom.Range.createFromNodeContents(node),
opt_allowPartial);
};
/**
* Tests whether this range is valid (i.e. whether its endpoints are still in
* the document). A range becomes invalid when, after this object was created,
* either one or both of its endpoints are removed from the document. Use of
* an invalid range can lead to runtime errors, particularly in IE.
* @return {boolean} Whether the range is valid.
*/
goog.dom.AbstractRange.prototype.isRangeInDocument = goog.abstractMethod;
/**
* @return {boolean} Whether the range is collapsed.
*/
goog.dom.AbstractRange.prototype.isCollapsed = goog.abstractMethod;
/**
* @return {string} The text content of the range.
*/
goog.dom.AbstractRange.prototype.getText = goog.abstractMethod;
/**
* Returns the HTML fragment this range selects. This is slow on all browsers.
* The HTML fragment may not be valid HTML, for instance if the user selects
* from a to b inclusively in the following html:
*
* >div<a>/div<b
*
* This method will return
*
* a</div>b
*
* If you need valid HTML, use {@link #getValidHtml} instead.
*
* @return {string} HTML fragment of the range, does not include context
* containing elements.
*/
goog.dom.AbstractRange.prototype.getHtmlFragment = goog.abstractMethod;
/**
* Returns valid HTML for this range. This is fast on IE, and semi-fast on
* other browsers.
* @return {string} Valid HTML of the range, including context containing
* elements.
*/
goog.dom.AbstractRange.prototype.getValidHtml = goog.abstractMethod;
/**
* Returns pastable HTML for this range. This guarantees that any child items
* that must have specific ancestors will have them, for instance all TDs will
* be contained in a TR in a TBODY in a TABLE and all LIs will be contained in
* a UL or OL as appropriate. This is semi-fast on all browsers.
* @return {string} Pastable HTML of the range, including context containing
* elements.
*/
goog.dom.AbstractRange.prototype.getPastableHtml = goog.abstractMethod;
/**
* Returns a RangeIterator over the contents of the range. Regardless of the
* direction of the range, the iterator will move in document order.
* @param {boolean=} opt_keys Unused for this iterator.
* @return {goog.dom.RangeIterator} An iterator over tags in the range.
*/
goog.dom.AbstractRange.prototype.__iterator__ = goog.abstractMethod;
// RANGE ACTIONS
/**
* Sets this range as the selection in its window.
*/
goog.dom.AbstractRange.prototype.select = goog.abstractMethod;
/**
* Removes the contents of the range from the document.
*/
goog.dom.AbstractRange.prototype.removeContents = goog.abstractMethod;
/**
* Inserts a node before (or after) the range. The range may be disrupted
* beyond recovery because of the way this splits nodes.
* @param {Node} node The node to insert.
* @param {boolean} before True to insert before, false to insert after.
* @return {Node} The node added to the document. This may be different
* than the node parameter because on IE we have to clone it.
*/
goog.dom.AbstractRange.prototype.insertNode = goog.abstractMethod;
/**
* Replaces the range contents with (possibly a copy of) the given node. The
* range may be disrupted beyond recovery because of the way this splits nodes.
* @param {Node} node The node to insert.
* @return {Node} The node added to the document. This may be different
* than the node parameter because on IE we have to clone it.
*/
goog.dom.AbstractRange.prototype.replaceContentsWithNode = function(node) {
if (!this.isCollapsed()) {
this.removeContents();
}
return this.insertNode(node, true);
};
/**
* Surrounds this range with the two given nodes. The range may be disrupted
* beyond recovery because of the way this splits nodes.
* @param {Element} startNode The node to insert at the start.
* @param {Element} endNode The node to insert at the end.
*/
goog.dom.AbstractRange.prototype.surroundWithNodes = goog.abstractMethod;
// SAVE/RESTORE
/**
* Saves the range so that if the start and end nodes are left alone, it can
* be restored.
* @return {goog.dom.SavedRange} A range representation that can be restored
* as long as the endpoint nodes of the selection are not modified.
*/
goog.dom.AbstractRange.prototype.saveUsingDom = goog.abstractMethod;
/**
* Saves the range using HTML carets. As long as the carets remained in the
* HTML, the range can be restored...even when the HTML is copied across
* documents.
* @return {goog.dom.SavedCaretRange?} A range representation that can be
* restored as long as carets are not removed. Returns null if carets
* could not be created.
*/
goog.dom.AbstractRange.prototype.saveUsingCarets = function() {
return (this.getStartNode() && this.getEndNode()) ?
new goog.dom.SavedCaretRange(this) : null;
};
// RANGE MODIFICATION
/**
* Collapses the range to one of its boundary points.
* @param {boolean} toAnchor Whether to collapse to the anchor of the range.
*/
goog.dom.AbstractRange.prototype.collapse = goog.abstractMethod;
// RANGE ITERATION
/**
* Subclass of goog.dom.TagIterator that iterates over a DOM range. It
* adds functions to determine the portion of each text node that is selected.
* @param {Node} node The node to start traversal at. When null, creates an
* empty iterator.
* @param {boolean=} opt_reverse Whether to traverse nodes in reverse.
* @constructor
* @extends {goog.dom.TagIterator}
*/
goog.dom.RangeIterator = function(node, opt_reverse) {
goog.dom.TagIterator.call(this, node, opt_reverse, true);
};
goog.inherits(goog.dom.RangeIterator, goog.dom.TagIterator);
/**
* @return {number} The offset into the current node, or -1 if the current node
* is not a text node.
*/
goog.dom.RangeIterator.prototype.getStartTextOffset = goog.abstractMethod;
/**
* @return {number} The end offset into the current node, or -1 if the current
* node is not a text node.
*/
goog.dom.RangeIterator.prototype.getEndTextOffset = goog.abstractMethod;
/**
* @return {Node} node The iterator's start node.
*/
goog.dom.RangeIterator.prototype.getStartNode = goog.abstractMethod;
/**
* @return {Node} The iterator's end node.
*/
goog.dom.RangeIterator.prototype.getEndNode = goog.abstractMethod;
/**
* @return {boolean} Whether a call to next will fail.
*/
goog.dom.RangeIterator.prototype.isLast = goog.abstractMethod;
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 Shared code for classlist_test.html.
*/
goog.provide('goog.dom.classlist_test');
goog.setTestOnly('goog.dom.classlist_test');
goog.require('goog.dom');
goog.require('goog.dom.classlist');
goog.require('goog.testing.jsunit');
var classlist = goog.dom.classlist;
function testGet() {
var el = document.createElement('div');
assertTrue(classlist.get(el).length == 0);
el.className = 'C';
assertElementsEquals(['C'], classlist.get(el));
el.className = 'C D';
assertElementsEquals(['C', 'D'], classlist.get(el));
el.className = 'C\nD';
assertElementsEquals(['C', 'D'], classlist.get(el));
el.className = ' C ';
assertElementsEquals(['C'], classlist.get(el));
}
function testContainsWithNewlines() {
var el = goog.dom.getElement('p1');
assertTrue('Should not have SOMECLASS', classlist.contains(el, 'SOMECLASS'));
assertTrue('Should also have OTHERCLASS',
classlist.contains(el, 'OTHERCLASS'));
assertFalse('Should not have WEIRDCLASS',
classlist.contains(el, 'WEIRDCLASS'));
}
function testContainsCaseSensitive() {
var el = goog.dom.getElement('p2');
assertFalse('Should not have camelcase',
classlist.contains(el, 'camelcase'));
assertFalse('Should not have CAMELCASE',
classlist.contains(el, 'CAMELCASE'));
assertTrue('Should have camelCase',
classlist.contains(el, 'camelCase'));
}
function testAddNotAddingMultiples() {
var el = document.createElement('div');
classlist.add(el, 'A');
assertEquals('A', el.className);
classlist.add(el, 'A');
assertEquals('A', el.className);
classlist.add(el, 'B', 'B');
assertEquals('A B', el.className);
}
function testAddCaseSensitive() {
var el = document.createElement('div');
classlist.add(el, 'A');
assertTrue(classlist.contains(el, 'A'));
assertFalse(classlist.contains(el, 'a'));
classlist.add(el, 'a');
assertTrue(classlist.contains(el, 'A'));
assertTrue(classlist.contains(el, 'a'));
assertEquals('A a', el.className);
}
function testAddAll() {
var elem = document.createElement('div');
elem.className = 'foo goog-bar';
goog.dom.classlist.addAll(elem, ['goog-baz', 'foo']);
assertEquals(3, classlist.get(elem).length);
assertTrue(goog.dom.classlist.contains(elem, 'foo'));
assertTrue(goog.dom.classlist.contains(elem, 'goog-bar'));
assertTrue(goog.dom.classlist.contains(elem, 'goog-baz'));
}
function testAddAllEmpty() {
var classes = 'foo bar';
var elem = document.createElement('div');
elem.className = classes;
goog.dom.classlist.addAll(elem, []);
assertEquals(elem.className, classes);
}
function testRemove() {
var el = document.createElement('div');
el.className = 'A B C';
classlist.remove(el, 'B');
assertEquals('A C', el.className);
}
function testRemoveCaseSensitive() {
var el = document.createElement('div');
el.className = 'A B C';
classlist.remove(el, 'b');
assertEquals('A B C', el.className);
}
function testRemoveAll() {
var elem = document.createElement('div');
elem.className = 'foo bar baz';
goog.dom.classlist.removeAll(elem, ['bar', 'foo']);
assertFalse(goog.dom.classlist.contains(elem, 'foo'));
assertFalse(goog.dom.classlist.contains(elem, 'bar'));
assertTrue(goog.dom.classlist.contains(elem, 'baz'));
}
function testRemoveAllOne() {
var elem = document.createElement('div');
elem.className = 'foo bar baz';
goog.dom.classlist.removeAll(elem, ['bar']);
assertFalse(goog.dom.classlist.contains(elem, 'bar'));
assertTrue(goog.dom.classlist.contains(elem, 'foo'));
assertTrue(goog.dom.classlist.contains(elem, 'baz'));
}
function testRemoveAllSomeNotPresent() {
var elem = document.createElement('div');
elem.className = 'foo bar baz';
goog.dom.classlist.removeAll(elem, ['a', 'bar']);
assertTrue(goog.dom.classlist.contains(elem, 'foo'));
assertFalse(goog.dom.classlist.contains(elem, 'bar'));
assertTrue(goog.dom.classlist.contains(elem, 'baz'));
}
function testRemoveAllCaseSensitive() {
var elem = document.createElement('div');
elem.className = 'foo bar baz';
goog.dom.classlist.removeAll(elem, ['BAR', 'foo']);
assertFalse(goog.dom.classlist.contains(elem, 'foo'));
assertTrue(goog.dom.classlist.contains(elem, 'bar'));
assertTrue(goog.dom.classlist.contains(elem, 'baz'));
}
function testEnable() {
var el = goog.dom.getElement('p1');
classlist.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class',
classlist.contains(el, 'SOMECLASS'));
classlist.enable(el, 'FIRST', false);
assertFalse('Should not have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class',
classlist.contains(el, 'SOMECLASS'));
classlist.enable(el, 'FIRST', true);
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class',
classlist.contains(el, 'SOMECLASS'));
}
function testEnableNotAddingMultiples() {
var el = document.createElement('div');
classlist.enable(el, 'A', true);
assertEquals('A', el.className);
classlist.enable(el, 'A', true);
assertEquals('A', el.className);
classlist.enable(el, 'B', 'B', true);
assertEquals('A B', el.className);
}
function testSwap() {
var el = goog.dom.getElement('p1');
classlist.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have FIRST class', classlist.contains(el, 'SOMECLASS'));
assertFalse('Should not have second class', classlist.contains(el, 'second'));
classlist.swap(el, 'FIRST', 'second');
assertFalse('Should not have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have FIRST class', classlist.contains(el, 'SOMECLASS'));
assertTrue('Should have second class', classlist.contains(el, 'second'));
classlist.swap(el, 'second', 'FIRST');
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have FIRST class', classlist.contains(el, 'SOMECLASS'));
assertFalse('Should not have second class', classlist.contains(el, 'second'));
}
function testToggle() {
var el = goog.dom.getElement('p1');
classlist.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classlist.contains(el, 'SOMECLASS'));
var ret = classlist.toggle(el, 'FIRST');
assertFalse('Should not have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classlist.contains(el, 'SOMECLASS'));
assertFalse('Return value should have been false', ret);
ret = classlist.toggle(el, 'FIRST');
assertTrue('Should have FIRST class', classlist.contains(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classlist.contains(el, 'SOMECLASS'));
assertTrue('Return value should have been true', ret);
}
function testAddRemoveString() {
var el = document.createElement('div');
el.className = 'A';
classlist.addRemove(el, 'A', 'B');
assertEquals('B', el.className);
classlist.addRemove(el, 'Z', 'C');
assertEquals('B C', el.className);
classlist.addRemove(el, 'C', 'D');
assertEquals('B D', el.className);
classlist.addRemove(el, 'D', 'B');
assertEquals('B', el.className);
}
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Utilities for working with IE control ranges.
*
* @author robbyw@google.com (Robby Walker)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.ControlRange');
goog.provide('goog.dom.ControlRangeIterator');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.AbstractMultiRange');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.RangeIterator');
goog.require('goog.dom.RangeType');
goog.require('goog.dom.SavedRange');
goog.require('goog.dom.TagWalkType');
goog.require('goog.dom.TextRange');
goog.require('goog.iter.StopIteration');
goog.require('goog.userAgent');
/**
* Create a new control selection with no properties. Do not use this
* constructor: use one of the goog.dom.Range.createFrom* methods instead.
* @constructor
* @extends {goog.dom.AbstractMultiRange}
*/
goog.dom.ControlRange = function() {
};
goog.inherits(goog.dom.ControlRange, goog.dom.AbstractMultiRange);
/**
* Create a new range wrapper from the given browser range object. Do not use
* this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Object} controlRange The browser range object.
* @return {goog.dom.ControlRange} A range wrapper object.
*/
goog.dom.ControlRange.createFromBrowserRange = function(controlRange) {
var range = new goog.dom.ControlRange();
range.range_ = controlRange;
return range;
};
/**
* Create a new range wrapper that selects the given element. Do not use
* this method directly - please use goog.dom.Range.createFrom* instead.
* @param {...Element} var_args The element(s) to select.
* @return {goog.dom.ControlRange} A range wrapper object.
*/
goog.dom.ControlRange.createFromElements = function(var_args) {
var range = goog.dom.getOwnerDocument(arguments[0]).body.createControlRange();
for (var i = 0, len = arguments.length; i < len; i++) {
range.addElement(arguments[i]);
}
return goog.dom.ControlRange.createFromBrowserRange(range);
};
/**
* The IE control range obejct.
* @type {Object}
* @private
*/
goog.dom.ControlRange.prototype.range_ = null;
/**
* Cached list of elements.
* @type {Array.<Element>?}
* @private
*/
goog.dom.ControlRange.prototype.elements_ = null;
/**
* Cached sorted list of elements.
* @type {Array.<Element>?}
* @private
*/
goog.dom.ControlRange.prototype.sortedElements_ = null;
// Method implementations
/**
* Clear cached values.
* @private
*/
goog.dom.ControlRange.prototype.clearCachedValues_ = function() {
this.elements_ = null;
this.sortedElements_ = null;
};
/** @override */
goog.dom.ControlRange.prototype.clone = function() {
return goog.dom.ControlRange.createFromElements.apply(this,
this.getElements());
};
/** @override */
goog.dom.ControlRange.prototype.getType = function() {
return goog.dom.RangeType.CONTROL;
};
/** @override */
goog.dom.ControlRange.prototype.getBrowserRangeObject = function() {
return this.range_ || document.body.createControlRange();
};
/** @override */
goog.dom.ControlRange.prototype.setBrowserRangeObject = function(nativeRange) {
if (!goog.dom.AbstractRange.isNativeControlRange(nativeRange)) {
return false;
}
this.range_ = nativeRange;
return true;
};
/** @override */
goog.dom.ControlRange.prototype.getTextRangeCount = function() {
return this.range_ ? this.range_.length : 0;
};
/** @override */
goog.dom.ControlRange.prototype.getTextRange = function(i) {
return goog.dom.TextRange.createFromNodeContents(this.range_.item(i));
};
/** @override */
goog.dom.ControlRange.prototype.getContainer = function() {
return goog.dom.findCommonAncestor.apply(null, this.getElements());
};
/** @override */
goog.dom.ControlRange.prototype.getStartNode = function() {
return this.getSortedElements()[0];
};
/** @override */
goog.dom.ControlRange.prototype.getStartOffset = function() {
return 0;
};
/** @override */
goog.dom.ControlRange.prototype.getEndNode = function() {
var sorted = this.getSortedElements();
var startsLast = /** @type {Node} */ (goog.array.peek(sorted));
return /** @type {Node} */ (goog.array.find(sorted, function(el) {
return goog.dom.contains(el, startsLast);
}));
};
/** @override */
goog.dom.ControlRange.prototype.getEndOffset = function() {
return this.getEndNode().childNodes.length;
};
// TODO(robbyw): Figure out how to unify getElements with TextRange API.
/**
* @return {Array.<Element>} Array of elements in the control range.
*/
goog.dom.ControlRange.prototype.getElements = function() {
if (!this.elements_) {
this.elements_ = [];
if (this.range_) {
for (var i = 0; i < this.range_.length; i++) {
this.elements_.push(this.range_.item(i));
}
}
}
return this.elements_;
};
/**
* @return {Array.<Element>} Array of elements comprising the control range,
* sorted by document order.
*/
goog.dom.ControlRange.prototype.getSortedElements = function() {
if (!this.sortedElements_) {
this.sortedElements_ = this.getElements().concat();
this.sortedElements_.sort(function(a, b) {
return a.sourceIndex - b.sourceIndex;
});
}
return this.sortedElements_;
};
/** @override */
goog.dom.ControlRange.prototype.isRangeInDocument = function() {
var returnValue = false;
try {
returnValue = goog.array.every(this.getElements(), function(element) {
// On IE, this throws an exception when the range is detached.
return goog.userAgent.IE ?
!!element.parentNode :
goog.dom.contains(element.ownerDocument.body, element);
});
} catch (e) {
// IE sometimes throws Invalid Argument errors for detached elements.
// Note: trying to return a value from the above try block can cause IE
// to crash. It is necessary to use the local returnValue.
}
return returnValue;
};
/** @override */
goog.dom.ControlRange.prototype.isCollapsed = function() {
return !this.range_ || !this.range_.length;
};
/** @override */
goog.dom.ControlRange.prototype.getText = function() {
// TODO(robbyw): What about for table selections? Should those have text?
return '';
};
/** @override */
goog.dom.ControlRange.prototype.getHtmlFragment = function() {
return goog.array.map(this.getSortedElements(), goog.dom.getOuterHtml).
join('');
};
/** @override */
goog.dom.ControlRange.prototype.getValidHtml = function() {
return this.getHtmlFragment();
};
/** @override */
goog.dom.ControlRange.prototype.getPastableHtml =
goog.dom.ControlRange.prototype.getValidHtml;
/** @override */
goog.dom.ControlRange.prototype.__iterator__ = function(opt_keys) {
return new goog.dom.ControlRangeIterator(this);
};
// RANGE ACTIONS
/** @override */
goog.dom.ControlRange.prototype.select = function() {
if (this.range_) {
this.range_.select();
}
};
/** @override */
goog.dom.ControlRange.prototype.removeContents = function() {
// TODO(robbyw): Test implementing with execCommand('Delete')
if (this.range_) {
var nodes = [];
for (var i = 0, len = this.range_.length; i < len; i++) {
nodes.push(this.range_.item(i));
}
goog.array.forEach(nodes, goog.dom.removeNode);
this.collapse(false);
}
};
/** @override */
goog.dom.ControlRange.prototype.replaceContentsWithNode = function(node) {
// Control selections have to have the node inserted before removing the
// selection contents because a collapsed control range doesn't have start or
// end nodes.
var result = this.insertNode(node, true);
if (!this.isCollapsed()) {
this.removeContents();
}
return result;
};
// SAVE/RESTORE
/** @override */
goog.dom.ControlRange.prototype.saveUsingDom = function() {
return new goog.dom.DomSavedControlRange_(this);
};
// RANGE MODIFICATION
/** @override */
goog.dom.ControlRange.prototype.collapse = function(toAnchor) {
// TODO(robbyw): Should this return a text range? If so, API needs to change.
this.range_ = null;
this.clearCachedValues_();
};
// SAVED RANGE OBJECTS
/**
* A SavedRange implementation using DOM endpoints.
* @param {goog.dom.ControlRange} range The range to save.
* @constructor
* @extends {goog.dom.SavedRange}
* @private
*/
goog.dom.DomSavedControlRange_ = function(range) {
/**
* The element list.
* @type {Array.<Element>}
* @private
*/
this.elements_ = range.getElements();
};
goog.inherits(goog.dom.DomSavedControlRange_, goog.dom.SavedRange);
/** @override */
goog.dom.DomSavedControlRange_.prototype.restoreInternal = function() {
var doc = this.elements_.length ?
goog.dom.getOwnerDocument(this.elements_[0]) : document;
var controlRange = doc.body.createControlRange();
for (var i = 0, len = this.elements_.length; i < len; i++) {
controlRange.addElement(this.elements_[i]);
}
return goog.dom.ControlRange.createFromBrowserRange(controlRange);
};
/** @override */
goog.dom.DomSavedControlRange_.prototype.disposeInternal = function() {
goog.dom.DomSavedControlRange_.superClass_.disposeInternal.call(this);
delete this.elements_;
};
// RANGE ITERATION
/**
* Subclass of goog.dom.TagIterator that iterates over a DOM range. It
* adds functions to determine the portion of each text node that is selected.
*
* @param {goog.dom.ControlRange?} range The range to traverse.
* @constructor
* @extends {goog.dom.RangeIterator}
*/
goog.dom.ControlRangeIterator = function(range) {
if (range) {
this.elements_ = range.getSortedElements();
this.startNode_ = this.elements_.shift();
this.endNode_ = /** @type {Node} */ (goog.array.peek(this.elements_)) ||
this.startNode_;
}
goog.dom.RangeIterator.call(this, this.startNode_, false);
};
goog.inherits(goog.dom.ControlRangeIterator, goog.dom.RangeIterator);
/**
* The first node in the selection.
* @type {Node}
* @private
*/
goog.dom.ControlRangeIterator.prototype.startNode_ = null;
/**
* The last node in the selection.
* @type {Node}
* @private
*/
goog.dom.ControlRangeIterator.prototype.endNode_ = null;
/**
* The list of elements left to traverse.
* @type {Array.<Element>?}
* @private
*/
goog.dom.ControlRangeIterator.prototype.elements_ = null;
/** @override */
goog.dom.ControlRangeIterator.prototype.getStartTextOffset = function() {
return 0;
};
/** @override */
goog.dom.ControlRangeIterator.prototype.getEndTextOffset = function() {
return 0;
};
/** @override */
goog.dom.ControlRangeIterator.prototype.getStartNode = function() {
return this.startNode_;
};
/** @override */
goog.dom.ControlRangeIterator.prototype.getEndNode = function() {
return this.endNode_;
};
/** @override */
goog.dom.ControlRangeIterator.prototype.isLast = function() {
return !this.depth && !this.elements_.length;
};
/**
* Move to the next position in the selection.
* Throws {@code goog.iter.StopIteration} when it passes the end of the range.
* @return {Node} The node at the next position.
* @override
*/
goog.dom.ControlRangeIterator.prototype.next = function() {
// Iterate over each element in the range, and all of its children.
if (this.isLast()) {
throw goog.iter.StopIteration;
} else if (!this.depth) {
var el = this.elements_.shift();
this.setPosition(el,
goog.dom.TagWalkType.START_TAG,
goog.dom.TagWalkType.START_TAG);
return el;
}
// Call the super function.
return goog.dom.ControlRangeIterator.superClass_.next.call(this);
};
/** @override */
goog.dom.ControlRangeIterator.prototype.copyFrom = function(other) {
this.elements_ = other.elements_;
this.startNode_ = other.startNode_;
this.endNode_ = other.endNode_;
goog.dom.ControlRangeIterator.superClass_.copyFrom.call(this, other);
};
/**
* @return {goog.dom.ControlRangeIterator} An identical iterator.
* @override
*/
goog.dom.ControlRangeIterator.prototype.clone = function() {
var copy = new goog.dom.ControlRangeIterator(null);
copy.copyFrom(this);
return copy;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Shared code for classes_test.html & classes_quirks_test.html.
*/
goog.provide('goog.dom.classes_test');
goog.setTestOnly('goog.dom.classes_test');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.testing.jsunit');
var classes = goog.dom.classes;
function testGet() {
var el = document.createElement('div');
assertArrayEquals([], goog.dom.classes.get(el));
el.className = 'C';
assertArrayEquals(['C'], goog.dom.classes.get(el));
el.className = 'C D';
assertArrayEquals(['C', 'D'], goog.dom.classes.get(el));
el.className = 'C\nD';
assertArrayEquals(['C', 'D'], goog.dom.classes.get(el));
el.className = ' C ';
assertArrayEquals(['C'], goog.dom.classes.get(el));
}
function testSetAddHasRemove() {
var el = goog.dom.getElement('p1');
classes.set(el, 'SOMECLASS');
assertTrue('Should have SOMECLASS', classes.has(el, 'SOMECLASS'));
classes.set(el, 'OTHERCLASS');
assertTrue('Should have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertFalse('Should not have SOMECLASS', classes.has(el, 'SOMECLASS'));
classes.add(el, 'WOOCLASS');
assertTrue('Should have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertTrue('Should have WOOCLASS', classes.has(el, 'WOOCLASS'));
classes.add(el, 'ACLASS', 'BCLASS', 'CCLASS');
assertTrue('Should have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertTrue('Should have WOOCLASS', classes.has(el, 'WOOCLASS'));
assertTrue('Should have ACLASS', classes.has(el, 'ACLASS'));
assertTrue('Should have BCLASS', classes.has(el, 'BCLASS'));
assertTrue('Should have CCLASS', classes.has(el, 'CCLASS'));
classes.remove(el, 'CCLASS');
assertTrue('Should have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertTrue('Should have WOOCLASS', classes.has(el, 'WOOCLASS'));
assertTrue('Should have ACLASS', classes.has(el, 'ACLASS'));
assertTrue('Should have BCLASS', classes.has(el, 'BCLASS'));
assertFalse('Should not have CCLASS', classes.has(el, 'CCLASS'));
classes.remove(el, 'ACLASS', 'BCLASS');
assertTrue('Should have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertTrue('Should have WOOCLASS', classes.has(el, 'WOOCLASS'));
assertFalse('Should not have ACLASS', classes.has(el, 'ACLASS'));
assertFalse('Should not have BCLASS', classes.has(el, 'BCLASS'));
}
// While support for this isn't implied in the method documentation,
// this is a frequently used pattern.
function testAddWithSpacesInClassName() {
var el = goog.dom.getElement('p1');
classes.add(el, 'CLASS1 CLASS2', 'CLASS3 CLASS4');
assertTrue('Should have CLASS1', classes.has(el, 'CLASS1'));
assertTrue('Should have CLASS2', classes.has(el, 'CLASS2'));
assertTrue('Should have CLASS3', classes.has(el, 'CLASS3'));
assertTrue('Should have CLASS4', classes.has(el, 'CLASS4'));
}
function testSwap() {
var el = goog.dom.getElement('p1');
classes.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have FIRST class', classes.has(el, 'SOMECLASS'));
assertFalse('Should not have second class', classes.has(el, 'second'));
classes.swap(el, 'FIRST', 'second');
assertFalse('Should not have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have FIRST class', classes.has(el, 'SOMECLASS'));
assertTrue('Should have second class', classes.has(el, 'second'));
classes.swap(el, 'second', 'FIRST');
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have FIRST class', classes.has(el, 'SOMECLASS'));
assertFalse('Should not have second class', classes.has(el, 'second'));
}
function testEnable() {
var el = goog.dom.getElement('p1');
classes.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
classes.enable(el, 'FIRST', false);
assertFalse('Should not have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
classes.enable(el, 'FIRST', true);
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
}
function testToggle() {
var el = goog.dom.getElement('p1');
classes.set(el, 'SOMECLASS FIRST');
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
classes.toggle(el, 'FIRST');
assertFalse('Should not have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
classes.toggle(el, 'FIRST');
assertTrue('Should have FIRST class', classes.has(el, 'FIRST'));
assertTrue('Should have SOMECLASS class', classes.has(el, 'SOMECLASS'));
}
function testAddNotAddingMultiples() {
var el = goog.dom.getElement('span6');
assertTrue(classes.add(el, 'A'));
assertEquals('A', el.className);
assertFalse(classes.add(el, 'A'));
assertEquals('A', el.className);
assertFalse(classes.add(el, 'B', 'B'));
assertEquals('A B', el.className);
}
function testAddRemoveString() {
var el = goog.dom.getElement('span6');
el.className = 'A';
goog.dom.classes.addRemove(el, 'A', 'B');
assertEquals('B', el.className);
goog.dom.classes.addRemove(el, null, 'C');
assertEquals('B C', el.className);
goog.dom.classes.addRemove(el, 'C', 'D');
assertEquals('B D', el.className);
goog.dom.classes.addRemove(el, 'D', null);
assertEquals('B', el.className);
}
function testAddRemoveArray() {
var el = goog.dom.getElement('span6');
el.className = 'A';
goog.dom.classes.addRemove(el, ['A'], ['B']);
assertEquals('B', el.className);
goog.dom.classes.addRemove(el, [], ['C']);
assertEquals('B C', el.className);
goog.dom.classes.addRemove(el, ['C'], ['D']);
assertEquals('B D', el.className);
goog.dom.classes.addRemove(el, ['D'], []);
assertEquals('B', el.className);
}
function testAddRemoveMultiple() {
var el = goog.dom.getElement('span6');
el.className = 'A';
goog.dom.classes.addRemove(el, ['A'], ['B', 'C', 'D']);
assertEquals('B C D', el.className);
goog.dom.classes.addRemove(el, [], ['E', 'F']);
assertEquals('B C D E F', el.className);
goog.dom.classes.addRemove(el, ['C', 'E'], []);
assertEquals('B D F', el.className);
goog.dom.classes.addRemove(el, ['B'], ['G']);
assertEquals('D F G', el.className);
}
// While support for this isn't implied in the method documentation,
// this is a frequently used pattern.
function testAddRemoveWithSpacesInClassName() {
var el = goog.dom.getElement('p1');
classes.addRemove(el, '', 'CLASS1 CLASS2');
assertTrue('Should have CLASS1', classes.has(el, 'CLASS1'));
assertTrue('Should have CLASS2', classes.has(el, 'CLASS2'));
}
function testHasWithNewlines() {
var el = goog.dom.getElement('p3');
assertTrue('Should have SOMECLASS', classes.has(el, 'SOMECLASS'));
assertTrue('Should also have OTHERCLASS', classes.has(el, 'OTHERCLASS'));
assertFalse('Should not have WEIRDCLASS', classes.has(el, 'WEIRDCLASS'));
}
function testEmptyClassNames() {
var el = goog.dom.getElement('span1');
// At the very least, make sure these do not error out.
assertFalse('Should not have an empty class', classes.has(el, ''));
classes.add(el, '');
classes.toggle(el, '');
assertFalse('Should not remove an empty class', classes.remove(el, ''));
classes.swap(el, '', 'OTHERCLASS');
classes.swap(el, 'TEST1', '');
classes.addRemove(el, '', '');
}
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 Utilities for detecting, adding and removing classes. Prefer
* this over goog.dom.classes for new code since it attempts to use classList
* (DOMTokenList: http://dom.spec.whatwg.org/#domtokenlist) which is faster
* and requires less code.
*
* Note: these utilities are meant to operate on HTMLElements and
* will not work on elements with differing interfaces (such as SVGElements).
*/
goog.provide('goog.dom.classlist');
goog.require('goog.array');
goog.require('goog.asserts');
/**
* Override this define at build-time if you know your target supports it.
* @define {boolean} Whether to use the classList property (DOMTokenList).
*/
goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST = false;
/**
* Enables use of the native DOMTokenList methods. See the spec at
* {@link http://dom.spec.whatwg.org/#domtokenlist}.
* @type {boolean}
* @private
*/
goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ =
goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST ||
typeof DOMTokenList != 'undefined';
/**
* Gets an array-like object of class names on an element.
* @param {Element} element DOM node to get the classes of.
* @return {!goog.array.ArrayLike} Class names on {@code element}.
*/
goog.dom.classlist.get = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element) {
return element.classList;
} :
function(element) {
var className = element.className;
// Some types of elements don't have a className in IE (e.g. iframes).
// Furthermore, in Firefox, className is not a string when the element is
// an SVG element.
return goog.isString(className) && className.match(/\S+/g) || [];
};
/**
* Sets the entire class name of an element.
* @param {Element} element DOM node to set class of.
* @param {string} className Class name(s) to apply to element.
*/
goog.dom.classlist.set = function(element, className) {
element.className = className;
};
/**
* Returns true if an element has a class. This method may throw a DOM
* exception for an invalid or empty class name if DOMTokenList is used.
* @param {Element} element DOM node to test.
* @param {string} className Class name to test for.
* @return {boolean} Whether element has the class.
*/
goog.dom.classlist.contains = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element, className) {
goog.asserts.assert(!!element.classList);
return element.classList.contains(className);
} :
function(element, className) {
return goog.array.contains(goog.dom.classlist.get(element), className);
};
/**
* Adds a class to an element. Does not add multiples of class names. This
* method may throw a DOM exception for an invalid or empty class name if
* DOMTokenList is used.
* @param {Element} element DOM node to add class to.
* @param {string} className Class name to add.
*/
goog.dom.classlist.add = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element, className) {
element.classList.add(className);
} :
function(element, className) {
if (!goog.dom.classlist.contains(element, className)) {
// Ensure we add a space if this is not the first class name added.
element.className += element.className.length > 0 ?
(' ' + className) : className;
}
};
/**
* Convenience method to add a number of class names at once.
* @param {Element} element The element to which to add classes.
* @param {goog.array.ArrayLike.<string>} classesToAdd An array-like object
* containing a collection of class names to add to the element.
* This method may throw a DOM exception if classesToAdd contains invalid
* or empty class names.
*/
goog.dom.classlist.addAll = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element, classesToAdd) {
goog.array.forEach(classesToAdd, function(className) {
goog.dom.classlist.add(element, className);
});
} :
function(element, classesToAdd) {
var classMap = {};
// Get all current class names into a map.
goog.array.forEach(goog.dom.classlist.get(element),
function(className) {
classMap[className] = true;
});
// Add new class names to the map.
goog.array.forEach(classesToAdd,
function(className) {
classMap[className] = true;
});
// Flatten the keys of the map into the className.
element.className = '';
for (var className in classMap) {
element.className += element.className.length > 0 ?
(' ' + className) : className;
}
};
/**
* Removes a class from an element. This method may throw a DOM exception
* for an invalid or empty class name if DOMTokenList is used.
* @param {Element} element DOM node to remove class from.
* @param {string} className Class name to remove.
*/
goog.dom.classlist.remove = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element, className) {
element.classList.remove(className);
} :
function(element, className) {
if (goog.dom.classlist.contains(element, className)) {
// Filter out the class name.
element.className = goog.array.filter(
goog.dom.classlist.get(element),
function(c) {
return c != className;
}).join(' ');
}
};
/**
* Removes a set of classes from an element. Prefer this call to
* repeatedly calling {@code goog.dom.classlist.remove} if you want to remove
* a large set of class names at once.
* @param {Element} element The element from which to remove classes.
* @param {goog.array.ArrayLike.<string>} classesToRemove An array-like object
* containing a collection of class names to remove from the element.
* This method may throw a DOM exception if classesToRemove contains invalid
* or empty class names.
*/
goog.dom.classlist.removeAll = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ?
function(element, classesToRemove) {
goog.array.forEach(classesToRemove, function(className) {
goog.dom.classlist.remove(element, className);
});
} :
function(element, classesToRemove) {
// Filter out those classes in classesToRemove.
element.className = goog.array.filter(
goog.dom.classlist.get(element),
function(className) {
// If this class is not one we are trying to remove,
// add it to the array of new class names.
return !goog.array.contains(classesToRemove, className);
}).join(' ');
};
/**
* Adds or removes a class depending on the enabled argument. This method
* may throw a DOM exception for an invalid or empty class name if DOMTokenList
* is used.
* @param {Element} element DOM node to add or remove the class on.
* @param {string} className Class name to add or remove.
* @param {boolean} enabled Whether to add or remove the class (true adds,
* false removes).
*/
goog.dom.classlist.enable = function(element, className, enabled) {
if (enabled) {
goog.dom.classlist.add(element, className);
} else {
goog.dom.classlist.remove(element, className);
}
};
/**
* Switches a class on an element from one to another without disturbing other
* classes. If the fromClass isn't removed, the toClass won't be added. This
* method may throw a DOM exception if the class names are empty or invalid.
* @param {Element} element DOM node to swap classes on.
* @param {string} fromClass Class to remove.
* @param {string} toClass Class to add.
* @return {boolean} Whether classes were switched.
*/
goog.dom.classlist.swap = function(element, fromClass, toClass) {
if (goog.dom.classlist.contains(element, fromClass)) {
goog.dom.classlist.remove(element, fromClass);
goog.dom.classlist.add(element, toClass);
return true;
}
return false;
};
/**
* Removes a class if an element has it, and adds it the element doesn't have
* it. Won't affect other classes on the node. This method may throw a DOM
* exception if the class name is empty or invalid.
* @param {Element} element DOM node to toggle class on.
* @param {string} className Class to toggle.
* @return {boolean} True if class was added, false if it was removed
* (in other words, whether element has the class after this function has
* been called).
*/
goog.dom.classlist.toggle = function(element, className) {
var add = !goog.dom.classlist.contains(element, className);
goog.dom.classlist.enable(element, className, add);
return add;
};
/**
* Adds and removes a class of an element. Unlike
* {@link goog.dom.classlist.swap}, this method adds the classToAdd regardless
* of whether the classToRemove was present and had been removed. This method
* may throw a DOM exception if the class names are empty or invalid.
*
* @param {Element} element DOM node to swap classes on.
* @param {string} classToRemove Class to remove.
* @param {string} classToAdd Class to add.
*/
goog.dom.classlist.addRemove = function(element, classToRemove, classToAdd) {
goog.dom.classlist.remove(element, classToRemove);
goog.dom.classlist.add(element, classToAdd);
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Utilities for working with ranges comprised of multiple
* sub-ranges.
*
* @author robbyw@google.com (Robby Walker)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.AbstractMultiRange');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.AbstractRange');
/**
* Creates a new multi range with no properties. Do not use this
* constructor: use one of the goog.dom.Range.createFrom* methods instead.
* @constructor
* @extends {goog.dom.AbstractRange}
*/
goog.dom.AbstractMultiRange = function() {
};
goog.inherits(goog.dom.AbstractMultiRange, goog.dom.AbstractRange);
/** @override */
goog.dom.AbstractMultiRange.prototype.containsRange = function(
otherRange, opt_allowPartial) {
// TODO(user): This will incorrectly return false if two (or more) adjacent
// elements are both in the control range, and are also in the text range
// being compared to.
var ranges = this.getTextRanges();
var otherRanges = otherRange.getTextRanges();
var fn = opt_allowPartial ? goog.array.some : goog.array.every;
return fn(otherRanges, function(otherRange) {
return goog.array.some(ranges, function(range) {
return range.containsRange(otherRange, opt_allowPartial);
});
});
};
/** @override */
goog.dom.AbstractMultiRange.prototype.insertNode = function(node, before) {
if (before) {
goog.dom.insertSiblingBefore(node, this.getStartNode());
} else {
goog.dom.insertSiblingAfter(node, this.getEndNode());
}
return node;
};
/** @override */
goog.dom.AbstractMultiRange.prototype.surroundWithNodes = function(startNode,
endNode) {
this.insertNode(startNode, true);
this.insertNode(endNode, false);
};
| JavaScript |
// Copyright 2005 The Closure Library Authors. 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 Object to store the offset from one node to another in a way
* that works on any similar DOM structure regardless of whether it is the same
* actual nodes.
*
*/
goog.provide('goog.dom.NodeOffset');
goog.require('goog.Disposable');
goog.require('goog.dom.TagName');
/**
* Object to store the offset from one node to another in a way that works on
* any similar DOM structure regardless of whether it is the same actual nodes.
* @param {Node} node The node to get the offset for.
* @param {Node} baseNode The node to calculate the offset from.
* @extends {goog.Disposable}
* @constructor
*/
goog.dom.NodeOffset = function(node, baseNode) {
goog.Disposable.call(this);
/**
* A stack of childNode offsets.
* @type {Array.<number>}
* @private
*/
this.offsetStack_ = [];
/**
* A stack of childNode names.
* @type {Array.<string>}
* @private
*/
this.nameStack_ = [];
while (node && node.nodeName != goog.dom.TagName.BODY && node != baseNode) {
// Compute the sibling offset.
var siblingOffset = 0;
var sib = node.previousSibling;
while (sib) {
sib = sib.previousSibling;
++siblingOffset;
}
this.offsetStack_.unshift(siblingOffset);
this.nameStack_.unshift(node.nodeName);
node = node.parentNode;
}
};
goog.inherits(goog.dom.NodeOffset, goog.Disposable);
/**
* @return {string} A string representation of this object.
* @override
*/
goog.dom.NodeOffset.prototype.toString = function() {
var strs = [];
var name;
for (var i = 0; name = this.nameStack_[i]; i++) {
strs.push(this.offsetStack_[i] + ',' + name);
}
return strs.join('\n');
};
/**
* Walk the dom and find the node relative to baseNode. Returns null on
* failure.
* @param {Node} baseNode The node to start walking from. Should be equivalent
* to the node passed in to the constructor, in that it should have the
* same contents.
* @return {Node} The node relative to baseNode, or null on failure.
*/
goog.dom.NodeOffset.prototype.findTargetNode = function(baseNode) {
var name;
var curNode = baseNode;
for (var i = 0; name = this.nameStack_[i]; ++i) {
curNode = curNode.childNodes[this.offsetStack_[i]];
// Sanity check and make sure the element names match.
if (!curNode || curNode.nodeName != name) {
return null;
}
}
return curNode;
};
/** @override */
goog.dom.NodeOffset.prototype.disposeInternal = function() {
delete this.offsetStack_;
delete this.nameStack_;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 generic interface for saving and restoring ranges.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.SavedRange');
goog.require('goog.Disposable');
goog.require('goog.debug.Logger');
/**
* Abstract interface for a saved range.
* @constructor
* @extends {goog.Disposable}
*/
goog.dom.SavedRange = function() {
goog.Disposable.call(this);
};
goog.inherits(goog.dom.SavedRange, goog.Disposable);
/**
* Logging object.
* @type {goog.debug.Logger}
* @private
*/
goog.dom.SavedRange.logger_ =
goog.debug.Logger.getLogger('goog.dom.SavedRange');
/**
* Restores the range and by default disposes of the saved copy. Take note:
* this means the by default SavedRange objects are single use objects.
* @param {boolean=} opt_stayAlive Whether this SavedRange should stay alive
* (not be disposed) after restoring the range. Defaults to false (dispose).
* @return {goog.dom.AbstractRange} The restored range.
*/
goog.dom.SavedRange.prototype.restore = function(opt_stayAlive) {
if (this.isDisposed()) {
goog.dom.SavedRange.logger_.severe(
'Disposed SavedRange objects cannot be restored.');
}
var range = this.restoreInternal();
if (!opt_stayAlive) {
this.dispose();
}
return range;
};
/**
* Internal method to restore the saved range.
* @return {goog.dom.AbstractRange} The restored range.
*/
goog.dom.SavedRange.prototype.restoreInternal = goog.abstractMethod;
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Simple struct for endpoints of a range.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.RangeEndpoint');
/**
* Constants for selection endpoints.
* @enum {number}
*/
goog.dom.RangeEndpoint = {
START: 1,
END: 0
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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 Methods for annotating occurrences of query terms in text or
* in a DOM tree. Adapted from Gmail code.
*
*/
goog.provide('goog.dom.annotate');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.string');
/**
* Calls {@code annotateFn} for each occurrence of a search term in text nodes
* under {@code node}. Returns the number of hits.
*
* @param {Node} node A DOM node.
* @param {Array} terms An array of [searchTerm, matchWholeWordOnly] tuples.
* The matchWholeWordOnly value is a per-term attribute because some terms
* may be CJK, while others are not. (For correctness, matchWholeWordOnly
* should always be false for CJK terms.).
* @param {Function} annotateFn A function that takes
* (1) the number of the term that is "hit",
* (2) the HTML string (search term) to be annotated,
* and returns the annotated term as an HTML string.
* @param {*=} opt_ignoreCase Whether to ignore the case of the query
* terms when looking for matches.
* @param {Array.<string>=} opt_classesToSkip Nodes with one of these CSS class
* names (and its descendants) will be skipped.
* @param {number=} opt_maxMs Number of milliseconds after which this function,
* if still annotating, should stop and return.
*
* @return {boolean} Whether any terms were annotated.
*/
goog.dom.annotate.annotateTerms = function(node, terms, annotateFn,
opt_ignoreCase,
opt_classesToSkip,
opt_maxMs) {
if (opt_ignoreCase) {
terms = goog.dom.annotate.lowercaseTerms_(terms);
}
var stopTime = opt_maxMs > 0 ? goog.now() + opt_maxMs : 0;
return goog.dom.annotate.annotateTermsInNode_(
node, terms, annotateFn, opt_ignoreCase, opt_classesToSkip || [],
stopTime, 0);
};
/**
* The maximum recursion depth allowed. Any DOM nodes deeper than this are
* ignored.
* @type {number}
* @private
*/
goog.dom.annotate.MAX_RECURSION_ = 200;
/**
* The node types whose descendants should not be affected by annotation.
* @type {Array}
* @private
*/
goog.dom.annotate.NODES_TO_SKIP_ = ['SCRIPT', 'STYLE', 'TEXTAREA'];
/**
* Recursive helper function.
*
* @param {Node} node A DOM node.
* @param {Array} terms An array of [searchTerm, matchWholeWordOnly] tuples.
* The matchWholeWordOnly value is a per-term attribute because some terms
* may be CJK, while others are not. (For correctness, matchWholeWordOnly
* should always be false for CJK terms.).
* @param {Function} annotateFn function(number, string) : string A function
* that takes :
* (1) the number of the term that is "hit",
* (2) the HTML string (search term) to be annotated,
* and returns the annotated term as an HTML string.
* @param {*} ignoreCase Whether to ignore the case of the query terms
* when looking for matches.
* @param {Array.<string>} classesToSkip Nodes with one of these CSS class
* names will be skipped (as will their descendants).
* @param {number} stopTime Deadline for annotation operation (ignored if 0).
* @param {number} recursionLevel How deep this recursive call is; pass the
* value 0 in the initial call.
* @return {boolean} Whether any terms were annotated.
* @private
*/
goog.dom.annotate.annotateTermsInNode_ =
function(node, terms, annotateFn, ignoreCase, classesToSkip,
stopTime, recursionLevel) {
if ((stopTime > 0 && goog.now() >= stopTime) ||
recursionLevel > goog.dom.annotate.MAX_RECURSION_) {
return false;
}
var annotated = false;
if (node.nodeType == goog.dom.NodeType.TEXT) {
var html = goog.dom.annotate.helpAnnotateText_(node.nodeValue, terms,
annotateFn, ignoreCase);
if (html != null) {
// Replace the text with the annotated html. First we put the html into
// a temporary node, to get its DOM structure. To avoid adding a wrapper
// element as a side effect, we'll only actually use the temporary node's
// children.
var tempNode = goog.dom.getOwnerDocument(node).createElement('SPAN');
tempNode.innerHTML = html;
var parentNode = node.parentNode;
var nodeToInsert;
while ((nodeToInsert = tempNode.firstChild) != null) {
// Each parentNode.insertBefore call removes the inserted node from
// tempNode's list of children.
parentNode.insertBefore(nodeToInsert, node);
}
parentNode.removeChild(node);
annotated = true;
}
} else if (node.hasChildNodes() &&
!goog.array.contains(goog.dom.annotate.NODES_TO_SKIP_,
node.tagName)) {
var classes = node.className.split(/\s+/);
var skip = goog.array.some(classes, function(className) {
return goog.array.contains(classesToSkip, className);
});
if (!skip) {
++recursionLevel;
var curNode = node.firstChild;
var numTermsAnnotated = 0;
while (curNode) {
var nextNode = curNode.nextSibling;
var curNodeAnnotated = goog.dom.annotate.annotateTermsInNode_(
curNode, terms, annotateFn, ignoreCase, classesToSkip,
stopTime, recursionLevel);
annotated = annotated || curNodeAnnotated;
curNode = nextNode;
}
}
}
return annotated;
};
/**
* Regular expression that matches non-word characters.
*
* Performance note: Testing a one-character string using this regex is as fast
* as the equivalent string test ("a-zA-Z0-9_".indexOf(c) < 0), give or take a
* few percent. (The regex is about 5% faster in IE 6 and about 4% slower in
* Firefox 1.5.) If performance becomes critical, it may be better to convert
* the character to a numerical char code and check whether it falls in the
* word character ranges. A quick test suggests that could be 33% faster.
*
* @type {RegExp}
* @private
*/
goog.dom.annotate.NONWORD_RE_ = /\W/;
/**
* Annotates occurrences of query terms in plain text. This process consists of
* identifying all occurrences of all query terms, calling a provided function
* to get the appropriate replacement HTML for each occurrence, and
* HTML-escaping all the text.
*
* @param {string} text The plain text to be searched.
* @param {Array} terms An array of
* [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
* The matchWholeWordOnly value is a per-term attribute because some terms
* may be CJK, while others are not. (For correctness, matchWholeWordOnly
* should always be false for CJK terms.).
* @param {Function} annotateFn {function(number, string) : string} A function
* that takes
* (1) the number of the term that is "hit",
* (2) the HTML string (search term) to be annotated,
* and returns the annotated term as an HTML string.
* @param {*=} opt_ignoreCase Whether to ignore the case of the query
* terms when looking for matches.
* @return {?string} The HTML equivalent of {@code text} with terms
* annotated, or null if the text did not contain any of the terms.
*/
goog.dom.annotate.annotateText = function(text, terms, annotateFn,
opt_ignoreCase) {
if (opt_ignoreCase) {
terms = goog.dom.annotate.lowercaseTerms_(terms);
}
return goog.dom.annotate.helpAnnotateText_(text, terms, annotateFn,
opt_ignoreCase);
};
/**
* Annotates occurrences of query terms in plain text. This process consists of
* identifying all occurrences of all query terms, calling a provided function
* to get the appropriate replacement HTML for each occurrence, and
* HTML-escaping all the text.
*
* @param {string} text The plain text to be searched.
* @param {Array} terms An array of
* [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
* If {@code ignoreCase} is true, each search term must already be lowercase.
* The matchWholeWordOnly value is a per-term attribute because some terms
* may be CJK, while others are not. (For correctness, matchWholeWordOnly
* should always be false for CJK terms.).
* @param {Function} annotateFn {function(number, string) : string} A function
* that takes
* (1) the number of the term that is "hit",
* (2) the HTML string (search term) to be annotated,
* and returns the annotated term as an HTML string.
* @param {*} ignoreCase Whether to ignore the case of the query terms
* when looking for matches.
* @return {?string} The HTML equivalent of {@code text} with terms
* annotated, or null if the text did not contain any of the terms.
* @private
*/
goog.dom.annotate.helpAnnotateText_ = function(text, terms, annotateFn,
ignoreCase) {
var hit = false;
var resultHtml = null;
var textToSearch = ignoreCase ? text.toLowerCase() : text;
var textLen = textToSearch.length;
var numTerms = terms.length;
// Each element will be an array of hit positions for the term.
var termHits = new Array(numTerms);
// First collect all the hits into allHits.
for (var i = 0; i < numTerms; i++) {
var term = terms[i];
var hits = [];
var termText = term[0];
if (termText != '') {
var matchWholeWordOnly = term[1];
var termLen = termText.length;
var pos = 0;
// Find each hit for term t and append to termHits.
while (pos < textLen) {
var hitPos = textToSearch.indexOf(termText, pos);
if (hitPos == -1) {
break;
} else {
var prevCharPos = hitPos - 1;
var nextCharPos = hitPos + termLen;
if (!matchWholeWordOnly ||
((prevCharPos < 0 ||
goog.dom.annotate.NONWORD_RE_.test(
textToSearch.charAt(prevCharPos))) &&
(nextCharPos >= textLen ||
goog.dom.annotate.NONWORD_RE_.test(
textToSearch.charAt(nextCharPos))))) {
hits.push(hitPos);
hit = true;
}
pos = hitPos + termLen;
}
}
}
termHits[i] = hits;
}
if (hit) {
var html = [];
var pos = 0;
while (true) {
// First determine which of the n terms is the next hit.
var termIndexOfNextHit;
var posOfNextHit = -1;
for (var i = 0; i < numTerms; i++) {
var hits = termHits[i];
// pull off the position of the next hit of term t
// (it's always the first in the array because we're shifting
// hits off the front of the array as we process them)
// this is the next candidate to consider for the next overall hit
if (!goog.array.isEmpty(hits)) {
var hitPos = hits[0];
// Discard any hits embedded in the previous hit.
while (hitPos >= 0 && hitPos < pos) {
hits.shift();
hitPos = goog.array.isEmpty(hits) ? -1 : hits[0];
}
if (hitPos >= 0 && (posOfNextHit < 0 || hitPos < posOfNextHit)) {
termIndexOfNextHit = i;
posOfNextHit = hitPos;
}
}
}
// Quit if there are no more hits.
if (posOfNextHit < 0) break;
// Remove the next hit from our hit list.
termHits[termIndexOfNextHit].shift();
// Append everything from the end of the last hit up to this one.
html.push(goog.string.htmlEscape(text.substr(pos, posOfNextHit - pos)));
// Append the annotated term.
var termLen = terms[termIndexOfNextHit][0].length;
var termHtml = goog.string.htmlEscape(text.substr(posOfNextHit, termLen));
html.push(annotateFn(termIndexOfNextHit, termHtml));
pos = posOfNextHit + termLen;
}
// Append everything after the last hit.
html.push(goog.string.htmlEscape(text.substr(pos)));
return html.join('');
} else {
return null;
}
};
/**
* Converts terms to lowercase.
*
* @param {Array} terms An array of
* [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
* @return {Array} An array of
* [{string} searchTerm, {boolean} matchWholeWordOnly] tuples.
* @private
*/
goog.dom.annotate.lowercaseTerms_ = function(terms) {
var lowercaseTerms = [];
for (var i = 0; i < terms.length; ++i) {
var term = terms[i];
lowercaseTerms[i] = [term[0].toLowerCase(), term[1]];
}
return lowercaseTerms;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the browser range interface.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.browserrange.AbstractRange');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.RangeEndpoint');
goog.require('goog.dom.TagName');
goog.require('goog.dom.TextRangeIterator');
goog.require('goog.iter');
goog.require('goog.math.Coordinate');
goog.require('goog.string');
goog.require('goog.string.StringBuffer');
goog.require('goog.userAgent');
/**
* The constructor for abstract ranges. Don't call this from subclasses.
* @constructor
*/
goog.dom.browserrange.AbstractRange = function() {
};
/**
* @return {goog.dom.browserrange.AbstractRange} A clone of this range.
*/
goog.dom.browserrange.AbstractRange.prototype.clone = goog.abstractMethod;
/**
* Returns the browser native implementation of the range. Please refrain from
* using this function - if you find you need the range please add wrappers for
* the functionality you need rather than just using the native range.
* @return {Range|TextRange} The browser native range object.
*/
goog.dom.browserrange.AbstractRange.prototype.getBrowserRange =
goog.abstractMethod;
/**
* Returns the deepest node in the tree that contains the entire range.
* @return {Node} The deepest node that contains the entire range.
*/
goog.dom.browserrange.AbstractRange.prototype.getContainer =
goog.abstractMethod;
/**
* Returns the node the range starts in.
* @return {Node} The element or text node the range starts in.
*/
goog.dom.browserrange.AbstractRange.prototype.getStartNode =
goog.abstractMethod;
/**
* Returns the offset into the node the range starts in.
* @return {number} The offset into the node the range starts in. For text
* nodes, this is an offset into the node value. For elements, this is
* an offset into the childNodes array.
*/
goog.dom.browserrange.AbstractRange.prototype.getStartOffset =
goog.abstractMethod;
/**
* @return {goog.math.Coordinate} The coordinate of the selection start node
* and offset.
*/
goog.dom.browserrange.AbstractRange.prototype.getStartPosition = function() {
goog.asserts.assert(this.range_.getClientRects,
'Getting selection coordinates is not supported.');
var rects = this.range_.getClientRects();
if (rects.length) {
return new goog.math.Coordinate(rects[0]['left'], rects[0]['top']);
}
return null;
};
/**
* Returns the node the range ends in.
* @return {Node} The element or text node the range ends in.
*/
goog.dom.browserrange.AbstractRange.prototype.getEndNode =
goog.abstractMethod;
/**
* Returns the offset into the node the range ends in.
* @return {number} The offset into the node the range ends in. For text
* nodes, this is an offset into the node value. For elements, this is
* an offset into the childNodes array.
*/
goog.dom.browserrange.AbstractRange.prototype.getEndOffset =
goog.abstractMethod;
/**
* @return {goog.math.Coordinate} The coordinate of the selection end node
* and offset.
*/
goog.dom.browserrange.AbstractRange.prototype.getEndPosition = function() {
goog.asserts.assert(this.range_.getClientRects,
'Getting selection coordinates is not supported.');
var rects = this.range_.getClientRects();
if (rects.length) {
var lastRect = goog.array.peek(rects);
return new goog.math.Coordinate(lastRect['right'], lastRect['bottom']);
}
return null;
};
/**
* Compares one endpoint of this range with the endpoint of another browser
* native range object.
* @param {Range|TextRange} range The browser native range to compare against.
* @param {goog.dom.RangeEndpoint} thisEndpoint The endpoint of this range
* to compare with.
* @param {goog.dom.RangeEndpoint} otherEndpoint The endpoint of the other
* range to compare with.
* @return {number} 0 if the endpoints are equal, negative if this range
* endpoint comes before the other range endpoint, and positive otherwise.
*/
goog.dom.browserrange.AbstractRange.prototype.compareBrowserRangeEndpoints =
goog.abstractMethod;
/**
* Tests if this range contains the given range.
* @param {goog.dom.browserrange.AbstractRange} abstractRange The range to test.
* @param {boolean=} opt_allowPartial If not set or false, the range must be
* entirely contained in the selection for this function to return true.
* @return {boolean} Whether this range contains the given range.
*/
goog.dom.browserrange.AbstractRange.prototype.containsRange =
function(abstractRange, opt_allowPartial) {
// IE sometimes misreports the boundaries for collapsed ranges. So if the
// other range is collapsed, make sure the whole range is contained. This is
// logically equivalent, and works around IE's bug.
var checkPartial = opt_allowPartial && !abstractRange.isCollapsed();
var range = abstractRange.getBrowserRange();
var start = goog.dom.RangeEndpoint.START, end = goog.dom.RangeEndpoint.END;
/** {@preserveTry} */
try {
if (checkPartial) {
// There are two ways to not overlap. Being before, and being after.
// Before is represented by this.end before range.start: comparison < 0.
// After is represented by this.start after range.end: comparison > 0.
// The below is the negation of not overlapping.
return this.compareBrowserRangeEndpoints(range, end, start) >= 0 &&
this.compareBrowserRangeEndpoints(range, start, end) <= 0;
} else {
// Return true if this range bounds the parameter range from both sides.
return this.compareBrowserRangeEndpoints(range, end, end) >= 0 &&
this.compareBrowserRangeEndpoints(range, start, start) <= 0;
}
} catch (e) {
if (!goog.userAgent.IE) {
throw e;
}
// IE sometimes throws exceptions when one range is invalid, i.e. points
// to a node that has been removed from the document. Return false in this
// case.
return false;
}
};
/**
* Tests if this range contains the given node.
* @param {Node} node The node to test.
* @param {boolean=} opt_allowPartial If not set or false, the node must be
* entirely contained in the selection for this function to return true.
* @return {boolean} Whether this range contains the given node.
*/
goog.dom.browserrange.AbstractRange.prototype.containsNode = function(node,
opt_allowPartial) {
return this.containsRange(
goog.dom.browserrange.createRangeFromNodeContents(node),
opt_allowPartial);
};
/**
* Tests if the selection is collapsed - i.e. is just a caret.
* @return {boolean} Whether the range is collapsed.
*/
goog.dom.browserrange.AbstractRange.prototype.isCollapsed =
goog.abstractMethod;
/**
* @return {string} The text content of the range.
*/
goog.dom.browserrange.AbstractRange.prototype.getText =
goog.abstractMethod;
/**
* Returns the HTML fragment this range selects. This is slow on all browsers.
* @return {string} HTML fragment of the range, does not include context
* containing elements.
*/
goog.dom.browserrange.AbstractRange.prototype.getHtmlFragment = function() {
var output = new goog.string.StringBuffer();
goog.iter.forEach(this, function(node, ignore, it) {
if (node.nodeType == goog.dom.NodeType.TEXT) {
output.append(goog.string.htmlEscape(node.nodeValue.substring(
it.getStartTextOffset(), it.getEndTextOffset())));
} else if (node.nodeType == goog.dom.NodeType.ELEMENT) {
if (it.isEndTag()) {
if (goog.dom.canHaveChildren(node)) {
output.append('</' + node.tagName + '>');
}
} else {
var shallow = node.cloneNode(false);
var html = goog.dom.getOuterHtml(shallow);
if (goog.userAgent.IE && node.tagName == goog.dom.TagName.LI) {
// For an LI, IE just returns "<li>" with no closing tag
output.append(html);
} else {
var index = html.lastIndexOf('<');
output.append(index ? html.substr(0, index) : html);
}
}
}
}, this);
return output.toString();
};
/**
* Returns valid HTML for this range. This is fast on IE, and semi-fast on
* other browsers.
* @return {string} Valid HTML of the range, including context containing
* elements.
*/
goog.dom.browserrange.AbstractRange.prototype.getValidHtml =
goog.abstractMethod;
/**
* Returns a RangeIterator over the contents of the range. Regardless of the
* direction of the range, the iterator will move in document order.
* @param {boolean=} opt_keys Unused for this iterator.
* @return {goog.dom.RangeIterator} An iterator over tags in the range.
*/
goog.dom.browserrange.AbstractRange.prototype.__iterator__ = function(
opt_keys) {
return new goog.dom.TextRangeIterator(this.getStartNode(),
this.getStartOffset(), this.getEndNode(), this.getEndOffset());
};
// SELECTION MODIFICATION
/**
* Set this range as the selection in its window.
* @param {boolean=} opt_reverse Whether to select the range in reverse,
* if possible.
*/
goog.dom.browserrange.AbstractRange.prototype.select =
goog.abstractMethod;
/**
* Removes the contents of the range from the document. As a side effect, the
* selection will be collapsed. The behavior of content removal is normalized
* across browsers. For instance, IE sometimes creates extra text nodes that
* a W3C browser does not. That behavior is corrected for.
*/
goog.dom.browserrange.AbstractRange.prototype.removeContents =
goog.abstractMethod;
/**
* Surrounds the text range with the specified element (on Mozilla) or with a
* clone of the specified element (on IE). Returns a reference to the
* surrounding element if the operation was successful; returns null if the
* operation failed.
* @param {Element} element The element with which the selection is to be
* surrounded.
* @return {Element} The surrounding element (same as the argument on Mozilla,
* but not on IE), or null if unsuccessful.
*/
goog.dom.browserrange.AbstractRange.prototype.surroundContents =
goog.abstractMethod;
/**
* Inserts a node before (or after) the range. The range may be disrupted
* beyond recovery because of the way this splits nodes.
* @param {Node} node The node to insert.
* @param {boolean} before True to insert before, false to insert after.
* @return {Node} The node added to the document. This may be different
* than the node parameter because on IE we have to clone it.
*/
goog.dom.browserrange.AbstractRange.prototype.insertNode =
goog.abstractMethod;
/**
* Surrounds this range with the two given nodes. The range may be disrupted
* beyond recovery because of the way this splits nodes.
* @param {Element} startNode The node to insert at the start.
* @param {Element} endNode The node to insert at the end.
*/
goog.dom.browserrange.AbstractRange.prototype.surroundWithNodes =
goog.abstractMethod;
/**
* Collapses the range to one of its boundary points.
* @param {boolean} toStart Whether to collapse to the start of the range.
*/
goog.dom.browserrange.AbstractRange.prototype.collapse =
goog.abstractMethod;
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 Definition of the Opera specific range wrapper. Inherits most
* functionality from W3CRange, but adds exceptions as necessary.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
*/
goog.provide('goog.dom.browserrange.OperaRange');
goog.require('goog.dom.browserrange.W3cRange');
/**
* The constructor for Opera specific browser ranges.
* @param {Range} range The range object.
* @constructor
* @extends {goog.dom.browserrange.W3cRange}
*/
goog.dom.browserrange.OperaRange = function(range) {
goog.dom.browserrange.W3cRange.call(this, range);
};
goog.inherits(goog.dom.browserrange.OperaRange, goog.dom.browserrange.W3cRange);
/**
* Creates a range object that selects the given node's text.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.OperaRange} A Opera range wrapper object.
*/
goog.dom.browserrange.OperaRange.createFromNodeContents = function(node) {
return new goog.dom.browserrange.OperaRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
};
/**
* Creates a range object that selects between the given nodes.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the node to start.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the node to end.
* @return {goog.dom.browserrange.OperaRange} A wrapper object.
*/
goog.dom.browserrange.OperaRange.createFromNodes = function(startNode,
startOffset, endNode, endOffset) {
return new goog.dom.browserrange.OperaRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
startOffset, endNode, endOffset));
};
/** @override */
goog.dom.browserrange.OperaRange.prototype.selectInternal = function(
selection, reversed) {
// Avoid using addRange as we have to removeAllRanges first, which
// blurs editable fields in Opera.
selection.collapse(this.getStartNode(), this.getStartOffset());
if (this.getEndNode() != this.getStartNode() ||
this.getEndOffset() != this.getStartOffset()) {
selection.extend(this.getEndNode(), this.getEndOffset());
}
// This can happen if the range isn't in an editable field.
if (selection.rangeCount == 0) {
selection.addRange(this.range_);
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the W3C spec following range wrapper.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.browserrange.W3cRange');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.RangeEndpoint');
goog.require('goog.dom.browserrange.AbstractRange');
goog.require('goog.string');
/**
* The constructor for W3C specific browser ranges.
* @param {Range} range The range object.
* @constructor
* @extends {goog.dom.browserrange.AbstractRange}
*/
goog.dom.browserrange.W3cRange = function(range) {
this.range_ = range;
};
goog.inherits(goog.dom.browserrange.W3cRange,
goog.dom.browserrange.AbstractRange);
/**
* Returns a browser range spanning the given node's contents.
* @param {Node} node The node to select.
* @return {Range} A browser range spanning the node's contents.
* @protected
*/
goog.dom.browserrange.W3cRange.getBrowserRangeForNode = function(node) {
var nodeRange = goog.dom.getOwnerDocument(node).createRange();
if (node.nodeType == goog.dom.NodeType.TEXT) {
nodeRange.setStart(node, 0);
nodeRange.setEnd(node, node.length);
} else {
if (!goog.dom.browserrange.canContainRangeEndpoint(node)) {
var rangeParent = node.parentNode;
var rangeStartOffset = goog.array.indexOf(rangeParent.childNodes, node);
nodeRange.setStart(rangeParent, rangeStartOffset);
nodeRange.setEnd(rangeParent, rangeStartOffset + 1);
} else {
var tempNode, leaf = node;
while ((tempNode = leaf.firstChild) &&
goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
leaf = tempNode;
}
nodeRange.setStart(leaf, 0);
leaf = node;
while ((tempNode = leaf.lastChild) &&
goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
leaf = tempNode;
}
nodeRange.setEnd(leaf, leaf.nodeType == goog.dom.NodeType.ELEMENT ?
leaf.childNodes.length : leaf.length);
}
}
return nodeRange;
};
/**
* Returns a browser range spanning the given nodes.
* @param {Node} startNode The node to start with - should not be a BR.
* @param {number} startOffset The offset within the start node.
* @param {Node} endNode The node to end with - should not be a BR.
* @param {number} endOffset The offset within the end node.
* @return {Range} A browser range spanning the node's contents.
* @protected
*/
goog.dom.browserrange.W3cRange.getBrowserRangeForNodes = function(startNode,
startOffset, endNode, endOffset) {
// Create and return the range.
var nodeRange = goog.dom.getOwnerDocument(startNode).createRange();
nodeRange.setStart(startNode, startOffset);
nodeRange.setEnd(endNode, endOffset);
return nodeRange;
};
/**
* Creates a range object that selects the given node's text.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.W3cRange} A Gecko range wrapper object.
*/
goog.dom.browserrange.W3cRange.createFromNodeContents = function(node) {
return new goog.dom.browserrange.W3cRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
};
/**
* Creates a range object that selects between the given nodes.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the start node.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the end node.
* @return {goog.dom.browserrange.W3cRange} A wrapper object.
*/
goog.dom.browserrange.W3cRange.createFromNodes = function(startNode,
startOffset, endNode, endOffset) {
return new goog.dom.browserrange.W3cRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
startOffset, endNode, endOffset));
};
/**
* @return {goog.dom.browserrange.W3cRange} A clone of this range.
* @override
*/
goog.dom.browserrange.W3cRange.prototype.clone = function() {
return new this.constructor(this.range_.cloneRange());
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getBrowserRange = function() {
return this.range_;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getContainer = function() {
return this.range_.commonAncestorContainer;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getStartNode = function() {
return this.range_.startContainer;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getStartOffset = function() {
return this.range_.startOffset;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getEndNode = function() {
return this.range_.endContainer;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getEndOffset = function() {
return this.range_.endOffset;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.compareBrowserRangeEndpoints =
function(range, thisEndpoint, otherEndpoint) {
return this.range_.compareBoundaryPoints(
otherEndpoint == goog.dom.RangeEndpoint.START ?
(thisEndpoint == goog.dom.RangeEndpoint.START ?
goog.global['Range'].START_TO_START :
goog.global['Range'].START_TO_END) :
(thisEndpoint == goog.dom.RangeEndpoint.START ?
goog.global['Range'].END_TO_START :
goog.global['Range'].END_TO_END),
/** @type {Range} */ (range));
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.isCollapsed = function() {
return this.range_.collapsed;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getText = function() {
return this.range_.toString();
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.getValidHtml = function() {
var div = goog.dom.getDomHelper(this.range_.startContainer).createDom('div');
div.appendChild(this.range_.cloneContents());
var result = div.innerHTML;
if (goog.string.startsWith(result, '<') ||
!this.isCollapsed() && !goog.string.contains(result, '<')) {
// We attempt to mimic IE, which returns no containing element when a
// only text nodes are selected, does return the containing element when
// the selection is empty, and does return the element when multiple nodes
// are selected.
return result;
}
var container = this.getContainer();
container = container.nodeType == goog.dom.NodeType.ELEMENT ? container :
container.parentNode;
var html = goog.dom.getOuterHtml(
/** @type {Element} */ (container.cloneNode(false)));
return html.replace('>', '>' + result);
};
// SELECTION MODIFICATION
/** @override */
goog.dom.browserrange.W3cRange.prototype.select = function(reverse) {
var win = goog.dom.getWindow(goog.dom.getOwnerDocument(this.getStartNode()));
this.selectInternal(win.getSelection(), reverse);
};
/**
* Select this range.
* @param {Selection} selection Browser selection object.
* @param {*} reverse Whether to select this range in reverse.
* @protected
*/
goog.dom.browserrange.W3cRange.prototype.selectInternal = function(selection,
reverse) {
// Browser-specific tricks are needed to create reversed selections
// programatically. For this generic W3C codepath, ignore the reverse
// parameter.
selection.removeAllRanges();
selection.addRange(this.range_);
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.removeContents = function() {
var range = this.range_;
range.extractContents();
if (range.startContainer.hasChildNodes()) {
// Remove any now empty nodes surrounding the extracted contents.
var rangeStartContainer =
range.startContainer.childNodes[range.startOffset];
if (rangeStartContainer) {
var rangePrevious = rangeStartContainer.previousSibling;
if (goog.dom.getRawTextContent(rangeStartContainer) == '') {
goog.dom.removeNode(rangeStartContainer);
}
if (rangePrevious && goog.dom.getRawTextContent(rangePrevious) == '') {
goog.dom.removeNode(rangePrevious);
}
}
}
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.surroundContents = function(element) {
this.range_.surroundContents(element);
return element;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.insertNode = function(node, before) {
var range = this.range_.cloneRange();
range.collapse(before);
range.insertNode(node);
range.detach();
return node;
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.surroundWithNodes = function(
startNode, endNode) {
var win = goog.dom.getWindow(
goog.dom.getOwnerDocument(this.getStartNode()));
var selectionRange = goog.dom.Range.createFromWindow(win);
if (selectionRange) {
var sNode = selectionRange.getStartNode();
var eNode = selectionRange.getEndNode();
var sOffset = selectionRange.getStartOffset();
var eOffset = selectionRange.getEndOffset();
}
var clone1 = this.range_.cloneRange();
var clone2 = this.range_.cloneRange();
clone1.collapse(false);
clone2.collapse(true);
clone1.insertNode(endNode);
clone2.insertNode(startNode);
clone1.detach();
clone2.detach();
if (selectionRange) {
// There are 4 ways that surroundWithNodes can wreck the saved
// selection object. All of them happen when an inserted node splits
// a text node, and one of the end points of the selection was in the
// latter half of that text node.
//
// Clients of this library should use saveUsingCarets to avoid this
// problem. Unfortunately, saveUsingCarets uses this method, so that's
// not really an option for us. :( We just recompute the offsets.
var isInsertedNode = function(n) {
return n == startNode || n == endNode;
};
if (sNode.nodeType == goog.dom.NodeType.TEXT) {
while (sOffset > sNode.length) {
sOffset -= sNode.length;
do {
sNode = sNode.nextSibling;
} while (isInsertedNode(sNode));
}
}
if (eNode.nodeType == goog.dom.NodeType.TEXT) {
while (eOffset > eNode.length) {
eOffset -= eNode.length;
do {
eNode = eNode.nextSibling;
} while (isInsertedNode(eNode));
}
}
goog.dom.Range.createFromNodes(
sNode, /** @type {number} */ (sOffset),
eNode, /** @type {number} */ (eOffset)).select();
}
};
/** @override */
goog.dom.browserrange.W3cRange.prototype.collapse = function(toStart) {
this.range_.collapse(toStart);
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the WebKit specific range wrapper. Inherits most
* functionality from W3CRange, but adds exceptions as necessary.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.browserrange.WebKitRange');
goog.require('goog.dom.RangeEndpoint');
goog.require('goog.dom.browserrange.W3cRange');
goog.require('goog.userAgent');
/**
* The constructor for WebKit specific browser ranges.
* @param {Range} range The range object.
* @constructor
* @extends {goog.dom.browserrange.W3cRange}
*/
goog.dom.browserrange.WebKitRange = function(range) {
goog.dom.browserrange.W3cRange.call(this, range);
};
goog.inherits(goog.dom.browserrange.WebKitRange,
goog.dom.browserrange.W3cRange);
/**
* Creates a range object that selects the given node's text.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.WebKitRange} A WebKit range wrapper object.
*/
goog.dom.browserrange.WebKitRange.createFromNodeContents = function(node) {
return new goog.dom.browserrange.WebKitRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
};
/**
* Creates a range object that selects between the given nodes.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the start node.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the end node.
* @return {goog.dom.browserrange.WebKitRange} A wrapper object.
*/
goog.dom.browserrange.WebKitRange.createFromNodes = function(startNode,
startOffset, endNode, endOffset) {
return new goog.dom.browserrange.WebKitRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
startOffset, endNode, endOffset));
};
/** @override */
goog.dom.browserrange.WebKitRange.prototype.compareBrowserRangeEndpoints =
function(range, thisEndpoint, otherEndpoint) {
// Webkit pre-528 has some bugs where compareBoundaryPoints() doesn't work the
// way it is supposed to, but if we reverse the sense of two comparisons,
// it works fine.
// https://bugs.webkit.org/show_bug.cgi?id=20738
if (goog.userAgent.isVersion('528')) {
return (goog.dom.browserrange.WebKitRange.superClass_.
compareBrowserRangeEndpoints.call(
this, range, thisEndpoint, otherEndpoint));
}
return this.range_.compareBoundaryPoints(
otherEndpoint == goog.dom.RangeEndpoint.START ?
(thisEndpoint == goog.dom.RangeEndpoint.START ?
goog.global['Range'].START_TO_START :
goog.global['Range'].END_TO_START) : // Sense reversed
(thisEndpoint == goog.dom.RangeEndpoint.START ?
goog.global['Range'].START_TO_END : // Sense reversed
goog.global['Range'].END_TO_END),
/** @type {Range} */ (range));
};
/** @override */
goog.dom.browserrange.WebKitRange.prototype.selectInternal = function(
selection, reversed) {
// Unselect everything. This addresses a bug in Webkit where it sometimes
// caches the old selection.
// https://bugs.webkit.org/show_bug.cgi?id=20117
selection.removeAllRanges();
if (reversed) {
selection.setBaseAndExtent(this.getEndNode(), this.getEndOffset(),
this.getStartNode(), this.getStartOffset());
} else {
selection.setBaseAndExtent(this.getStartNode(), this.getStartOffset(),
this.getEndNode(), this.getEndOffset());
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the IE browser specific range wrapper.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.browserrange.IeRange');
goog.require('goog.array');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.RangeEndpoint');
goog.require('goog.dom.TagName');
goog.require('goog.dom.browserrange.AbstractRange');
goog.require('goog.string');
/**
* The constructor for IE specific browser ranges.
* @param {TextRange} range The range object.
* @param {Document} doc The document the range exists in.
* @constructor
* @extends {goog.dom.browserrange.AbstractRange}
*/
goog.dom.browserrange.IeRange = function(range, doc) {
/**
* The browser range object this class wraps.
* @type {TextRange}
* @private
*/
this.range_ = range;
/**
* The document the range exists in.
* @type {Document}
* @private
*/
this.doc_ = doc;
};
goog.inherits(goog.dom.browserrange.IeRange,
goog.dom.browserrange.AbstractRange);
/**
* Logging object.
* @type {goog.debug.Logger}
* @private
*/
goog.dom.browserrange.IeRange.logger_ =
goog.debug.Logger.getLogger('goog.dom.browserrange.IeRange');
/**
* Returns a browser range spanning the given node's contents.
* @param {Node} node The node to select.
* @return {TextRange} A browser range spanning the node's contents.
* @private
*/
goog.dom.browserrange.IeRange.getBrowserRangeForNode_ = function(node) {
var nodeRange = goog.dom.getOwnerDocument(node).body.createTextRange();
if (node.nodeType == goog.dom.NodeType.ELEMENT) {
// Elements are easy.
nodeRange.moveToElementText(node);
// Note(user) : If there are no child nodes of the element, the
// range.htmlText includes the element's outerHTML. The range created above
// is not collapsed, and should be collapsed explicitly.
// Example : node = <div></div>
// But if the node is sth like <br>, it shouldnt be collapsed.
if (goog.dom.browserrange.canContainRangeEndpoint(node) &&
!node.childNodes.length) {
nodeRange.collapse(false);
}
} else {
// Text nodes are hard.
// Compute the offset from the nearest element related position.
var offset = 0;
var sibling = node;
while (sibling = sibling.previousSibling) {
var nodeType = sibling.nodeType;
if (nodeType == goog.dom.NodeType.TEXT) {
offset += sibling.length;
} else if (nodeType == goog.dom.NodeType.ELEMENT) {
// Move to the space after this element.
nodeRange.moveToElementText(sibling);
break;
}
}
if (!sibling) {
nodeRange.moveToElementText(node.parentNode);
}
nodeRange.collapse(!sibling);
if (offset) {
nodeRange.move('character', offset);
}
nodeRange.moveEnd('character', node.length);
}
return nodeRange;
};
/**
* Returns a browser range spanning the given nodes.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the start node.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the end node.
* @return {TextRange} A browser range spanning the node's contents.
* @private
*/
goog.dom.browserrange.IeRange.getBrowserRangeForNodes_ = function(startNode,
startOffset, endNode, endOffset) {
// Create a range starting at the correct start position.
var child, collapse = false;
if (startNode.nodeType == goog.dom.NodeType.ELEMENT) {
if (startOffset > startNode.childNodes.length) {
goog.dom.browserrange.IeRange.logger_.severe(
'Cannot have startOffset > startNode child count');
}
child = startNode.childNodes[startOffset];
collapse = !child;
startNode = child || startNode.lastChild || startNode;
startOffset = 0;
}
var leftRange = goog.dom.browserrange.IeRange.
getBrowserRangeForNode_(startNode);
// This happens only when startNode is a text node.
if (startOffset) {
leftRange.move('character', startOffset);
}
// The range movements in IE are still an approximation to the standard W3C
// behavior, and IE has its trickery when it comes to htmlText and text
// properties of the range. So we short-circuit computation whenever we can.
if (startNode == endNode && startOffset == endOffset) {
leftRange.collapse(true);
return leftRange;
}
// This can happen only when the startNode is an element, and there is no node
// at the given offset. We start at the last point inside the startNode in
// that case.
if (collapse) {
leftRange.collapse(false);
}
// Create a range that ends at the right position.
collapse = false;
if (endNode.nodeType == goog.dom.NodeType.ELEMENT) {
if (endOffset > endNode.childNodes.length) {
goog.dom.browserrange.IeRange.logger_.severe(
'Cannot have endOffset > endNode child count');
}
child = endNode.childNodes[endOffset];
endNode = child || endNode.lastChild || endNode;
endOffset = 0;
collapse = !child;
}
var rightRange = goog.dom.browserrange.IeRange.
getBrowserRangeForNode_(endNode);
rightRange.collapse(!collapse);
if (endOffset) {
rightRange.moveEnd('character', endOffset);
}
// Merge and return.
leftRange.setEndPoint('EndToEnd', rightRange);
return leftRange;
};
/**
* Create a range object that selects the given node's text.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.IeRange} An IE range wrapper object.
*/
goog.dom.browserrange.IeRange.createFromNodeContents = function(node) {
var range = new goog.dom.browserrange.IeRange(
goog.dom.browserrange.IeRange.getBrowserRangeForNode_(node),
goog.dom.getOwnerDocument(node));
if (!goog.dom.browserrange.canContainRangeEndpoint(node)) {
range.startNode_ = range.endNode_ = range.parentNode_ = node.parentNode;
range.startOffset_ = goog.array.indexOf(range.parentNode_.childNodes, node);
range.endOffset_ = range.startOffset_ + 1;
} else {
// Note(user) : Emulate the behavior of W3CRange - Go to deepest possible
// range containers on both edges. It seems W3CRange did this to match the
// IE behavior, and now it is a circle. Changing W3CRange may break clients
// in all sorts of ways.
var tempNode, leaf = node;
while ((tempNode = leaf.firstChild) &&
goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
leaf = tempNode;
}
range.startNode_ = leaf;
range.startOffset_ = 0;
leaf = node;
while ((tempNode = leaf.lastChild) &&
goog.dom.browserrange.canContainRangeEndpoint(tempNode)) {
leaf = tempNode;
}
range.endNode_ = leaf;
range.endOffset_ = leaf.nodeType == goog.dom.NodeType.ELEMENT ?
leaf.childNodes.length : leaf.length;
range.parentNode_ = node;
}
return range;
};
/**
* Static method that returns the proper type of browser range.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the start node.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the end node.
* @return {goog.dom.browserrange.AbstractRange} A wrapper object.
*/
goog.dom.browserrange.IeRange.createFromNodes = function(startNode,
startOffset, endNode, endOffset) {
var range = new goog.dom.browserrange.IeRange(
goog.dom.browserrange.IeRange.getBrowserRangeForNodes_(startNode,
startOffset, endNode, endOffset),
goog.dom.getOwnerDocument(startNode));
range.startNode_ = startNode;
range.startOffset_ = startOffset;
range.endNode_ = endNode;
range.endOffset_ = endOffset;
return range;
};
// Even though goog.dom.TextRange does similar caching to below, keeping these
// caches allows for better performance in the get*Offset methods.
/**
* Lazy cache of the node containing the entire selection.
* @type {Node}
* @private
*/
goog.dom.browserrange.IeRange.prototype.parentNode_ = null;
/**
* Lazy cache of the node containing the start of the selection.
* @type {Node}
* @private
*/
goog.dom.browserrange.IeRange.prototype.startNode_ = null;
/**
* Lazy cache of the node containing the end of the selection.
* @type {Node}
* @private
*/
goog.dom.browserrange.IeRange.prototype.endNode_ = null;
/**
* Lazy cache of the offset in startNode_ where this range starts.
* @type {number}
* @private
*/
goog.dom.browserrange.IeRange.prototype.startOffset_ = -1;
/**
* Lazy cache of the offset in endNode_ where this range ends.
* @type {number}
* @private
*/
goog.dom.browserrange.IeRange.prototype.endOffset_ = -1;
/**
* @return {goog.dom.browserrange.IeRange} A clone of this range.
* @override
*/
goog.dom.browserrange.IeRange.prototype.clone = function() {
var range = new goog.dom.browserrange.IeRange(
this.range_.duplicate(), this.doc_);
range.parentNode_ = this.parentNode_;
range.startNode_ = this.startNode_;
range.endNode_ = this.endNode_;
return range;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getBrowserRange = function() {
return this.range_;
};
/**
* Clears the cached values for containers.
* @private
*/
goog.dom.browserrange.IeRange.prototype.clearCachedValues_ = function() {
this.parentNode_ = this.startNode_ = this.endNode_ = null;
this.startOffset_ = this.endOffset_ = -1;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getContainer = function() {
if (!this.parentNode_) {
var selectText = this.range_.text;
// If the selection ends with spaces, we need to remove these to get the
// parent container of only the real contents. This is to get around IE's
// inconsistency where it selects the spaces after a word when you double
// click, but leaves out the spaces during execCommands.
var range = this.range_.duplicate();
// We can't use goog.string.trimRight, as that will remove other whitespace
// too.
var rightTrimmedSelectText = selectText.replace(/ +$/, '');
var numSpacesAtEnd = selectText.length - rightTrimmedSelectText.length;
if (numSpacesAtEnd) {
range.moveEnd('character', -numSpacesAtEnd);
}
// Get the parent node. This should be the end, but alas, it is not.
var parent = range.parentElement();
var htmlText = range.htmlText;
var htmlTextLen = goog.string.stripNewlines(htmlText).length;
if (this.isCollapsed() && htmlTextLen > 0) {
return (this.parentNode_ = parent);
}
// Deal with selection bug where IE thinks one of the selection's children
// is actually the selection's parent. Relies on the assumption that the
// HTML text of the parent container is longer than the length of the
// selection's HTML text.
// Also note IE will sometimes insert \r and \n whitespace, which should be
// disregarded. Otherwise the loop may run too long and return wrong parent
while (htmlTextLen > goog.string.stripNewlines(parent.outerHTML).length) {
parent = parent.parentNode;
}
// Deal with IE's selecting the outer tags when you double click
// If the innerText is the same, then we just want the inner node
while (parent.childNodes.length == 1 &&
parent.innerText == goog.dom.browserrange.IeRange.getNodeText_(
parent.firstChild)) {
// A container should be an element which can have children or a text
// node. Elements like IMG, BR, etc. can not be containers.
if (!goog.dom.browserrange.canContainRangeEndpoint(parent.firstChild)) {
break;
}
parent = parent.firstChild;
}
// If the selection is empty, we may need to do extra work to position it
// properly.
if (selectText.length == 0) {
parent = this.findDeepestContainer_(parent);
}
this.parentNode_ = parent;
}
return this.parentNode_;
};
/**
* Helper method to find the deepest parent for this range, starting
* the search from {@code node}, which must contain the range.
* @param {Node} node The node to start the search from.
* @return {Node} The deepest parent for this range.
* @private
*/
goog.dom.browserrange.IeRange.prototype.findDeepestContainer_ = function(node) {
var childNodes = node.childNodes;
for (var i = 0, len = childNodes.length; i < len; i++) {
var child = childNodes[i];
if (goog.dom.browserrange.canContainRangeEndpoint(child)) {
var childRange =
goog.dom.browserrange.IeRange.getBrowserRangeForNode_(child);
var start = goog.dom.RangeEndpoint.START;
var end = goog.dom.RangeEndpoint.END;
// There are two types of erratic nodes where the range over node has
// different htmlText than the node's outerHTML.
// Case 1 - A node with magic child. In this case :
// nodeRange.htmlText shows ('<p> </p>), while
// node.outerHTML doesn't show the magic node (<p></p>).
// Case 2 - Empty span. In this case :
// node.outerHTML shows '<span></span>'
// node.htmlText is just empty string ''.
var isChildRangeErratic = (childRange.htmlText != child.outerHTML);
// Moreover the inRange comparison fails only when the
var isNativeInRangeErratic = this.isCollapsed() && isChildRangeErratic;
// In case 2 mentioned above, childRange is also collapsed. So we need to
// compare start of this range with both start and end of child range.
var inChildRange = isNativeInRangeErratic ?
(this.compareBrowserRangeEndpoints(childRange, start, start) >= 0 &&
this.compareBrowserRangeEndpoints(childRange, start, end) <= 0) :
this.range_.inRange(childRange);
if (inChildRange) {
return this.findDeepestContainer_(child);
}
}
}
return node;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getStartNode = function() {
if (!this.startNode_) {
this.startNode_ = this.getEndpointNode_(goog.dom.RangeEndpoint.START);
if (this.isCollapsed()) {
this.endNode_ = this.startNode_;
}
}
return this.startNode_;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getStartOffset = function() {
if (this.startOffset_ < 0) {
this.startOffset_ = this.getOffset_(goog.dom.RangeEndpoint.START);
if (this.isCollapsed()) {
this.endOffset_ = this.startOffset_;
}
}
return this.startOffset_;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getEndNode = function() {
if (this.isCollapsed()) {
return this.getStartNode();
}
if (!this.endNode_) {
this.endNode_ = this.getEndpointNode_(goog.dom.RangeEndpoint.END);
}
return this.endNode_;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getEndOffset = function() {
if (this.isCollapsed()) {
return this.getStartOffset();
}
if (this.endOffset_ < 0) {
this.endOffset_ = this.getOffset_(goog.dom.RangeEndpoint.END);
if (this.isCollapsed()) {
this.startOffset_ = this.endOffset_;
}
}
return this.endOffset_;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.compareBrowserRangeEndpoints = function(
range, thisEndpoint, otherEndpoint) {
return this.range_.compareEndPoints(
(thisEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End') +
'To' +
(otherEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End'),
range);
};
/**
* Recurses to find the correct node for the given endpoint.
* @param {goog.dom.RangeEndpoint} endpoint The endpoint to get the node for.
* @param {Node=} opt_node Optional node to start the search from.
* @return {Node} The deepest node containing the endpoint.
* @private
*/
goog.dom.browserrange.IeRange.prototype.getEndpointNode_ = function(endpoint,
opt_node) {
/** @type {Node} */
var node = opt_node || this.getContainer();
// If we're at a leaf in the DOM, we're done.
if (!node || !node.firstChild) {
return node;
}
var start = goog.dom.RangeEndpoint.START, end = goog.dom.RangeEndpoint.END;
var isStartEndpoint = endpoint == start;
// Find the first/last child that overlaps the selection.
// NOTE(user) : One of the children can be the magic node. This
// node will have only nodeType property as valid and accessible. All other
// dom related properties like ownerDocument, parentNode, nextSibling etc
// cause error when accessed. Therefore use the for-loop on childNodes to
// iterate.
for (var j = 0, length = node.childNodes.length; j < length; j++) {
var i = isStartEndpoint ? j : length - j - 1;
var child = node.childNodes[i];
var childRange;
try {
childRange = goog.dom.browserrange.createRangeFromNodeContents(child);
} catch (e) {
// If the child is the magic node, then the above will throw
// error. The magic node exists only when editing using keyboard, so can
// not add any unit test.
continue;
}
var ieRange = childRange.getBrowserRange();
// Case 1 : Finding end points when this range is collapsed.
// Note that in case of collapsed range, getEnd{Node,Offset} call
// getStart{Node,Offset}.
if (this.isCollapsed()) {
// Handle situations where caret is not in a text node. In such cases,
// the adjacent child won't be a valid range endpoint container.
if (!goog.dom.browserrange.canContainRangeEndpoint(child)) {
// The following handles a scenario like <div><BR>[caret]<BR></div>,
// where point should be (div, 1).
if (this.compareBrowserRangeEndpoints(ieRange, start, start) == 0) {
this.startOffset_ = this.endOffset_ = i;
return node;
}
} else if (childRange.containsRange(this)) {
// For collapsed range, we should invert the containsRange check with
// childRange.
return this.getEndpointNode_(endpoint, child);
}
// Case 2 - The first child encountered to have overlap this range is
// contained entirely in this range.
} else if (this.containsRange(childRange)) {
// If it is an element which can not be a range endpoint container, the
// current child offset can be used to deduce the endpoint offset.
if (!goog.dom.browserrange.canContainRangeEndpoint(child)) {
// Container can't be any deeper, so current node is the container.
if (isStartEndpoint) {
this.startOffset_ = i;
} else {
this.endOffset_ = i + 1;
}
return node;
}
// If child can contain range endpoints, recurse inside this child.
return this.getEndpointNode_(endpoint, child);
// Case 3 - Partial non-adjacency overlap.
} else if (this.compareBrowserRangeEndpoints(ieRange, start, end) < 0 &&
this.compareBrowserRangeEndpoints(ieRange, end, start) > 0) {
// If this child overlaps the selection partially, recurse down to find
// the first/last child the next level down that overlaps the selection
// completely. We do not consider edge-adjacency (== 0) as overlap.
return this.getEndpointNode_(endpoint, child);
}
}
// None of the children of this node overlapped the selection, that means
// the selection starts/ends in this node directly.
return node;
};
/**
* Compares one endpoint of this range with the endpoint of a node.
* For internal methods, we should prefer this method to containsNode.
* containsNode has a lot of false negatives when we're dealing with
* {@code <br>} tags.
*
* @param {Node} node The node to compare against.
* @param {goog.dom.RangeEndpoint} thisEndpoint The endpoint of this range
* to compare with.
* @param {goog.dom.RangeEndpoint} otherEndpoint The endpoint of the node
* to compare with.
* @return {number} 0 if the endpoints are equal, negative if this range
* endpoint comes before the other node endpoint, and positive otherwise.
* @private
*/
goog.dom.browserrange.IeRange.prototype.compareNodeEndpoints_ =
function(node, thisEndpoint, otherEndpoint) {
return this.range_.compareEndPoints(
(thisEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End') +
'To' +
(otherEndpoint == goog.dom.RangeEndpoint.START ? 'Start' : 'End'),
goog.dom.browserrange.createRangeFromNodeContents(node).
getBrowserRange());
};
/**
* Returns the offset into the start/end container.
* @param {goog.dom.RangeEndpoint} endpoint The endpoint to get the offset for.
* @param {Node=} opt_container The container to get the offset relative to.
* Defaults to the value returned by getStartNode/getEndNode.
* @return {number} The offset.
* @private
*/
goog.dom.browserrange.IeRange.prototype.getOffset_ = function(endpoint,
opt_container) {
var isStartEndpoint = endpoint == goog.dom.RangeEndpoint.START;
var container = opt_container ||
(isStartEndpoint ? this.getStartNode() : this.getEndNode());
if (container.nodeType == goog.dom.NodeType.ELEMENT) {
// Find the first/last child that overlaps the selection
var children = container.childNodes;
var len = children.length;
var edge = isStartEndpoint ? 0 : len - 1;
var sign = isStartEndpoint ? 1 : - 1;
// We find the index in the child array of the endpoint of the selection.
for (var i = edge; i >= 0 && i < len; i += sign) {
var child = children[i];
// Ignore the child nodes, which could be end point containers.
if (goog.dom.browserrange.canContainRangeEndpoint(child)) {
continue;
}
// Stop looping when we reach the edge of the selection.
var endPointCompare =
this.compareNodeEndpoints_(child, endpoint, endpoint);
if (endPointCompare == 0) {
return isStartEndpoint ? i : i + 1;
}
}
// When starting from the end in an empty container, we erroneously return
// -1: fix this to return 0.
return i == -1 ? 0 : i;
} else {
// Get a temporary range object.
var range = this.range_.duplicate();
// Create a range that selects the entire container.
var nodeRange = goog.dom.browserrange.IeRange.getBrowserRangeForNode_(
container);
// Now, intersect our range with the container range - this should give us
// the part of our selection that is in the container.
range.setEndPoint(isStartEndpoint ? 'EndToEnd' : 'StartToStart', nodeRange);
var rangeLength = range.text.length;
return isStartEndpoint ? container.length - rangeLength : rangeLength;
}
};
/**
* Returns the text of the given node. Uses IE specific properties.
* @param {Node} node The node to retrieve the text of.
* @return {string} The node's text.
* @private
*/
goog.dom.browserrange.IeRange.getNodeText_ = function(node) {
return node.nodeType == goog.dom.NodeType.TEXT ?
node.nodeValue : node.innerText;
};
/**
* Tests whether this range is valid (i.e. whether its endpoints are still in
* the document). A range becomes invalid when, after this object was created,
* either one or both of its endpoints are removed from the document. Use of
* an invalid range can lead to runtime errors, particularly in IE.
* @return {boolean} Whether the range is valid.
*/
goog.dom.browserrange.IeRange.prototype.isRangeInDocument = function() {
var range = this.doc_.body.createTextRange();
range.moveToElementText(this.doc_.body);
return this.containsRange(
new goog.dom.browserrange.IeRange(range, this.doc_), true);
};
/** @override */
goog.dom.browserrange.IeRange.prototype.isCollapsed = function() {
// Note(user) : The earlier implementation used (range.text == ''), but this
// fails when (range.htmlText == '<br>')
// Alternative: this.range_.htmlText == '';
return this.range_.compareEndPoints('StartToEnd', this.range_) == 0;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getText = function() {
return this.range_.text;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.getValidHtml = function() {
return this.range_.htmlText;
};
// SELECTION MODIFICATION
/** @override */
goog.dom.browserrange.IeRange.prototype.select = function(opt_reverse) {
// IE doesn't support programmatic reversed selections.
this.range_.select();
};
/** @override */
goog.dom.browserrange.IeRange.prototype.removeContents = function() {
// NOTE: Sometimes htmlText is non-empty, but the range is actually empty.
// TODO(gboyer): The htmlText check is probably unnecessary, but I left it in
// for paranoia.
if (!this.isCollapsed() && this.range_.htmlText) {
// Store some before-removal state.
var startNode = this.getStartNode();
var endNode = this.getEndNode();
var oldText = this.range_.text;
// IE sometimes deletes nodes unrelated to the selection. This trick fixes
// that problem most of the time. Even though it looks like a no-op, it is
// somehow changing IE's internal state such that empty unrelated nodes are
// no longer deleted.
var clone = this.range_.duplicate();
clone.moveStart('character', 1);
clone.moveStart('character', -1);
// However, sometimes moving the start back and forth ends up changing the
// range.
// TODO(gboyer): This condition used to happen for empty ranges, but (1)
// never worked, and (2) the isCollapsed call should protect against empty
// ranges better than before. However, this is left for paranoia.
if (clone.text == oldText) {
this.range_ = clone;
}
// Use the browser's native deletion code.
this.range_.text = '';
this.clearCachedValues_();
// Unfortunately, when deleting a portion of a single text node, IE creates
// an extra text node unlike other browsers which just change the text in
// the node. We normalize for that behavior here, making IE behave like all
// the other browsers.
var newStartNode = this.getStartNode();
var newStartOffset = this.getStartOffset();
/** @preserveTry */
try {
var sibling = startNode.nextSibling;
if (startNode == endNode && startNode.parentNode &&
startNode.nodeType == goog.dom.NodeType.TEXT &&
sibling && sibling.nodeType == goog.dom.NodeType.TEXT) {
startNode.nodeValue += sibling.nodeValue;
goog.dom.removeNode(sibling);
// Make sure to reselect the appropriate position.
this.range_ = goog.dom.browserrange.IeRange.getBrowserRangeForNode_(
newStartNode);
this.range_.move('character', newStartOffset);
this.clearCachedValues_();
}
} catch (e) {
// IE throws errors on orphaned nodes.
}
}
};
/**
* @param {TextRange} range The range to get a dom helper for.
* @return {goog.dom.DomHelper} A dom helper for the document the range
* resides in.
* @private
*/
goog.dom.browserrange.IeRange.getDomHelper_ = function(range) {
return goog.dom.getDomHelper(range.parentElement());
};
/**
* Pastes the given element into the given range, returning the resulting
* element.
* @param {TextRange} range The range to paste into.
* @param {Element} element The node to insert a copy of.
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper object for the document
* the range resides in.
* @return {Element} The resulting copy of element.
* @private
*/
goog.dom.browserrange.IeRange.pasteElement_ = function(range, element,
opt_domHelper) {
opt_domHelper = opt_domHelper || goog.dom.browserrange.IeRange.getDomHelper_(
range);
// Make sure the node has a unique id.
var id;
var originalId = id = element.id;
if (!id) {
id = element.id = goog.string.createUniqueString();
}
// Insert (a clone of) the node.
range.pasteHTML(element.outerHTML);
// Pasting the outerHTML of the modified element into the document creates
// a clone of the element argument. We want to return a reference to the
// clone, not the original. However we need to remove the temporary ID
// first.
element = opt_domHelper.getElement(id);
// If element is null here, we failed.
if (element) {
if (!originalId) {
element.removeAttribute('id');
}
}
return element;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.surroundContents = function(element) {
// Make sure the element is detached from the document.
goog.dom.removeNode(element);
// IE more or less guarantees that range.htmlText is well-formed & valid.
element.innerHTML = this.range_.htmlText;
element = goog.dom.browserrange.IeRange.pasteElement_(this.range_, element);
// If element is null here, we failed.
if (element) {
this.range_.moveToElementText(element);
}
this.clearCachedValues_();
return element;
};
/**
* Internal handler for inserting a node.
* @param {TextRange} clone A clone of this range's browser range object.
* @param {Node} node The node to insert.
* @param {boolean} before Whether to insert the node before or after the range.
* @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use.
* @return {Node} The resulting copy of node.
* @private
*/
goog.dom.browserrange.IeRange.insertNode_ = function(clone, node,
before, opt_domHelper) {
// Get a DOM helper.
opt_domHelper = opt_domHelper || goog.dom.browserrange.IeRange.getDomHelper_(
clone);
// If it's not an element, wrap it in one.
var isNonElement;
if (node.nodeType != goog.dom.NodeType.ELEMENT) {
isNonElement = true;
node = opt_domHelper.createDom(goog.dom.TagName.DIV, null, node);
}
clone.collapse(before);
node = goog.dom.browserrange.IeRange.pasteElement_(clone,
/** @type {Element} */ (node), opt_domHelper);
// If we didn't want an element, unwrap the element and return the node.
if (isNonElement) {
// pasteElement_() may have returned a copy of the wrapper div, and the
// node it wraps could also be a new copy. So we must extract that new
// node from the new wrapper.
var newNonElement = node.firstChild;
opt_domHelper.flattenElement(node);
node = newNonElement;
}
return node;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.insertNode = function(node, before) {
var output = goog.dom.browserrange.IeRange.insertNode_(
this.range_.duplicate(), node, before);
this.clearCachedValues_();
return output;
};
/** @override */
goog.dom.browserrange.IeRange.prototype.surroundWithNodes = function(
startNode, endNode) {
var clone1 = this.range_.duplicate();
var clone2 = this.range_.duplicate();
goog.dom.browserrange.IeRange.insertNode_(clone1, startNode, true);
goog.dom.browserrange.IeRange.insertNode_(clone2, endNode, false);
this.clearCachedValues_();
};
/** @override */
goog.dom.browserrange.IeRange.prototype.collapse = function(toStart) {
this.range_.collapse(toStart);
if (toStart) {
this.endNode_ = this.startNode_;
this.endOffset_ = this.startOffset_;
} else {
this.startNode_ = this.endNode_;
this.startOffset_ = this.endOffset_;
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the browser range namespace and interface, as
* well as several useful utility functions.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*
* @supported IE6, IE7, FF1.5+, Safari.
*/
goog.provide('goog.dom.browserrange');
goog.provide('goog.dom.browserrange.Error');
goog.require('goog.dom');
goog.require('goog.dom.browserrange.GeckoRange');
goog.require('goog.dom.browserrange.IeRange');
goog.require('goog.dom.browserrange.OperaRange');
goog.require('goog.dom.browserrange.W3cRange');
goog.require('goog.dom.browserrange.WebKitRange');
goog.require('goog.userAgent');
/**
* Common error constants.
* @enum {string}
*/
goog.dom.browserrange.Error = {
NOT_IMPLEMENTED: 'Not Implemented'
};
// NOTE(robbyw): While it would be nice to eliminate the duplicate switches
// below, doing so uncovers bugs in the JsCompiler in which
// necessary code is stripped out.
/**
* Static method that returns the proper type of browser range.
* @param {Range|TextRange} range A browser range object.
* @return {goog.dom.browserrange.AbstractRange} A wrapper object.
*/
goog.dom.browserrange.createRange = function(range) {
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
return new goog.dom.browserrange.IeRange(
/** @type {TextRange} */ (range),
goog.dom.getOwnerDocument(range.parentElement()));
} else if (goog.userAgent.WEBKIT) {
return new goog.dom.browserrange.WebKitRange(
/** @type {Range} */ (range));
} else if (goog.userAgent.GECKO) {
return new goog.dom.browserrange.GeckoRange(
/** @type {Range} */ (range));
} else if (goog.userAgent.OPERA) {
return new goog.dom.browserrange.OperaRange(
/** @type {Range} */ (range));
} else {
// Default other browsers, including Opera, to W3c ranges.
return new goog.dom.browserrange.W3cRange(
/** @type {Range} */ (range));
}
};
/**
* Static method that returns the proper type of browser range.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.AbstractRange} A wrapper object.
*/
goog.dom.browserrange.createRangeFromNodeContents = function(node) {
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
return goog.dom.browserrange.IeRange.createFromNodeContents(node);
} else if (goog.userAgent.WEBKIT) {
return goog.dom.browserrange.WebKitRange.createFromNodeContents(node);
} else if (goog.userAgent.GECKO) {
return goog.dom.browserrange.GeckoRange.createFromNodeContents(node);
} else if (goog.userAgent.OPERA) {
return goog.dom.browserrange.OperaRange.createFromNodeContents(node);
} else {
// Default other browsers to W3c ranges.
return goog.dom.browserrange.W3cRange.createFromNodeContents(node);
}
};
/**
* Static method that returns the proper type of browser range.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the node to start. This is
* either the index into the childNodes array for element startNodes or
* the index into the character array for text startNodes.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the node to end. This is
* either the index into the childNodes array for element endNodes or
* the index into the character array for text endNodes.
* @return {goog.dom.browserrange.AbstractRange} A wrapper object.
*/
goog.dom.browserrange.createRangeFromNodes = function(startNode, startOffset,
endNode, endOffset) {
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
return goog.dom.browserrange.IeRange.createFromNodes(startNode, startOffset,
endNode, endOffset);
} else if (goog.userAgent.WEBKIT) {
return goog.dom.browserrange.WebKitRange.createFromNodes(startNode,
startOffset, endNode, endOffset);
} else if (goog.userAgent.GECKO) {
return goog.dom.browserrange.GeckoRange.createFromNodes(startNode,
startOffset, endNode, endOffset);
} else if (goog.userAgent.OPERA) {
return goog.dom.browserrange.OperaRange.createFromNodes(startNode,
startOffset, endNode, endOffset);
} else {
// Default other browsers to W3c ranges.
return goog.dom.browserrange.W3cRange.createFromNodes(startNode,
startOffset, endNode, endOffset);
}
};
/**
* Tests whether the given node can contain a range end point.
* @param {Node} node The node to check.
* @return {boolean} Whether the given node can contain a range end point.
*/
goog.dom.browserrange.canContainRangeEndpoint = function(node) {
// NOTE(user, bloom): This is not complete, as divs with style -
// 'display:inline-block' or 'position:absolute' can also not contain range
// endpoints. A more complete check is to see if that element can be partially
// selected (can be container) or not.
return goog.dom.canHaveChildren(node) ||
node.nodeType == goog.dom.NodeType.TEXT;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Definition of the Gecko specific range wrapper. Inherits most
* functionality from W3CRange, but adds exceptions as necessary.
*
* DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.browserrange.GeckoRange');
goog.require('goog.dom.browserrange.W3cRange');
/**
* The constructor for Gecko specific browser ranges.
* @param {Range} range The range object.
* @constructor
* @extends {goog.dom.browserrange.W3cRange}
*/
goog.dom.browserrange.GeckoRange = function(range) {
goog.dom.browserrange.W3cRange.call(this, range);
};
goog.inherits(goog.dom.browserrange.GeckoRange, goog.dom.browserrange.W3cRange);
/**
* Creates a range object that selects the given node's text.
* @param {Node} node The node to select.
* @return {goog.dom.browserrange.GeckoRange} A Gecko range wrapper object.
*/
goog.dom.browserrange.GeckoRange.createFromNodeContents = function(node) {
return new goog.dom.browserrange.GeckoRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNode(node));
};
/**
* Creates a range object that selects between the given nodes.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the node to start.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the node to end.
* @return {goog.dom.browserrange.GeckoRange} A wrapper object.
*/
goog.dom.browserrange.GeckoRange.createFromNodes = function(startNode,
startOffset, endNode, endOffset) {
return new goog.dom.browserrange.GeckoRange(
goog.dom.browserrange.W3cRange.getBrowserRangeForNodes(startNode,
startOffset, endNode, endOffset));
};
/** @override */
goog.dom.browserrange.GeckoRange.prototype.selectInternal = function(
selection, reversed) {
if (!reversed || this.isCollapsed()) {
// The base implementation for select() is more robust, and works fine for
// collapsed and forward ranges. This works around
// https://bugzilla.mozilla.org/show_bug.cgi?id=773137, and is tested by
// range_test.html's testFocusedElementDisappears.
goog.base(this, 'selectInternal', selection, reversed);
} else {
// Reversed selection -- start with a caret on the end node, and extend it
// back to the start. Unfortunately, collapse() fails when focus is
// invalid.
selection.collapse(this.getEndNode(), this.getEndOffset());
selection.extend(this.getStartNode(), this.getStartOffset());
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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 Utilities for adding, removing and setting classes. Prefer
* {@link goog.dom.classlist} over these utilities since goog.dom.classlist
* conforms closer to the semantics of Element.classList, is faster (uses
* native methods rather than parsing strings on every call) and compiles
* to smaller code as a result.
*
* Note: these utilities are meant to operate on HTMLElements and
* will not work on elements with differing interfaces (such as SVGElements).
*
*/
goog.provide('goog.dom.classes');
goog.require('goog.array');
/**
* Sets the entire class name of an element.
* @param {Node} element DOM node to set class of.
* @param {string} className Class name(s) to apply to element.
*/
goog.dom.classes.set = function(element, className) {
element.className = className;
};
/**
* Gets an array of class names on an element
* @param {Node} element DOM node to get class of.
* @return {!Array} Class names on {@code element}. Some browsers add extra
* properties to the array. Do not depend on any of these!
*/
goog.dom.classes.get = function(element) {
var className = element.className;
// Some types of elements don't have a className in IE (e.g. iframes).
// Furthermore, in Firefox, className is not a string when the element is
// an SVG element.
return goog.isString(className) && className.match(/\S+/g) || [];
};
/**
* Adds a class or classes to an element. Does not add multiples of class names.
* @param {Node} element DOM node to add class to.
* @param {...string} var_args Class names to add.
* @return {boolean} Whether class was added (or all classes were added).
*/
goog.dom.classes.add = function(element, var_args) {
var classes = goog.dom.classes.get(element);
var args = goog.array.slice(arguments, 1);
var expectedCount = classes.length + args.length;
goog.dom.classes.add_(classes, args);
goog.dom.classes.set(element, classes.join(' '));
return classes.length == expectedCount;
};
/**
* Removes a class or classes from an element.
* @param {Node} element DOM node to remove class from.
* @param {...string} var_args Class name(s) to remove.
* @return {boolean} Whether all classes in {@code var_args} were found and
* removed.
*/
goog.dom.classes.remove = function(element, var_args) {
var classes = goog.dom.classes.get(element);
var args = goog.array.slice(arguments, 1);
var newClasses = goog.dom.classes.getDifference_(classes, args);
goog.dom.classes.set(element, newClasses.join(' '));
return newClasses.length == classes.length - args.length;
};
/**
* Helper method for {@link goog.dom.classes.add} and
* {@link goog.dom.classes.addRemove}. Adds one or more classes to the supplied
* classes array.
* @param {Array.<string>} classes All class names for the element, will be
* updated to have the classes supplied in {@code args} added.
* @param {Array.<string>} args Class names to add.
* @private
*/
goog.dom.classes.add_ = function(classes, args) {
for (var i = 0; i < args.length; i++) {
if (!goog.array.contains(classes, args[i])) {
classes.push(args[i]);
}
}
};
/**
* Helper method for {@link goog.dom.classes.remove} and
* {@link goog.dom.classes.addRemove}. Calculates the difference of two arrays.
* @param {!Array.<string>} arr1 First array.
* @param {!Array.<string>} arr2 Second array.
* @return {!Array.<string>} The first array without the elements of the second
* array.
* @private
*/
goog.dom.classes.getDifference_ = function(arr1, arr2) {
return goog.array.filter(arr1, function(item) {
return !goog.array.contains(arr2, item);
});
};
/**
* Switches a class on an element from one to another without disturbing other
* classes. If the fromClass isn't removed, the toClass won't be added.
* @param {Node} element DOM node to swap classes on.
* @param {string} fromClass Class to remove.
* @param {string} toClass Class to add.
* @return {boolean} Whether classes were switched.
*/
goog.dom.classes.swap = function(element, fromClass, toClass) {
var classes = goog.dom.classes.get(element);
var removed = false;
for (var i = 0; i < classes.length; i++) {
if (classes[i] == fromClass) {
goog.array.splice(classes, i--, 1);
removed = true;
}
}
if (removed) {
classes.push(toClass);
goog.dom.classes.set(element, classes.join(' '));
}
return removed;
};
/**
* Adds zero or more classes to an element and removes zero or more as a single
* operation. Unlike calling {@link goog.dom.classes.add} and
* {@link goog.dom.classes.remove} separately, this is more efficient as it only
* parses the class property once.
*
* If a class is in both the remove and add lists, it will be added. Thus,
* you can use this instead of {@link goog.dom.classes.swap} when you have
* more than two class names that you want to swap.
*
* @param {Node} element DOM node to swap classes on.
* @param {?(string|Array.<string>)} classesToRemove Class or classes to
* remove, if null no classes are removed.
* @param {?(string|Array.<string>)} classesToAdd Class or classes to add, if
* null no classes are added.
*/
goog.dom.classes.addRemove = function(element, classesToRemove, classesToAdd) {
var classes = goog.dom.classes.get(element);
if (goog.isString(classesToRemove)) {
goog.array.remove(classes, classesToRemove);
} else if (goog.isArray(classesToRemove)) {
classes = goog.dom.classes.getDifference_(classes, classesToRemove);
}
if (goog.isString(classesToAdd) &&
!goog.array.contains(classes, classesToAdd)) {
classes.push(classesToAdd);
} else if (goog.isArray(classesToAdd)) {
goog.dom.classes.add_(classes, classesToAdd);
}
goog.dom.classes.set(element, classes.join(' '));
};
/**
* Returns true if an element has a class.
* @param {Node} element DOM node to test.
* @param {string} className Class name to test for.
* @return {boolean} Whether element has the class.
*/
goog.dom.classes.has = function(element, className) {
return goog.array.contains(goog.dom.classes.get(element), className);
};
/**
* Adds or removes a class depending on the enabled argument.
* @param {Node} element DOM node to add or remove the class on.
* @param {string} className Class name to add or remove.
* @param {boolean} enabled Whether to add or remove the class (true adds,
* false removes).
*/
goog.dom.classes.enable = function(element, className, enabled) {
if (enabled) {
goog.dom.classes.add(element, className);
} else {
goog.dom.classes.remove(element, className);
}
};
/**
* Removes a class if an element has it, and adds it the element doesn't have
* it. Won't affect other classes on the node.
* @param {Node} element DOM node to toggle class on.
* @param {string} className Class to toggle.
* @return {boolean} True if class was added, false if it was removed
* (in other words, whether element has the class after this function has
* been called).
*/
goog.dom.classes.toggle = function(element, className) {
var add = !goog.dom.classes.has(element, className);
goog.dom.classes.enable(element, className, add);
return add;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 viewport size monitor that buffers RESIZE events until the
* window size has stopped changing, within a specified period of time. For
* every RESIZE event dispatched, this will dispatch up to two *additional*
* events:
* - {@link #EventType.RESIZE_WIDTH} if the viewport's width has changed since
* the last buffered dispatch.
* - {@link #EventType.RESIZE_HEIGHT} if the viewport's height has changed since
* the last buffered dispatch.
* You likely only need to listen to one of the three events. But if you need
* more, just be cautious of duplicating effort.
*
*/
goog.provide('goog.dom.BufferedViewportSizeMonitor');
goog.require('goog.asserts');
goog.require('goog.async.Delay');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
/**
* Creates a new BufferedViewportSizeMonitor.
* @param {!goog.dom.ViewportSizeMonitor} viewportSizeMonitor The
* underlying viewport size monitor.
* @param {number=} opt_bufferMs The buffer time, in ms. If not specified, this
* value defaults to {@link #RESIZE_EVENT_DELAY_MS_}.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.dom.BufferedViewportSizeMonitor = function(
viewportSizeMonitor, opt_bufferMs) {
goog.base(this);
/**
* The underlying viewport size monitor.
* @type {goog.dom.ViewportSizeMonitor}
* @private
*/
this.viewportSizeMonitor_ = viewportSizeMonitor;
/**
* The current size of the viewport.
* @type {goog.math.Size}
* @private
*/
this.currentSize_ = this.viewportSizeMonitor_.getSize();
/**
* The resize buffer time in ms.
* @type {number}
* @private
*/
this.resizeBufferMs_ = opt_bufferMs ||
goog.dom.BufferedViewportSizeMonitor.RESIZE_EVENT_DELAY_MS_;
/**
* Listener key for the viewport size monitor.
* @type {goog.events.Key}
* @private
*/
this.listenerKey_ = goog.events.listen(
viewportSizeMonitor,
goog.events.EventType.RESIZE,
this.handleResize_,
false,
this);
};
goog.inherits(goog.dom.BufferedViewportSizeMonitor, goog.events.EventTarget);
/**
* Additional events to dispatch.
* @enum {string}
*/
goog.dom.BufferedViewportSizeMonitor.EventType = {
RESIZE_HEIGHT: goog.events.getUniqueId('resizeheight'),
RESIZE_WIDTH: goog.events.getUniqueId('resizewidth')
};
/**
* Delay for the resize event.
* @type {goog.async.Delay}
* @private
*/
goog.dom.BufferedViewportSizeMonitor.prototype.resizeDelay_;
/**
* Default number of milliseconds to wait after a resize event to relayout the
* page.
* @type {number}
* @const
* @private
*/
goog.dom.BufferedViewportSizeMonitor.RESIZE_EVENT_DELAY_MS_ = 100;
/** @override */
goog.dom.BufferedViewportSizeMonitor.prototype.disposeInternal =
function() {
goog.events.unlistenByKey(this.listenerKey_);
goog.base(this, 'disposeInternal');
};
/**
* Handles resize events on the underlying ViewportMonitor.
* @private
*/
goog.dom.BufferedViewportSizeMonitor.prototype.handleResize_ =
function() {
// Lazily create when needed.
if (!this.resizeDelay_) {
this.resizeDelay_ = new goog.async.Delay(
this.onWindowResize_,
this.resizeBufferMs_,
this);
this.registerDisposable(this.resizeDelay_);
}
this.resizeDelay_.start();
};
/**
* Window resize callback that determines whether to reflow the view contents.
* @private
*/
goog.dom.BufferedViewportSizeMonitor.prototype.onWindowResize_ =
function() {
if (this.viewportSizeMonitor_.isDisposed()) {
return;
}
var previousSize = this.currentSize_;
var currentSize = this.viewportSizeMonitor_.getSize();
goog.asserts.assert(currentSize,
'Viewport size should be set at this point');
this.currentSize_ = currentSize;
if (previousSize) {
var resized = false;
// Width has changed
if (previousSize.width != currentSize.width) {
this.dispatchEvent(
goog.dom.BufferedViewportSizeMonitor.EventType.RESIZE_WIDTH);
resized = true;
}
// Height has changed
if (previousSize.height != currentSize.height) {
this.dispatchEvent(
goog.dom.BufferedViewportSizeMonitor.EventType.RESIZE_HEIGHT);
resized = true;
}
// If either has changed, this is a resize event.
if (resized) {
this.dispatchEvent(goog.events.EventType.RESIZE);
}
} else {
// If we didn't have a previous size, we consider all events to have
// changed.
this.dispatchEvent(
goog.dom.BufferedViewportSizeMonitor.EventType.RESIZE_HEIGHT);
this.dispatchEvent(
goog.dom.BufferedViewportSizeMonitor.EventType.RESIZE_WIDTH);
this.dispatchEvent(goog.events.EventType.RESIZE);
}
};
/**
* Returns the current size of the viewport.
* @return {goog.math.Size?} The current viewport size.
*/
goog.dom.BufferedViewportSizeMonitor.prototype.getSize = function() {
return this.currentSize_ ? this.currentSize_.clone() : null;
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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
* XML utilities.
*
*/
goog.provide('goog.dom.xml');
goog.require('goog.dom');
goog.require('goog.dom.NodeType');
/**
* Max XML size for MSXML2. Used to prevent potential DoS attacks.
* @type {number}
*/
goog.dom.xml.MAX_XML_SIZE_KB = 2 * 1024; // In kB
/**
* Max XML size for MSXML2. Used to prevent potential DoS attacks.
* @type {number}
*/
goog.dom.xml.MAX_ELEMENT_DEPTH = 256; // Same default as MSXML6.
/**
* Creates an XML document appropriate for the current JS runtime
* @param {string=} opt_rootTagName The root tag name.
* @param {string=} opt_namespaceUri Namespace URI of the document element.
* @return {Document} The new document.
*/
goog.dom.xml.createDocument = function(opt_rootTagName, opt_namespaceUri) {
if (opt_namespaceUri && !opt_rootTagName) {
throw Error("Can't create document with namespace and no root tag");
}
if (document.implementation && document.implementation.createDocument) {
return document.implementation.createDocument(opt_namespaceUri || '',
opt_rootTagName || '',
null);
} else if (typeof ActiveXObject != 'undefined') {
var doc = goog.dom.xml.createMsXmlDocument_();
if (doc) {
if (opt_rootTagName) {
doc.appendChild(doc.createNode(goog.dom.NodeType.ELEMENT,
opt_rootTagName,
opt_namespaceUri || ''));
}
return doc;
}
}
throw Error('Your browser does not support creating new documents');
};
/**
* Creates an XML document from a string
* @param {string} xml The text.
* @return {Document} XML document from the text.
*/
goog.dom.xml.loadXml = function(xml) {
if (typeof DOMParser != 'undefined') {
return new DOMParser().parseFromString(xml, 'application/xml');
} else if (typeof ActiveXObject != 'undefined') {
var doc = goog.dom.xml.createMsXmlDocument_();
doc.loadXML(xml);
return doc;
}
throw Error('Your browser does not support loading xml documents');
};
/**
* Serializes an XML document or subtree to string.
* @param {Document|Element} xml The document or the root node of the subtree.
* @return {string} The serialized XML.
*/
goog.dom.xml.serialize = function(xml) {
// Compatible with Firefox, Opera and WebKit.
if (typeof XMLSerializer != 'undefined') {
return new XMLSerializer().serializeToString(xml);
}
// Compatible with Internet Explorer.
var text = xml.xml;
if (text) {
return text;
}
throw Error('Your browser does not support serializing XML documents');
};
/**
* Selects a single node using an Xpath expression and a root node
* @param {Node} node The root node.
* @param {string} path Xpath selector.
* @return {Node} The selected node, or null if no matching node.
*/
goog.dom.xml.selectSingleNode = function(node, path) {
if (typeof node.selectSingleNode != 'undefined') {
var doc = goog.dom.getOwnerDocument(node);
if (typeof doc.setProperty != 'undefined') {
doc.setProperty('SelectionLanguage', 'XPath');
}
return node.selectSingleNode(path);
} else if (document.implementation.hasFeature('XPath', '3.0')) {
var doc = goog.dom.getOwnerDocument(node);
var resolver = doc.createNSResolver(doc.documentElement);
var result = doc.evaluate(path, node, resolver,
XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
return null;
};
/**
* Selects multiple nodes using an Xpath expression and a root node
* @param {Node} node The root node.
* @param {string} path Xpath selector.
* @return {(NodeList,Array.<Node>)} The selected nodes, or empty array if no
* matching nodes.
*/
goog.dom.xml.selectNodes = function(node, path) {
if (typeof node.selectNodes != 'undefined') {
var doc = goog.dom.getOwnerDocument(node);
if (typeof doc.setProperty != 'undefined') {
doc.setProperty('SelectionLanguage', 'XPath');
}
return node.selectNodes(path);
} else if (document.implementation.hasFeature('XPath', '3.0')) {
var doc = goog.dom.getOwnerDocument(node);
var resolver = doc.createNSResolver(doc.documentElement);
var nodes = doc.evaluate(path, node, resolver,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var results = [];
var count = nodes.snapshotLength;
for (var i = 0; i < count; i++) {
results.push(nodes.snapshotItem(i));
}
return results;
} else {
return [];
}
};
/**
* Sets multiple attributes on an element. Differs from goog.dom.setProperties
* in that it exclusively uses the element's setAttributes method. Use this
* when you need to ensure that the exact property is available as an attribute
* and can be read later by the native getAttribute method.
* @param {!Element} element XML or DOM element to set attributes on.
* @param {!Object.<string, string>} attributes Map of property:value pairs.
*/
goog.dom.xml.setAttributes = function(element, attributes) {
for (var key in attributes) {
if (attributes.hasOwnProperty(key)) {
element.setAttribute(key, attributes[key]);
}
}
};
/**
* Creates an instance of the MSXML2.DOMDocument.
* @return {Document} The new document.
* @private
*/
goog.dom.xml.createMsXmlDocument_ = function() {
var doc = new ActiveXObject('MSXML2.DOMDocument');
if (doc) {
// Prevent potential vulnerabilities exposed by MSXML2, see
// http://b/1707300 and http://wiki/Main/ISETeamXMLAttacks for details.
doc.resolveExternals = false;
doc.validateOnParse = false;
// Add a try catch block because accessing these properties will throw an
// error on unsupported MSXML versions. This affects Windows machines
// running IE6 or IE7 that are on XP SP2 or earlier without MSXML updates.
// See http://msdn.microsoft.com/en-us/library/ms766391(VS.85).aspx for
// specific details on which MSXML versions support these properties.
try {
doc.setProperty('ProhibitDTD', true);
doc.setProperty('MaxXMLSize', goog.dom.xml.MAX_XML_SIZE_KB);
doc.setProperty('MaxElementDepth', goog.dom.xml.MAX_ELEMENT_DEPTH);
} catch (e) {
// No-op.
}
}
return doc;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Iterator between two DOM text range positions.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.TextRangeIterator');
goog.require('goog.array');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.RangeIterator');
goog.require('goog.dom.TagName');
goog.require('goog.iter.StopIteration');
/**
* Subclass of goog.dom.TagIterator that iterates over a DOM range. It
* adds functions to determine the portion of each text node that is selected.
*
* @param {Node} startNode The starting node position.
* @param {number} startOffset The offset in to startNode. If startNode is
* an element, indicates an offset in to childNodes. If startNode is a
* text node, indicates an offset in to nodeValue.
* @param {Node} endNode The ending node position.
* @param {number} endOffset The offset in to endNode. If endNode is
* an element, indicates an offset in to childNodes. If endNode is a
* text node, indicates an offset in to nodeValue.
* @param {boolean=} opt_reverse Whether to traverse nodes in reverse.
* @constructor
* @extends {goog.dom.RangeIterator}
*/
goog.dom.TextRangeIterator = function(startNode, startOffset, endNode,
endOffset, opt_reverse) {
var goNext;
if (startNode) {
this.startNode_ = startNode;
this.startOffset_ = startOffset;
this.endNode_ = endNode;
this.endOffset_ = endOffset;
// Skip to the offset nodes - being careful to special case BRs since these
// have no children but still can appear as the startContainer of a range.
if (startNode.nodeType == goog.dom.NodeType.ELEMENT &&
startNode.tagName != goog.dom.TagName.BR) {
var startChildren = startNode.childNodes;
var candidate = startChildren[startOffset];
if (candidate) {
this.startNode_ = candidate;
this.startOffset_ = 0;
} else {
if (startChildren.length) {
this.startNode_ =
/** @type {Node} */ (goog.array.peek(startChildren));
}
goNext = true;
}
}
if (endNode.nodeType == goog.dom.NodeType.ELEMENT) {
this.endNode_ = endNode.childNodes[endOffset];
if (this.endNode_) {
this.endOffset_ = 0;
} else {
// The offset was past the last element.
this.endNode_ = endNode;
}
}
}
goog.dom.RangeIterator.call(this, opt_reverse ? this.endNode_ :
this.startNode_, opt_reverse);
if (goNext) {
try {
this.next();
} catch (e) {
if (e != goog.iter.StopIteration) {
throw e;
}
}
}
};
goog.inherits(goog.dom.TextRangeIterator, goog.dom.RangeIterator);
/**
* The first node in the selection.
* @type {Node}
* @private
*/
goog.dom.TextRangeIterator.prototype.startNode_ = null;
/**
* The last node in the selection.
* @type {Node}
* @private
*/
goog.dom.TextRangeIterator.prototype.endNode_ = null;
/**
* The offset within the first node in the selection.
* @type {number}
* @private
*/
goog.dom.TextRangeIterator.prototype.startOffset_ = 0;
/**
* The offset within the last node in the selection.
* @type {number}
* @private
*/
goog.dom.TextRangeIterator.prototype.endOffset_ = 0;
/** @override */
goog.dom.TextRangeIterator.prototype.getStartTextOffset = function() {
// Offsets only apply to text nodes. If our current node is the start node,
// return the saved offset. Otherwise, return 0.
return this.node.nodeType != goog.dom.NodeType.TEXT ? -1 :
this.node == this.startNode_ ? this.startOffset_ : 0;
};
/** @override */
goog.dom.TextRangeIterator.prototype.getEndTextOffset = function() {
// Offsets only apply to text nodes. If our current node is the end node,
// return the saved offset. Otherwise, return the length of the node.
return this.node.nodeType != goog.dom.NodeType.TEXT ? -1 :
this.node == this.endNode_ ? this.endOffset_ : this.node.nodeValue.length;
};
/** @override */
goog.dom.TextRangeIterator.prototype.getStartNode = function() {
return this.startNode_;
};
/**
* Change the start node of the iterator.
* @param {Node} node The new start node.
*/
goog.dom.TextRangeIterator.prototype.setStartNode = function(node) {
if (!this.isStarted()) {
this.setPosition(node);
}
this.startNode_ = node;
this.startOffset_ = 0;
};
/** @override */
goog.dom.TextRangeIterator.prototype.getEndNode = function() {
return this.endNode_;
};
/**
* Change the end node of the iterator.
* @param {Node} node The new end node.
*/
goog.dom.TextRangeIterator.prototype.setEndNode = function(node) {
this.endNode_ = node;
this.endOffset_ = 0;
};
/** @override */
goog.dom.TextRangeIterator.prototype.isLast = function() {
return this.isStarted() && this.node == this.endNode_ &&
(!this.endOffset_ || !this.isStartTag());
};
/**
* Move to the next position in the selection.
* Throws {@code goog.iter.StopIteration} when it passes the end of the range.
* @return {Node} The node at the next position.
* @override
*/
goog.dom.TextRangeIterator.prototype.next = function() {
if (this.isLast()) {
throw goog.iter.StopIteration;
}
// Call the super function.
return goog.dom.TextRangeIterator.superClass_.next.call(this);
};
/** @override */
goog.dom.TextRangeIterator.prototype.skipTag = function() {
goog.dom.TextRangeIterator.superClass_.skipTag.apply(this);
// If the node we are skipping contains the end node, we just skipped past
// the end, so we stop the iteration.
if (goog.dom.contains(this.node, this.endNode_)) {
throw goog.iter.StopIteration;
}
};
/** @override */
goog.dom.TextRangeIterator.prototype.copyFrom = function(other) {
this.startNode_ = other.startNode_;
this.endNode_ = other.endNode_;
this.startOffset_ = other.startOffset_;
this.endOffset_ = other.endOffset_;
this.isReversed_ = other.isReversed_;
goog.dom.TextRangeIterator.superClass_.copyFrom.call(this, other);
};
/**
* @return {goog.dom.TextRangeIterator} An identical iterator.
* @override
*/
goog.dom.TextRangeIterator.prototype.clone = function() {
var copy = new goog.dom.TextRangeIterator(this.startNode_,
this.startOffset_, this.endNode_, this.endOffset_, this.isReversed_);
copy.copyFrom(this);
return copy;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Utilities for working with text ranges in HTML documents.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.TextRange');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.RangeType');
goog.require('goog.dom.SavedRange');
goog.require('goog.dom.TagName');
goog.require('goog.dom.TextRangeIterator');
goog.require('goog.dom.browserrange');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Create a new text selection with no properties. Do not use this constructor:
* use one of the goog.dom.Range.createFrom* methods instead.
* @constructor
* @extends {goog.dom.AbstractRange}
*/
goog.dom.TextRange = function() {
};
goog.inherits(goog.dom.TextRange, goog.dom.AbstractRange);
/**
* Create a new range wrapper from the given browser range object. Do not use
* this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Range|TextRange} range The browser range object.
* @param {boolean=} opt_isReversed Whether the focus node is before the anchor
* node.
* @return {goog.dom.TextRange} A range wrapper object.
*/
goog.dom.TextRange.createFromBrowserRange = function(range, opt_isReversed) {
return goog.dom.TextRange.createFromBrowserRangeWrapper_(
goog.dom.browserrange.createRange(range), opt_isReversed);
};
/**
* Create a new range wrapper from the given browser range wrapper.
* @param {goog.dom.browserrange.AbstractRange} browserRange The browser range
* wrapper.
* @param {boolean=} opt_isReversed Whether the focus node is before the anchor
* node.
* @return {goog.dom.TextRange} A range wrapper object.
* @private
*/
goog.dom.TextRange.createFromBrowserRangeWrapper_ = function(browserRange,
opt_isReversed) {
var range = new goog.dom.TextRange();
// Initialize the range as a browser range wrapper type range.
range.browserRangeWrapper_ = browserRange;
range.isReversed_ = !!opt_isReversed;
return range;
};
/**
* Create a new range wrapper that selects the given node's text. Do not use
* this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Node} node The node to select.
* @param {boolean=} opt_isReversed Whether the focus node is before the anchor
* node.
* @return {goog.dom.TextRange} A range wrapper object.
*/
goog.dom.TextRange.createFromNodeContents = function(node, opt_isReversed) {
return goog.dom.TextRange.createFromBrowserRangeWrapper_(
goog.dom.browserrange.createRangeFromNodeContents(node),
opt_isReversed);
};
/**
* Create a new range wrapper that selects the area between the given nodes,
* accounting for the given offsets. Do not use this method directly - please
* use goog.dom.Range.createFrom* instead.
* @param {Node} anchorNode The node to start with.
* @param {number} anchorOffset The offset within the node to start.
* @param {Node} focusNode The node to end with.
* @param {number} focusOffset The offset within the node to end.
* @return {goog.dom.TextRange} A range wrapper object.
*/
goog.dom.TextRange.createFromNodes = function(anchorNode, anchorOffset,
focusNode, focusOffset) {
var range = new goog.dom.TextRange();
range.isReversed_ = goog.dom.Range.isReversed(anchorNode, anchorOffset,
focusNode, focusOffset);
// Avoid selecting terminal elements directly
if (goog.dom.isElement(anchorNode) && !goog.dom.canHaveChildren(anchorNode)) {
var parent = anchorNode.parentNode;
anchorOffset = goog.array.indexOf(parent.childNodes, anchorNode);
anchorNode = parent;
}
if (goog.dom.isElement(focusNode) && !goog.dom.canHaveChildren(focusNode)) {
var parent = focusNode.parentNode;
focusOffset = goog.array.indexOf(parent.childNodes, focusNode);
focusNode = parent;
}
// Initialize the range as a W3C style range.
if (range.isReversed_) {
range.startNode_ = focusNode;
range.startOffset_ = focusOffset;
range.endNode_ = anchorNode;
range.endOffset_ = anchorOffset;
} else {
range.startNode_ = anchorNode;
range.startOffset_ = anchorOffset;
range.endNode_ = focusNode;
range.endOffset_ = focusOffset;
}
return range;
};
// Representation 1: a browser range wrapper.
/**
* The browser specific range wrapper. This can be null if one of the other
* representations of the range is specified.
* @type {goog.dom.browserrange.AbstractRange?}
* @private
*/
goog.dom.TextRange.prototype.browserRangeWrapper_ = null;
// Representation 2: two endpoints specified as nodes + offsets
/**
* The start node of the range. This can be null if one of the other
* representations of the range is specified.
* @type {Node}
* @private
*/
goog.dom.TextRange.prototype.startNode_ = null;
/**
* The start offset of the range. This can be null if one of the other
* representations of the range is specified.
* @type {?number}
* @private
*/
goog.dom.TextRange.prototype.startOffset_ = null;
/**
* The end node of the range. This can be null if one of the other
* representations of the range is specified.
* @type {Node}
* @private
*/
goog.dom.TextRange.prototype.endNode_ = null;
/**
* The end offset of the range. This can be null if one of the other
* representations of the range is specified.
* @type {?number}
* @private
*/
goog.dom.TextRange.prototype.endOffset_ = null;
/**
* Whether the focus node is before the anchor node.
* @type {boolean}
* @private
*/
goog.dom.TextRange.prototype.isReversed_ = false;
// Method implementations
/**
* @return {goog.dom.TextRange} A clone of this range.
* @override
*/
goog.dom.TextRange.prototype.clone = function() {
var range = new goog.dom.TextRange();
range.browserRangeWrapper_ = this.browserRangeWrapper_;
range.startNode_ = this.startNode_;
range.startOffset_ = this.startOffset_;
range.endNode_ = this.endNode_;
range.endOffset_ = this.endOffset_;
range.isReversed_ = this.isReversed_;
return range;
};
/** @override */
goog.dom.TextRange.prototype.getType = function() {
return goog.dom.RangeType.TEXT;
};
/** @override */
goog.dom.TextRange.prototype.getBrowserRangeObject = function() {
return this.getBrowserRangeWrapper_().getBrowserRange();
};
/** @override */
goog.dom.TextRange.prototype.setBrowserRangeObject = function(nativeRange) {
// Test if it's a control range by seeing if a control range only method
// exists.
if (goog.dom.AbstractRange.isNativeControlRange(nativeRange)) {
return false;
}
this.browserRangeWrapper_ = goog.dom.browserrange.createRange(
nativeRange);
this.clearCachedValues_();
return true;
};
/**
* Clear all cached values.
* @private
*/
goog.dom.TextRange.prototype.clearCachedValues_ = function() {
this.startNode_ = this.startOffset_ = this.endNode_ = this.endOffset_ = null;
};
/** @override */
goog.dom.TextRange.prototype.getTextRangeCount = function() {
return 1;
};
/** @override */
goog.dom.TextRange.prototype.getTextRange = function(i) {
return this;
};
/**
* @return {goog.dom.browserrange.AbstractRange} The range wrapper object.
* @private
*/
goog.dom.TextRange.prototype.getBrowserRangeWrapper_ = function() {
return this.browserRangeWrapper_ ||
(this.browserRangeWrapper_ = goog.dom.browserrange.createRangeFromNodes(
this.getStartNode(), this.getStartOffset(),
this.getEndNode(), this.getEndOffset()));
};
/** @override */
goog.dom.TextRange.prototype.getContainer = function() {
return this.getBrowserRangeWrapper_().getContainer();
};
/** @override */
goog.dom.TextRange.prototype.getStartNode = function() {
return this.startNode_ ||
(this.startNode_ = this.getBrowserRangeWrapper_().getStartNode());
};
/** @override */
goog.dom.TextRange.prototype.getStartOffset = function() {
return this.startOffset_ != null ? this.startOffset_ :
(this.startOffset_ = this.getBrowserRangeWrapper_().getStartOffset());
};
/** @override */
goog.dom.TextRange.prototype.getStartPosition = function() {
return this.isReversed() ?
this.getBrowserRangeWrapper_().getEndPosition() :
this.getBrowserRangeWrapper_().getStartPosition();
};
/** @override */
goog.dom.TextRange.prototype.getEndNode = function() {
return this.endNode_ ||
(this.endNode_ = this.getBrowserRangeWrapper_().getEndNode());
};
/** @override */
goog.dom.TextRange.prototype.getEndOffset = function() {
return this.endOffset_ != null ? this.endOffset_ :
(this.endOffset_ = this.getBrowserRangeWrapper_().getEndOffset());
};
/** @override */
goog.dom.TextRange.prototype.getEndPosition = function() {
return this.isReversed() ?
this.getBrowserRangeWrapper_().getStartPosition() :
this.getBrowserRangeWrapper_().getEndPosition();
};
/**
* Moves a TextRange to the provided nodes and offsets.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the node to start.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the node to end.
* @param {boolean} isReversed Whether the range is reversed.
*/
goog.dom.TextRange.prototype.moveToNodes = function(startNode, startOffset,
endNode, endOffset,
isReversed) {
this.startNode_ = startNode;
this.startOffset_ = startOffset;
this.endNode_ = endNode;
this.endOffset_ = endOffset;
this.isReversed_ = isReversed;
this.browserRangeWrapper_ = null;
};
/** @override */
goog.dom.TextRange.prototype.isReversed = function() {
return this.isReversed_;
};
/** @override */
goog.dom.TextRange.prototype.containsRange = function(otherRange,
opt_allowPartial) {
var otherRangeType = otherRange.getType();
if (otherRangeType == goog.dom.RangeType.TEXT) {
return this.getBrowserRangeWrapper_().containsRange(
otherRange.getBrowserRangeWrapper_(), opt_allowPartial);
} else if (otherRangeType == goog.dom.RangeType.CONTROL) {
var elements = otherRange.getElements();
var fn = opt_allowPartial ? goog.array.some : goog.array.every;
return fn(elements, function(el) {
return this.containsNode(el, opt_allowPartial);
}, this);
}
return false;
};
/**
* Tests if the given node is in a document.
* @param {Node} node The node to check.
* @return {boolean} Whether the given node is in the given document.
*/
goog.dom.TextRange.isAttachedNode = function(node) {
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
var returnValue = false;
/** @preserveTry */
try {
returnValue = node.parentNode;
} catch (e) {
// IE sometimes throws Invalid Argument errors when a node is detached.
// Note: trying to return a value from the above try block can cause IE
// to crash. It is necessary to use the local returnValue
}
return !!returnValue;
} else {
return goog.dom.contains(node.ownerDocument.body, node);
}
};
/** @override */
goog.dom.TextRange.prototype.isRangeInDocument = function() {
// Ensure any cached nodes are in the document. IE also allows ranges to
// become detached, so we check if the range is still in the document as
// well for IE.
return (!this.startNode_ ||
goog.dom.TextRange.isAttachedNode(this.startNode_)) &&
(!this.endNode_ ||
goog.dom.TextRange.isAttachedNode(this.endNode_)) &&
(!(goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) ||
this.getBrowserRangeWrapper_().isRangeInDocument());
};
/** @override */
goog.dom.TextRange.prototype.isCollapsed = function() {
return this.getBrowserRangeWrapper_().isCollapsed();
};
/** @override */
goog.dom.TextRange.prototype.getText = function() {
return this.getBrowserRangeWrapper_().getText();
};
/** @override */
goog.dom.TextRange.prototype.getHtmlFragment = function() {
// TODO(robbyw): Generalize the code in browserrange so it is static and
// just takes an iterator. This would mean we don't always have to create a
// browser range.
return this.getBrowserRangeWrapper_().getHtmlFragment();
};
/** @override */
goog.dom.TextRange.prototype.getValidHtml = function() {
return this.getBrowserRangeWrapper_().getValidHtml();
};
/** @override */
goog.dom.TextRange.prototype.getPastableHtml = function() {
// TODO(robbyw): Get any attributes the table or tr has.
var html = this.getValidHtml();
if (html.match(/^\s*<td\b/i)) {
// Match html starting with a TD.
html = '<table><tbody><tr>' + html + '</tr></tbody></table>';
} else if (html.match(/^\s*<tr\b/i)) {
// Match html starting with a TR.
html = '<table><tbody>' + html + '</tbody></table>';
} else if (html.match(/^\s*<tbody\b/i)) {
// Match html starting with a TBODY.
html = '<table>' + html + '</table>';
} else if (html.match(/^\s*<li\b/i)) {
// Match html starting with an LI.
var container = this.getContainer();
var tagType = goog.dom.TagName.UL;
while (container) {
if (container.tagName == goog.dom.TagName.OL) {
tagType = goog.dom.TagName.OL;
break;
} else if (container.tagName == goog.dom.TagName.UL) {
break;
}
container = container.parentNode;
}
html = goog.string.buildString('<', tagType, '>', html, '</', tagType, '>');
}
return html;
};
/**
* Returns a TextRangeIterator over the contents of the range. Regardless of
* the direction of the range, the iterator will move in document order.
* @param {boolean=} opt_keys Unused for this iterator.
* @return {goog.dom.TextRangeIterator} An iterator over tags in the range.
* @override
*/
goog.dom.TextRange.prototype.__iterator__ = function(opt_keys) {
return new goog.dom.TextRangeIterator(this.getStartNode(),
this.getStartOffset(), this.getEndNode(), this.getEndOffset());
};
// RANGE ACTIONS
/** @override */
goog.dom.TextRange.prototype.select = function() {
this.getBrowserRangeWrapper_().select(this.isReversed_);
};
/** @override */
goog.dom.TextRange.prototype.removeContents = function() {
this.getBrowserRangeWrapper_().removeContents();
this.clearCachedValues_();
};
/**
* Surrounds the text range with the specified element (on Mozilla) or with a
* clone of the specified element (on IE). Returns a reference to the
* surrounding element if the operation was successful; returns null if the
* operation failed.
* @param {Element} element The element with which the selection is to be
* surrounded.
* @return {Element} The surrounding element (same as the argument on Mozilla,
* but not on IE), or null if unsuccessful.
*/
goog.dom.TextRange.prototype.surroundContents = function(element) {
var output = this.getBrowserRangeWrapper_().surroundContents(element);
this.clearCachedValues_();
return output;
};
/** @override */
goog.dom.TextRange.prototype.insertNode = function(node, before) {
var output = this.getBrowserRangeWrapper_().insertNode(node, before);
this.clearCachedValues_();
return output;
};
/** @override */
goog.dom.TextRange.prototype.surroundWithNodes = function(startNode, endNode) {
this.getBrowserRangeWrapper_().surroundWithNodes(startNode, endNode);
this.clearCachedValues_();
};
// SAVE/RESTORE
/** @override */
goog.dom.TextRange.prototype.saveUsingDom = function() {
return new goog.dom.DomSavedTextRange_(this);
};
// RANGE MODIFICATION
/** @override */
goog.dom.TextRange.prototype.collapse = function(toAnchor) {
var toStart = this.isReversed() ? !toAnchor : toAnchor;
if (this.browserRangeWrapper_) {
this.browserRangeWrapper_.collapse(toStart);
}
if (toStart) {
this.endNode_ = this.startNode_;
this.endOffset_ = this.startOffset_;
} else {
this.startNode_ = this.endNode_;
this.startOffset_ = this.endOffset_;
}
// Collapsed ranges can't be reversed
this.isReversed_ = false;
};
// SAVED RANGE OBJECTS
/**
* A SavedRange implementation using DOM endpoints.
* @param {goog.dom.AbstractRange} range The range to save.
* @constructor
* @extends {goog.dom.SavedRange}
* @private
*/
goog.dom.DomSavedTextRange_ = function(range) {
/**
* The anchor node.
* @type {Node}
* @private
*/
this.anchorNode_ = range.getAnchorNode();
/**
* The anchor node offset.
* @type {number}
* @private
*/
this.anchorOffset_ = range.getAnchorOffset();
/**
* The focus node.
* @type {Node}
* @private
*/
this.focusNode_ = range.getFocusNode();
/**
* The focus node offset.
* @type {number}
* @private
*/
this.focusOffset_ = range.getFocusOffset();
};
goog.inherits(goog.dom.DomSavedTextRange_, goog.dom.SavedRange);
/**
* @return {goog.dom.AbstractRange} The restored range.
* @override
*/
goog.dom.DomSavedTextRange_.prototype.restoreInternal = function() {
return goog.dom.Range.createFromNodes(this.anchorNode_, this.anchorOffset_,
this.focusNode_, this.focusOffset_);
};
/** @override */
goog.dom.DomSavedTextRange_.prototype.disposeInternal = function() {
goog.dom.DomSavedTextRange_.superClass_.disposeInternal.call(this);
this.anchorNode_ = null;
this.focusNode_ = null;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 the goog.dom.TagName enum. This enumerates
* all HTML tag names specified in either the the W3C HTML 4.01 index of
* elements or the HTML5 draft specification.
*
* References:
* http://www.w3.org/TR/html401/index/elements.html
* http://dev.w3.org/html5/spec/section-index.html
*
*/
goog.provide('goog.dom.TagName');
/**
* Enum of all html tag names specified by the W3C HTML4.01 and HTML5
* specifications.
* @enum {string}
*/
goog.dom.TagName = {
A: 'A',
ABBR: 'ABBR',
ACRONYM: 'ACRONYM',
ADDRESS: 'ADDRESS',
APPLET: 'APPLET',
AREA: 'AREA',
ARTICLE: 'ARTICLE',
ASIDE: 'ASIDE',
AUDIO: 'AUDIO',
B: 'B',
BASE: 'BASE',
BASEFONT: 'BASEFONT',
BDI: 'BDI',
BDO: 'BDO',
BIG: 'BIG',
BLOCKQUOTE: 'BLOCKQUOTE',
BODY: 'BODY',
BR: 'BR',
BUTTON: 'BUTTON',
CANVAS: 'CANVAS',
CAPTION: 'CAPTION',
CENTER: 'CENTER',
CITE: 'CITE',
CODE: 'CODE',
COL: 'COL',
COLGROUP: 'COLGROUP',
COMMAND: 'COMMAND',
DATA: 'DATA',
DATALIST: 'DATALIST',
DD: 'DD',
DEL: 'DEL',
DETAILS: 'DETAILS',
DFN: 'DFN',
DIALOG: 'DIALOG',
DIR: 'DIR',
DIV: 'DIV',
DL: 'DL',
DT: 'DT',
EM: 'EM',
EMBED: 'EMBED',
FIELDSET: 'FIELDSET',
FIGCAPTION: 'FIGCAPTION',
FIGURE: 'FIGURE',
FONT: 'FONT',
FOOTER: 'FOOTER',
FORM: 'FORM',
FRAME: 'FRAME',
FRAMESET: 'FRAMESET',
H1: 'H1',
H2: 'H2',
H3: 'H3',
H4: 'H4',
H5: 'H5',
H6: 'H6',
HEAD: 'HEAD',
HEADER: 'HEADER',
HGROUP: 'HGROUP',
HR: 'HR',
HTML: 'HTML',
I: 'I',
IFRAME: 'IFRAME',
IMG: 'IMG',
INPUT: 'INPUT',
INS: 'INS',
ISINDEX: 'ISINDEX',
KBD: 'KBD',
KEYGEN: 'KEYGEN',
LABEL: 'LABEL',
LEGEND: 'LEGEND',
LI: 'LI',
LINK: 'LINK',
MAP: 'MAP',
MARK: 'MARK',
MATH: 'MATH',
MENU: 'MENU',
META: 'META',
METER: 'METER',
NAV: 'NAV',
NOFRAMES: 'NOFRAMES',
NOSCRIPT: 'NOSCRIPT',
OBJECT: 'OBJECT',
OL: 'OL',
OPTGROUP: 'OPTGROUP',
OPTION: 'OPTION',
OUTPUT: 'OUTPUT',
P: 'P',
PARAM: 'PARAM',
PRE: 'PRE',
PROGRESS: 'PROGRESS',
Q: 'Q',
RP: 'RP',
RT: 'RT',
RUBY: 'RUBY',
S: 'S',
SAMP: 'SAMP',
SCRIPT: 'SCRIPT',
SECTION: 'SECTION',
SELECT: 'SELECT',
SMALL: 'SMALL',
SOURCE: 'SOURCE',
SPAN: 'SPAN',
STRIKE: 'STRIKE',
STRONG: 'STRONG',
STYLE: 'STYLE',
SUB: 'SUB',
SUMMARY: 'SUMMARY',
SUP: 'SUP',
SVG: 'SVG',
TABLE: 'TABLE',
TBODY: 'TBODY',
TD: 'TD',
TEXTAREA: 'TEXTAREA',
TFOOT: 'TFOOT',
TH: 'TH',
THEAD: 'THEAD',
TIME: 'TIME',
TITLE: 'TITLE',
TR: 'TR',
TRACK: 'TRACK',
TT: 'TT',
U: 'U',
UL: 'UL',
VAR: 'VAR',
VIDEO: 'VIDEO',
WBR: 'WBR'
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 Shared code for dom_test.html and dom_quirks_test.html.
*/
/** @suppress {extraProvide} */
goog.provide('goog.dom.dom_test');
goog.require('goog.dom');
goog.require('goog.dom.BrowserFeature');
goog.require('goog.dom.DomHelper');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagName');
goog.require('goog.object');
goog.require('goog.string.Unicode');
goog.require('goog.testing.asserts');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
goog.require('goog.userAgent.product.isVersion');
goog.setTestOnly('dom_test');
var $ = goog.dom.getElement;
var divForTestingScrolling;
var myIframe;
var myIframeDoc;
function setUpPage() {
divForTestingScrolling = document.createElement('div');
divForTestingScrolling.style.width = '5000px';
divForTestingScrolling.style.height = '5000px';
document.body.appendChild(divForTestingScrolling);
// Setup for the iframe
myIframe = $('myIframe');
myIframeDoc = goog.dom.getFrameContentDocument(
/** @type {HTMLIFrameElement} */ (myIframe));
// Set up document for iframe: total height of elements in document is 65
// If the elements are not create like below, IE will get a wrong height for
// the document.
myIframeDoc.open();
// Make sure we progate the compat mode
myIframeDoc.write((goog.dom.isCss1CompatMode() ? '<!DOCTYPE html>' : '') +
'<style>body{margin:0;padding:0}</style>' +
'<div style="height:42px;font-size:1px;line-height:0;">' +
'hello world</div>' +
'<div style="height:23px;font-size:1px;line-height:0;">' +
'hello world</div>');
myIframeDoc.close();
}
function tearDownPage() {
document.body.removeChild(divForTestingScrolling);
}
function tearDown() {
window.scrollTo(0, 0);
}
function testDom() {
assert('Dom library exists', typeof goog.dom != 'undefined');
}
function testGetElement() {
var el = $('testEl');
assertEquals('Should be able to get id', el.id, 'testEl');
assertEquals($, goog.dom.getElement);
assertEquals(goog.dom.$, goog.dom.getElement);
}
function testGetElementsByTagNameAndClass() {
assertEquals('Should get 6 spans',
goog.dom.getElementsByTagNameAndClass('span').length, 6);
assertEquals('Should get 6 spans',
goog.dom.getElementsByTagNameAndClass('SPAN').length, 6);
assertEquals('Should get 3 spans',
goog.dom.getElementsByTagNameAndClass('span', 'test1').length, 3);
assertEquals('Should get 1 span',
goog.dom.getElementsByTagNameAndClass('span', 'test2').length, 1);
assertEquals('Should get 1 span',
goog.dom.getElementsByTagNameAndClass('SPAN', 'test2').length, 1);
assertEquals('Should get lots of elements',
goog.dom.getElementsByTagNameAndClass().length,
document.getElementsByTagName('*').length);
assertEquals('Should get 1 span',
goog.dom.getElementsByTagNameAndClass('span', null, $('testEl')).length,
1);
// '*' as the tag name should be equivalent to all tags
var container = goog.dom.getElement('span-container');
assertEquals(5,
goog.dom.getElementsByTagNameAndClass('*', undefined, container).length);
assertEquals(3,
goog.dom.getElementsByTagNameAndClass('*', 'test1', container).length);
assertEquals(1,
goog.dom.getElementsByTagNameAndClass('*', 'test2', container).length);
// Some version of WebKit have problems with mixed-case class names
assertEquals(1,
goog.dom.getElementsByTagNameAndClass(
undefined, 'mixedCaseClass').length);
// Make sure that out of bounds indices are OK
assertUndefined(
goog.dom.getElementsByTagNameAndClass(undefined, 'noSuchClass')[0]);
assertEquals(goog.dom.getElementsByTagNameAndClass,
goog.dom.getElementsByTagNameAndClass);
}
function testGetElementsByClass() {
assertEquals(3, goog.dom.getElementsByClass('test1').length);
assertEquals(1, goog.dom.getElementsByClass('test2').length);
assertEquals(0, goog.dom.getElementsByClass('nonexistant').length);
var container = goog.dom.getElement('span-container');
assertEquals(3, goog.dom.getElementsByClass('test1', container).length);
}
function testGetElementByClass() {
assertNotNull(goog.dom.getElementByClass('test1'));
assertNotNull(goog.dom.getElementByClass('test2'));
// assertNull(goog.dom.getElementByClass('nonexistant'));
var container = goog.dom.getElement('span-container');
assertNotNull(goog.dom.getElementByClass('test1', container));
}
function testSetProperties() {
var attrs = {'name': 'test3', 'title': 'A title', 'random': 'woop'};
var el = $('testEl');
var res = goog.dom.setProperties(el, attrs);
assertEquals('Should be equal', el.name, 'test3');
assertEquals('Should be equal', el.title, 'A title');
assertEquals('Should be equal', el.random, 'woop');
}
function testSetPropertiesDirectAttributeMap() {
var attrs = {'usemap': '#myMap'};
var el = goog.dom.createDom('img');
var res = goog.dom.setProperties(el, attrs);
assertEquals('Should be equal', '#myMap', el.getAttribute('usemap'));
}
function testSetPropertiesAria() {
var attrs = {
'aria-hidden': 'true',
'aria-label': 'This is a label',
'role': 'presentation'
};
var el = goog.dom.createDom('div');
goog.dom.setProperties(el, attrs);
assertEquals('Should be equal', 'true', el.getAttribute('aria-hidden'));
assertEquals('Should be equal',
'This is a label', el.getAttribute('aria-label'));
assertEquals('Should be equal', 'presentation', el.getAttribute('role'));
}
function testSetPropertiesData() {
var attrs = {
'data-tooltip': 'This is a tooltip',
'data-tooltip-delay': '100'
};
var el = goog.dom.createDom('div');
goog.dom.setProperties(el, attrs);
assertEquals('Should be equal', 'This is a tooltip',
el.getAttribute('data-tooltip'));
assertEquals('Should be equal', '100',
el.getAttribute('data-tooltip-delay'));
}
function testSetTableProperties() {
var attrs = {
'style': 'padding-left: 10px;',
'class': 'mytestclass',
'height': '101',
'cellpadding': '15'
};
var el = $('testTable1');
var res = goog.dom.setProperties(el, attrs);
assertEquals('Should be equal', el.style.paddingLeft, '10px');
assertEquals('Should be equal', el.className, 'mytestclass');
assertEquals('Should be equal', el.getAttribute('height'), '101');
assertEquals('Should be equal', el.cellPadding, '15');
}
function testGetViewportSize() {
// TODO: This is failing in the test runner now, fix later.
//var dims = getViewportSize();
//assertNotUndefined('Should be defined at least', dims.width);
//assertNotUndefined('Should be defined at least', dims.height);
}
function testGetViewportSizeInIframe() {
var iframe = /** @type {HTMLIFrameElement} */ (goog.dom.getElement('iframe'));
var contentDoc = goog.dom.getFrameContentDocument(iframe);
contentDoc.write('<body></body>');
var outerSize = goog.dom.getViewportSize();
var innerSize = (new goog.dom.DomHelper(contentDoc)).getViewportSize();
assert('Viewport sizes must not match',
innerSize.width != outerSize.width);
}
function testGetDocumentHeightInIframe() {
var doc = goog.dom.getDomHelper(myIframeDoc).getDocument();
var height = goog.dom.getDomHelper(myIframeDoc).getDocumentHeight();
// Broken in webkit quirks mode and in IE8+
if ((goog.dom.isCss1CompatMode_(doc) || !goog.userAgent.WEBKIT) &&
!isIE8OrHigher()) {
assertEquals('height should be 65', 42 + 23, height);
}
}
function testCreateDom() {
var el = goog.dom.$dom('div',
{
style: 'border: 1px solid black; width: 50%; background-color: #EEE;',
onclick: "alert('woo')"
},
goog.dom.$dom('p', {style: 'font: normal 12px arial; color: red; '},
'Para 1'),
goog.dom.$dom('p', {style: 'font: bold 18px garamond; color: blue; '},
'Para 2'),
goog.dom.$dom('p', {style: 'font: normal 24px monospace; color: green'},
'Para 3 ',
goog.dom.$dom('a', {
name: 'link', href: 'http://bbc.co.uk'
},
'has a link'),
', how cool is this?'));
assertEquals('Tagname should be a DIV', 'DIV', el.tagName);
assertEquals('Style width should be 50%', '50%', el.style.width);
assertEquals('first child is a P tag', 'P', el.childNodes[0].tagName);
assertEquals('second child .innerHTML', 'Para 2',
el.childNodes[1].innerHTML);
assertEquals(goog.dom.$dom, goog.dom.createDom);
}
function testCreateDomNoChildren() {
var el;
// Test unspecified children.
el = goog.dom.$dom('div');
assertNull('firstChild should be null', el.firstChild);
// Test null children.
el = goog.dom.$dom('div', null, null);
assertNull('firstChild should be null', el.firstChild);
// Test empty array of children.
el = goog.dom.$dom('div', null, []);
assertNull('firstChild should be null', el.firstChild);
}
function testCreateDomAcceptsArray() {
var items = [
goog.dom.$dom('li', {}, 'Item 1'),
goog.dom.$dom('li', {}, 'Item 2')
];
var ul = goog.dom.$dom('ul', {}, items);
assertEquals('List should have two children', 2, ul.childNodes.length);
assertEquals('First child should be an LI tag',
'LI', ul.firstChild.tagName);
assertEquals('Item 1', ul.childNodes[0].innerHTML);
assertEquals('Item 2', ul.childNodes[1].innerHTML);
}
function testCreateDomStringArg() {
var el;
// Test string arg.
el = goog.dom.$dom('div', null, 'Hello');
assertEquals('firstChild should be a text node', goog.dom.NodeType.TEXT,
el.firstChild.nodeType);
assertEquals('firstChild should have node value "Hello"', 'Hello',
el.firstChild.nodeValue);
// Test text node arg.
el = goog.dom.$dom('div', null, goog.dom.createTextNode('World'));
assertEquals('firstChild should be a text node', goog.dom.NodeType.TEXT,
el.firstChild.nodeType);
assertEquals('firstChild should have node value "World"', 'World',
el.firstChild.nodeValue);
}
function testCreateDomNodeListArg() {
var el;
var emptyElem = goog.dom.$dom('div');
var simpleElem = goog.dom.$dom('div', null, 'Hello, world!');
var complexElem = goog.dom.$dom('div', null, 'Hello, ',
goog.dom.$dom('b', null, 'world'),
goog.dom.createTextNode('!'));
// Test empty node list.
el = goog.dom.$dom('div', null, emptyElem.childNodes);
assertNull('emptyElem.firstChild should be null', emptyElem.firstChild);
assertNull('firstChild should be null', el.firstChild);
// Test simple node list.
el = goog.dom.$dom('div', null, simpleElem.childNodes);
assertNull('simpleElem.firstChild should be null', simpleElem.firstChild);
assertEquals('firstChild should be a text node with value "Hello, world!"',
'Hello, world!', el.firstChild.nodeValue);
// Test complex node list.
el = goog.dom.$dom('div', null, complexElem.childNodes);
assertNull('complexElem.firstChild should be null', complexElem.firstChild);
assertEquals('Element should have 3 child nodes', 3, el.childNodes.length);
assertEquals('childNodes[0] should be a text node with value "Hello, "',
'Hello, ', el.childNodes[0].nodeValue);
assertEquals('childNodes[1] should be an element node with tagName "B"',
'B', el.childNodes[1].tagName);
assertEquals('childNodes[2] should be a text node with value "!"', '!',
el.childNodes[2].nodeValue);
}
function testCreateDomWithTypeAttribute() {
var el = goog.dom.createDom('button', {'type': 'reset', 'id': 'cool-button'},
'Cool button');
assertNotNull('Button with type attribute was created successfully', el);
assertEquals('Button has correct type attribute', 'reset', el.type);
assertEquals('Button has correct id', 'cool-button', el.id);
}
function testCreateDomWithClassList() {
var el = goog.dom.createDom('div', ['foo', 'bar']);
assertEquals('foo bar', el.className);
el = goog.dom.createDom('div', ['foo', 'foo']);
assertEquals('foo', el.className);
}
function testContains() {
assertTrue('HTML should contain BODY', goog.dom.contains(
document.documentElement, document.body));
assertTrue('Document should contain BODY', goog.dom.contains(
document, document.body));
var d = goog.dom.$dom('p', null, 'A paragraph');
var t = d.firstChild;
assertTrue('Same element', goog.dom.contains(d, d));
assertTrue('Same text', goog.dom.contains(t, t));
assertTrue('Nested text', goog.dom.contains(d, t));
assertFalse('Nested text, reversed', goog.dom.contains(t, d));
assertFalse('Disconnected element', goog.dom.contains(
document, d));
goog.dom.appendChild(document.body, d);
assertTrue('Connected element', goog.dom.contains(
document, d));
goog.dom.removeNode(d);
}
function testCreateDomWithClassName() {
var el = goog.dom.$dom('div', 'cls');
assertNull('firstChild should be null', el.firstChild);
assertEquals('Tagname should be a DIV', 'DIV', el.tagName);
assertEquals('ClassName should be cls', 'cls', el.className);
el = goog.dom.$dom('div', '');
assertEquals('ClassName should be empty', '', el.className);
}
function testCompareNodeOrder() {
var b1 = $('b1');
var b2 = $('b2');
var p2 = $('p2');
assertEquals('equal nodes should compare to 0', 0,
goog.dom.compareNodeOrder(b1, b1));
assertTrue('parent should come before child',
goog.dom.compareNodeOrder(p2, b1) < 0);
assertTrue('child should come after parent',
goog.dom.compareNodeOrder(b1, p2) > 0);
assertTrue('parent should come before text child',
goog.dom.compareNodeOrder(b1, b1.firstChild) < 0);
assertTrue('text child should come after parent', goog.dom.compareNodeOrder(
b1.firstChild, b1) > 0);
assertTrue('first sibling should come before second',
goog.dom.compareNodeOrder(b1, b2) < 0);
assertTrue('second sibling should come after first',
goog.dom.compareNodeOrder(b2, b1) > 0);
assertTrue('text node after cousin element returns correct value',
goog.dom.compareNodeOrder(b1.nextSibling, b1) > 0);
assertTrue('text node before cousin element returns correct value',
goog.dom.compareNodeOrder(b1, b1.nextSibling) < 0);
assertTrue('text node is before once removed cousin element',
goog.dom.compareNodeOrder(b1.firstChild, b2) < 0);
assertTrue('once removed cousin element is before text node',
goog.dom.compareNodeOrder(b2, b1.firstChild) > 0);
assertTrue('text node is after once removed cousin text node',
goog.dom.compareNodeOrder(b1.nextSibling, b1.firstChild) > 0);
assertTrue('once removed cousin text node is before text node',
goog.dom.compareNodeOrder(b1.firstChild, b1.nextSibling) < 0);
assertTrue('first text node is before second text node',
goog.dom.compareNodeOrder(b1.previousSibling, b1.nextSibling) < 0);
assertTrue('second text node is after first text node',
goog.dom.compareNodeOrder(b1.nextSibling, b1.previousSibling) > 0);
assertTrue('grandchild is after grandparent',
goog.dom.compareNodeOrder(b1.firstChild, b1.parentNode) > 0);
assertTrue('grandparent is after grandchild',
goog.dom.compareNodeOrder(b1.parentNode, b1.firstChild) < 0);
assertTrue('grandchild is after grandparent',
goog.dom.compareNodeOrder(b1.firstChild, b1.parentNode) > 0);
assertTrue('grandparent is after grandchild',
goog.dom.compareNodeOrder(b1.parentNode, b1.firstChild) < 0);
assertTrue('second cousins compare correctly',
goog.dom.compareNodeOrder(b1.firstChild, b2.firstChild) < 0);
assertTrue('second cousins compare correctly in reverse',
goog.dom.compareNodeOrder(b2.firstChild, b1.firstChild) > 0);
assertTrue('testEl2 is after testEl',
goog.dom.compareNodeOrder($('testEl2'), $('testEl')) > 0);
assertTrue('testEl is before testEl2',
goog.dom.compareNodeOrder($('testEl'), $('testEl2')) < 0);
var p = $('order-test');
var text1 = document.createTextNode('1');
p.appendChild(text1);
var text2 = document.createTextNode('1');
p.appendChild(text2);
assertEquals('Equal text nodes should compare to 0', 0,
goog.dom.compareNodeOrder(text1, text1));
assertTrue('First text node is before second',
goog.dom.compareNodeOrder(text1, text2) < 0);
assertTrue('Second text node is after first',
goog.dom.compareNodeOrder(text2, text1) > 0);
assertTrue('Late text node is after b1',
goog.dom.compareNodeOrder(text1, $('b1')) > 0);
assertTrue('Document node is before non-document node',
goog.dom.compareNodeOrder(document, b1) < 0);
assertTrue('Non-document node is after document node',
goog.dom.compareNodeOrder(b1, document) > 0);
}
function testFindCommonAncestor() {
var b1 = $('b1');
var b2 = $('b2');
var p1 = $('p1');
var p2 = $('p2');
var testEl2 = $('testEl2');
assertNull('findCommonAncestor() = null', goog.dom.findCommonAncestor());
assertEquals('findCommonAncestor(b1) = b1', b1,
goog.dom.findCommonAncestor(b1));
assertEquals('findCommonAncestor(b1, b1) = b1', b1,
goog.dom.findCommonAncestor(b1, b1));
assertEquals('findCommonAncestor(b1, b2) = p2', p2,
goog.dom.findCommonAncestor(b1, b2));
assertEquals('findCommonAncestor(p1, b2) = body', document.body,
goog.dom.findCommonAncestor(p1, b2));
assertEquals('findCommonAncestor(testEl2, b1, b2, p1, p2) = body',
document.body, goog.dom.findCommonAncestor(testEl2, b1, b2, p1, p2));
var outOfDoc = document.createElement('div');
assertNull('findCommonAncestor(outOfDoc, b1) = null',
goog.dom.findCommonAncestor(outOfDoc, b1));
}
function testRemoveNode() {
var b = document.createElement('b');
var el = $('p1');
el.appendChild(b);
goog.dom.removeNode(b);
assertTrue('b should have been removed', el.lastChild != b);
}
function testReplaceNode() {
var n = $('toReplace');
var previousSibling = n.previousSibling;
var goodNode = goog.dom.createDom('div', {'id': 'goodReplaceNode'});
goog.dom.replaceNode(goodNode, n);
assertEquals('n should have been replaced', previousSibling.nextSibling,
goodNode);
assertNull('n should no longer be in the DOM tree', $('toReplace'));
var badNode = goog.dom.createDom('div', {'id': 'badReplaceNode'});
goog.dom.replaceNode(badNode, n);
assertNull('badNode should not be in the DOM tree', $('badReplaceNode'));
}
function testAppendChildAt() {
var parent = $('p2');
var origNumChildren = parent.childNodes.length;
var child1 = document.createElement('div');
goog.dom.insertChildAt(parent, child1, origNumChildren);
assertEquals(origNumChildren + 1, parent.childNodes.length);
var child2 = document.createElement('div');
goog.dom.insertChildAt(parent, child2, origNumChildren + 42);
assertEquals(origNumChildren + 2, parent.childNodes.length);
var child3 = document.createElement('div');
goog.dom.insertChildAt(parent, child3, 0);
assertEquals(origNumChildren + 3, parent.childNodes.length);
var child4 = document.createElement('div');
goog.dom.insertChildAt(parent, child3, 2);
assertEquals(origNumChildren + 3, parent.childNodes.length);
parent.removeChild(child1);
parent.removeChild(child2);
parent.removeChild(child3);
var emptyParentNotInDocument = document.createElement('div');
goog.dom.insertChildAt(emptyParentNotInDocument, child1, 0);
assertEquals(1, emptyParentNotInDocument.childNodes.length);
}
function testFlattenElement() {
var text = document.createTextNode('Text');
var br = document.createElement('br');
var span = goog.dom.createDom('span', null, text, br);
assertEquals('span should have 2 children', 2, span.childNodes.length);
var el = $('p1');
el.appendChild(span);
var ret = goog.dom.flattenElement(span);
assertTrue('span should have been removed', el.lastChild != span);
assertFalse('span should have no parent', !!span.parentNode &&
span.parentNode.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT);
assertEquals('span should have no children', 0, span.childNodes.length);
assertEquals('Last child of p should be br', br, el.lastChild);
assertEquals('Previous sibling of br should be text', text,
br.previousSibling);
var outOfDoc = goog.dom.createDom('span', null, '1 child');
// Should do nothing.
goog.dom.flattenElement(outOfDoc);
assertEquals('outOfDoc should still have 1 child', 1,
outOfDoc.childNodes.length);
}
function testIsNodeLike() {
assertTrue('document should be node like', goog.dom.isNodeLike(document));
assertTrue('document.body should be node like',
goog.dom.isNodeLike(document.body));
assertTrue('a text node should be node like', goog.dom.isNodeLike(
document.createTextNode('')));
assertFalse('null should not be node like', goog.dom.isNodeLike(null));
assertFalse('a string should not be node like', goog.dom.isNodeLike('abcd'));
assertTrue('custom object should be node like',
goog.dom.isNodeLike({nodeType: 1}));
}
function testIsElement() {
assertFalse('document is not an element', goog.dom.isElement(document));
assertTrue('document.body is an element',
goog.dom.isElement(document.body));
assertFalse('a text node is not an element', goog.dom.isElement(
document.createTextNode('')));
assertTrue('an element created with createElement() is an element',
goog.dom.isElement(document.createElement('a')));
assertFalse('null is not an element', goog.dom.isElement(null));
assertFalse('a string is not an element', goog.dom.isElement('abcd'));
assertTrue('custom object is an element',
goog.dom.isElement({nodeType: 1}));
assertFalse('custom non-element object is a not an element',
goog.dom.isElement({someProperty: 'somevalue'}));
}
function testIsWindow() {
var global = goog.global;
var frame = window.frames['frame'];
var otherWindow = window.open('', 'blank');
var object = {window: goog.global};
var nullVar = null;
var notDefined;
try {
// Use try/finally to ensure that we clean up the window we open, even if an
// assertion fails or something else goes wrong.
assertTrue('global object in HTML context should be a window',
goog.dom.isWindow(goog.global));
assertTrue('iframe window should be a window', goog.dom.isWindow(frame));
if (otherWindow) {
assertTrue('other window should be a window',
goog.dom.isWindow(otherWindow));
}
assertFalse('object should not be a window', goog.dom.isWindow(object));
assertFalse('null should not be a window', goog.dom.isWindow(nullVar));
assertFalse('undefined should not be a window',
goog.dom.isWindow(notDefined));
} finally {
if (otherWindow) {
otherWindow.close();
}
}
}
function testGetOwnerDocument() {
assertEquals(goog.dom.getOwnerDocument($('p1')), document);
assertEquals(goog.dom.getOwnerDocument(document.body), document);
assertEquals(goog.dom.getOwnerDocument(document.documentElement), document);
}
function testDomHelper() {
var x = new goog.dom.DomHelper(window.frames['frame'].document);
assertTrue('Should have some HTML',
x.getDocument().body.innerHTML.length > 0);
}
function testGetFirstElementChild() {
var p2 = $('p2');
var b1 = goog.dom.getFirstElementChild(p2);
assertNotNull('First element child of p2 should not be null', b1);
assertEquals('First element child is b1', 'b1', b1.id);
var c = goog.dom.getFirstElementChild(b1);
assertNull('First element child of b1 should be null', c);
// Test with an undefined firstElementChild attribute.
var b2 = $('b2');
var mockP2 = {
childNodes: [b1, b2],
firstChild: b1,
firstElementChild: undefined
};
b1 = goog.dom.getFirstElementChild(mockP2);
assertNotNull('First element child of mockP2 should not be null', b1);
assertEquals('First element child is b1', 'b1', b1.id);
}
function testGetLastElementChild() {
var p2 = $('p2');
var b2 = goog.dom.getLastElementChild(p2);
assertNotNull('Last element child of p2 should not be null', b2);
assertEquals('Last element child is b2', 'b2', b2.id);
var c = goog.dom.getLastElementChild(b2);
assertNull('Last element child of b2 should be null', c);
// Test with an undefined lastElementChild attribute.
var b1 = $('b1');
var mockP2 = {
childNodes: [b1, b2],
lastChild: b2,
lastElementChild: undefined
};
b2 = goog.dom.getLastElementChild(mockP2);
assertNotNull('Last element child of mockP2 should not be null', b2);
assertEquals('Last element child is b2', 'b2', b2.id);
}
function testGetNextElementSibling() {
var b1 = $('b1');
var b2 = goog.dom.getNextElementSibling(b1);
assertNotNull('Next element sibling of b1 should not be null', b1);
assertEquals('Next element sibling is b2', 'b2', b2.id);
var c = goog.dom.getNextElementSibling(b2);
assertNull('Next element sibling of b2 should be null', c);
// Test with an undefined nextElementSibling attribute.
var mockB1 = {
nextSibling: b2,
nextElementSibling: undefined
};
b2 = goog.dom.getNextElementSibling(mockB1);
assertNotNull('Next element sibling of mockB1 should not be null', b1);
assertEquals('Next element sibling is b2', 'b2', b2.id);
}
function testGetPreviousElementSibling() {
var b2 = $('b2');
var b1 = goog.dom.getPreviousElementSibling(b2);
assertNotNull('Previous element sibling of b2 should not be null', b1);
assertEquals('Previous element sibling is b1', 'b1', b1.id);
var c = goog.dom.getPreviousElementSibling(b1);
assertNull('Previous element sibling of b1 should be null', c);
// Test with an undefined previousElementSibling attribute.
var mockB2 = {
previousSibling: b1,
previousElementSibling: undefined
};
b1 = goog.dom.getPreviousElementSibling(mockB2);
assertNotNull('Previous element sibling of mockB2 should not be null', b1);
assertEquals('Previous element sibling is b1', 'b1', b1.id);
}
function testGetChildren() {
var p2 = $('p2');
var children = goog.dom.getChildren(p2);
assertNotNull('Elements array should not be null', children);
assertEquals('List of element children should be length two.', 2,
children.length);
var b1 = $('b1');
var b2 = $('b2');
assertObjectEquals('First element child should be b1.', b1, children[0]);
assertObjectEquals('Second element child should be b2.', b2, children[1]);
var noChildren = goog.dom.getChildren(b1);
assertNotNull('Element children array should not be null', noChildren);
assertEquals('List of element children should be length zero.', 0,
noChildren.length);
// Test with an undefined children attribute.
var mockP2 = {
childNodes: [b1, b2],
children: undefined
};
children = goog.dom.getChildren(mockP2);
assertNotNull('Elements array should not be null', children);
assertEquals('List of element children should be length two.', 2,
children.length);
assertObjectEquals('First element child should be b1.', b1, children[0]);
assertObjectEquals('Second element child should be b2.', b2, children[1]);
}
function testGetNextNode() {
var tree = goog.dom.htmlToDocumentFragment(
'<div>' +
'<p>Some text</p>' +
'<blockquote>Some <i>special</i> <b>text</b></blockquote>' +
'<address><!-- comment -->Foo</address>' +
'</div>');
assertNull(goog.dom.getNextNode(null));
var node = tree;
var next = function() {
return node = goog.dom.getNextNode(node);
};
assertEquals('P', next().tagName);
assertEquals('Some text', next().nodeValue);
assertEquals('BLOCKQUOTE', next().tagName);
assertEquals('Some ', next().nodeValue);
assertEquals('I', next().tagName);
assertEquals('special', next().nodeValue);
assertEquals(' ', next().nodeValue);
assertEquals('B', next().tagName);
assertEquals('text', next().nodeValue);
assertEquals('ADDRESS', next().tagName);
assertEquals(goog.dom.NodeType.COMMENT, next().nodeType);
assertEquals('Foo', next().nodeValue);
assertNull(next());
}
function testGetPreviousNode() {
var tree = goog.dom.htmlToDocumentFragment(
'<div>' +
'<p>Some text</p>' +
'<blockquote>Some <i>special</i> <b>text</b></blockquote>' +
'<address><!-- comment -->Foo</address>' +
'</div>');
assertNull(goog.dom.getPreviousNode(null));
var node = tree.lastChild.lastChild;
var previous = function() {
return node = goog.dom.getPreviousNode(node);
};
assertEquals(goog.dom.NodeType.COMMENT, previous().nodeType);
assertEquals('ADDRESS', previous().tagName);
assertEquals('text', previous().nodeValue);
assertEquals('B', previous().tagName);
assertEquals(' ', previous().nodeValue);
assertEquals('special', previous().nodeValue);
assertEquals('I', previous().tagName);
assertEquals('Some ', previous().nodeValue);
assertEquals('BLOCKQUOTE', previous().tagName);
assertEquals('Some text', previous().nodeValue);
assertEquals('P', previous().tagName);
assertEquals('DIV', previous().tagName);
if (!goog.userAgent.IE) {
// Internet Explorer maintains a parentNode for Elements after they are
// removed from the hierarchy. Everyone else agrees on a null parentNode.
assertNull(previous());
}
}
function testSetTextContent() {
var p1 = $('p1');
var s = 'hello world';
goog.dom.setTextContent(p1, s);
assertEquals('We should have one childNode after setTextContent', 1,
p1.childNodes.length);
assertEquals(s, p1.firstChild.data);
assertEquals(s, p1.innerHTML);
s = 'four elefants < five ants';
var sHtml = 'four elefants < five ants';
goog.dom.setTextContent(p1, s);
assertEquals('We should have one childNode after setTextContent', 1,
p1.childNodes.length);
assertEquals(s, p1.firstChild.data);
assertEquals(sHtml, p1.innerHTML);
// ensure that we remove existing children
p1.innerHTML = 'a<b>b</b>c';
s = 'hello world';
goog.dom.setTextContent(p1, s);
assertEquals('We should have one childNode after setTextContent', 1,
p1.childNodes.length);
assertEquals(s, p1.firstChild.data);
// same but start with an element
p1.innerHTML = '<b>a</b>b<i>c</i>';
s = 'hello world';
goog.dom.setTextContent(p1, s);
assertEquals('We should have one childNode after setTextContent', 1,
p1.childNodes.length);
assertEquals(s, p1.firstChild.data);
// clean up
p1.innerHTML = '';
}
function testFindNode() {
var expected = document.body;
var result = goog.dom.findNode(document, function(n) {
return n.nodeType == goog.dom.NodeType.ELEMENT && n.tagName == 'BODY';
});
assertEquals(expected, result);
expected = document.getElementsByTagName('P')[0];
result = goog.dom.findNode(document, function(n) {
return n.nodeType == goog.dom.NodeType.ELEMENT && n.tagName == 'P';
});
assertEquals(expected, result);
result = goog.dom.findNode(document, function(n) {
return false;
});
assertUndefined(result);
}
function testFindNodes() {
var expected = document.getElementsByTagName('P');
var result = goog.dom.findNodes(document, function(n) {
return n.nodeType == goog.dom.NodeType.ELEMENT && n.tagName == 'P';
});
assertEquals(expected.length, result.length);
assertEquals(expected[0], result[0]);
assertEquals(expected[1], result[1]);
result = goog.dom.findNodes(document, function(n) {
return false;
}).length;
assertEquals(0, result);
}
function createTestDom(txt) {
var dom = goog.dom.createDom('div');
dom.innerHTML = txt;
return dom;
}
function testIsFocusableTabIndex() {
assertFalse('isFocusableTabIndex() must be false for no tab index',
goog.dom.isFocusableTabIndex(goog.dom.getElement('noTabIndex')));
assertFalse('isFocusableTabIndex() must be false for tab index -2',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndexNegative2')));
assertFalse('isFocusableTabIndex() must be false for tab index -1',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndexNegative1')));
// WebKit on Mac doesn't support focusable DIVs until version 526 and later.
if (!goog.userAgent.WEBKIT || !goog.userAgent.MAC ||
goog.userAgent.isVersion('526')) {
assertTrue('isFocusableTabIndex() must be true for tab index 0',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndex0')));
assertTrue('isFocusableTabIndex() must be true for tab index 1',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndex1')));
assertTrue('isFocusableTabIndex() must be true for tab index 2',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndex2')));
}
}
function testSetFocusableTabIndex() {
// WebKit on Mac doesn't support focusable DIVs until version 526 and later.
if (!goog.userAgent.WEBKIT || !goog.userAgent.MAC ||
goog.userAgent.isVersion('526')) {
// Test enabling focusable tab index.
goog.dom.setFocusableTabIndex(goog.dom.getElement('noTabIndex'), true);
assertTrue('isFocusableTabIndex() must be true after enabling tab index',
goog.dom.isFocusableTabIndex(goog.dom.getElement('noTabIndex')));
// Test disabling focusable tab index that was added programmatically.
goog.dom.setFocusableTabIndex(goog.dom.getElement('noTabIndex'), false);
assertFalse('isFocusableTabIndex() must be false after disabling tab ' +
'index that was programmatically added',
goog.dom.isFocusableTabIndex(goog.dom.getElement('noTabIndex')));
// Test disabling focusable tab index that was specified in markup.
goog.dom.setFocusableTabIndex(goog.dom.getElement('tabIndex0'), false);
assertFalse('isFocusableTabIndex() must be false after disabling tab ' +
'index that was specified in markup',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndex0')));
// Test re-enabling focusable tab index.
goog.dom.setFocusableTabIndex(goog.dom.getElement('tabIndex0'), true);
assertTrue('isFocusableTabIndex() must be true after reenabling tabindex',
goog.dom.isFocusableTabIndex(goog.dom.getElement('tabIndex0')));
}
}
function testGetTextContent() {
function t(inp, out) {
assertEquals(out.replace(/ /g, '_'),
goog.dom.getTextContent(
createTestDom(inp)).replace(/ /g, '_'));
}
t('abcde', 'abcde');
t('a<b>bcd</b>efgh', 'abcdefgh');
t('a<script type="text/javascript' + '">var a=1;<' + '/script>h', 'ah');
t('<html><head><style type="text/css">' +
'p{margin:100%;padding:5px}\n.class{background-color:red;}</style>' +
'</head><body><h1>Hello</h1>\n<p>One two three</p>\n<table><tr><td>a' +
'<td>b</table><' + 'script>var a = \'foo\';' +
'</scrip' + 't></body></html>', 'HelloOne two threeab');
t('abc<br>def', 'abc\ndef');
t('abc<br>\ndef', 'abc\ndef');
t('abc<br>\n\ndef', 'abc\ndef');
t('abc<br><br>\ndef', 'abc\n\ndef');
t(' <b>abcde </b> ', 'abcde ');
t(' <b>abcde </b> hi ', 'abcde hi ');
t(' \n<b>abcde </b> ', 'abcde ');
t(' \n<b>abcde </b> \n\n\n', 'abcde ');
t('<p>abcde</p>\nfg', 'abcdefg');
t('\n <div> <b>abcde </b> ', 'abcde ');
t(' \n­<b>abcde ­ </b> \n\n\n­', 'abcde ');
t(' \n­\n\n­\na ', 'a ');
t(' \n<wbr></wbr><b>abcde <wbr></wbr> </b> \n\n\n<wbr></wbr>', 'abcde ');
t('a b',
goog.dom.BrowserFeature.CAN_USE_INNER_TEXT ?
'a b' : 'a\xA0\xA0\xA0\xA0\xA0b');
}
function testGetNodeTextLength() {
assertEquals(6, goog.dom.getNodeTextLength(createTestDom('abcdef')));
assertEquals(8, goog.dom.getNodeTextLength(
createTestDom('a<b>bcd</b>efgh')));
assertEquals(2, goog.dom.getNodeTextLength(createTestDom(
'a<script type="text/javascript' + '">var a = 1234;<' + '/script>h')));
assertEquals(4, goog.dom.getNodeTextLength(createTestDom(
'a<br>\n<!-- some comments -->\nfo')));
assertEquals(20, goog.dom.getNodeTextLength(createTestDom(
'<html><head><style type="text/css">' +
'p{margin:100%;padding:5px}\n.class{background-color:red;}</style>' +
'</head><body><h1>Hello</h1><p>One two three</p><table><tr><td>a<td>b' +
'</table><' + 'script>var a = \'foo\';</scrip' +
't></body></html>')));
assertEquals(10, goog.dom.getNodeTextLength(createTestDom(
'a<b>bcd</b><br />efghi')));
}
function testGetNodeTextOffset() {
assertEquals(4, goog.dom.getNodeTextOffset($('offsetTest1'),
$('offsetParent1')));
assertEquals(12, goog.dom.getNodeTextOffset($('offsetTest1')));
}
function testGetNodeAtOffset() {
var html = '<div id=a>123<b id=b>45</b><span id=c>67<b id=d>89<i id=e>01' +
'</i>23<i id=f>45</i>67</b>890<i id=g>123</i><b id=h>456</b>' +
'</span></div><div id=i>7890<i id=j>123</i></div>';
var node = document.createElement('div');
node.innerHTML = html;
var rv = {};
goog.dom.getNodeAtOffset(node, 2, rv);
assertEquals('123', rv.node.nodeValue);
assertEquals('a', rv.node.parentNode.id);
assertEquals(1, rv.remainder);
goog.dom.getNodeAtOffset(node, 3, rv);
assertEquals('123', rv.node.nodeValue);
assertEquals('a', rv.node.parentNode.id);
assertEquals(2, rv.remainder);
goog.dom.getNodeAtOffset(node, 5, rv);
assertEquals('45', rv.node.nodeValue);
assertEquals('b', rv.node.parentNode.id);
assertEquals(1, rv.remainder);
goog.dom.getNodeAtOffset(node, 6, rv);
assertEquals('67', rv.node.nodeValue);
assertEquals('c', rv.node.parentNode.id);
assertEquals(0, rv.remainder);
goog.dom.getNodeAtOffset(node, 23, rv);
assertEquals('123', rv.node.nodeValue);
assertEquals('g', rv.node.parentNode.id);
assertEquals(2, rv.remainder);
goog.dom.getNodeAtOffset(node, 30, rv);
assertEquals('7890', rv.node.nodeValue);
assertEquals('i', rv.node.parentNode.id);
assertEquals(3, rv.remainder);
}
// IE inserts line breaks and capitalizes nodenames.
function assertEqualsCaseAndLeadingWhitespaceInsensitive(value1, value2) {
value1 = value1.replace(/^\s+|\s+$/g, '').toLowerCase();
value2 = value2.replace(/^\s+|\s+$/g, '').toLowerCase();
assertEquals(value1, value2);
}
function testGetOuterHtml() {
var contents = '<b>foo</b>';
var node = document.createElement('div');
node.setAttribute('foo', 'bar');
node.innerHTML = contents;
assertEqualsCaseAndLeadingWhitespaceInsensitive(
goog.dom.getOuterHtml(node), '<div foo="bar">' + contents + '</div>');
var imgNode = document.createElement('img');
imgNode.setAttribute('foo', 'bar');
assertEqualsCaseAndLeadingWhitespaceInsensitive(
goog.dom.getOuterHtml(imgNode), '<img foo="bar">');
}
function testGetWindowFrame() {
var frameWindow = window.frames['frame'];
var frameDocument = frameWindow.document;
var frameDomHelper = new goog.dom.DomHelper(frameDocument);
// Cannot use assertEquals since IE fails on ===
assertTrue(frameWindow == frameDomHelper.getWindow());
}
function testGetWindow() {
var domHelper = new goog.dom.DomHelper();
// Cannot use assertEquals since IE fails on ===
assertTrue(window == domHelper.getWindow());
}
function testGetWindowStatic() {
// Cannot use assertEquals since IE fails on ===
assertTrue(window == goog.dom.getWindow());
}
function testIsNodeList() {
var elem = document.getElementById('p2');
var text = document.getElementById('b2').firstChild;
assertTrue('NodeList should be a node list',
goog.dom.isNodeList(elem.childNodes));
assertFalse('TextNode should not be a node list',
goog.dom.isNodeList(text));
assertFalse('Array of nodes should not be a node list',
goog.dom.isNodeList([elem.firstChild, elem.lastChild]));
}
function testGetFrameContentDocument() {
var iframe = document.getElementsByTagName('iframe')[0];
var name = iframe.name;
var iframeDoc = goog.dom.getFrameContentDocument(iframe);
assertEquals(window.frames[name].document, iframeDoc);
}
function testGetFrameContentWindow() {
var iframe = document.getElementsByTagName('iframe')[0];
var name = iframe.name;
var iframeWin = goog.dom.getFrameContentWindow(iframe);
assertEquals(window.frames[name], iframeWin);
}
function testCanHaveChildren() {
var EMPTY_ELEMENTS = goog.object.createSet(
goog.dom.TagName.APPLET,
goog.dom.TagName.AREA,
goog.dom.TagName.BASE,
goog.dom.TagName.BR,
goog.dom.TagName.COL,
goog.dom.TagName.COMMAND,
goog.dom.TagName.EMBED,
goog.dom.TagName.FRAME,
goog.dom.TagName.HR,
goog.dom.TagName.IMG,
goog.dom.TagName.INPUT,
goog.dom.TagName.IFRAME,
goog.dom.TagName.ISINDEX,
goog.dom.TagName.KEYGEN,
goog.dom.TagName.LINK,
goog.dom.TagName.NOFRAMES,
goog.dom.TagName.NOSCRIPT,
goog.dom.TagName.META,
goog.dom.TagName.OBJECT,
goog.dom.TagName.PARAM,
goog.dom.TagName.SCRIPT,
goog.dom.TagName.SOURCE,
goog.dom.TagName.STYLE,
goog.dom.TagName.TRACK,
goog.dom.TagName.WBR);
// IE opens a dialog warning about using Java content if an EMBED is created.
var IE_ILLEGAL_ELEMENTS = goog.object.createSet(goog.dom.TagName.EMBED);
for (var tag in goog.dom.TagName) {
if (goog.userAgent.IE && tag in IE_ILLEGAL_ELEMENTS) {
continue;
}
var expected = !(tag in EMPTY_ELEMENTS);
var node = goog.dom.createElement(tag);
assertEquals(tag + ' should ' + (expected ? '' : 'not ') +
'have children', expected, goog.dom.canHaveChildren(node));
// Make sure we can _actually_ add a child if we identify the node as
// allowing children.
if (goog.dom.canHaveChildren(node)) {
node.appendChild(goog.dom.createDom('div', null, 'foo'));
}
}
}
function testGetAncestorNoMatch() {
var elem = goog.dom.getElement('nestedElement');
assertNull(goog.dom.getAncestor(elem, function() {return false;}));
}
function testGetAncestorMatchSelf() {
var elem = goog.dom.getElement('nestedElement');
var matched = goog.dom.getAncestor(elem, function() {return true;}, true);
assertEquals(elem, matched);
}
function testGetAncestorNoMatchSelf() {
var elem = goog.dom.getElement('nestedElement');
var matched = goog.dom.getAncestor(elem, function() {return true;});
assertEquals(elem.parentNode, matched);
}
function testGetAncestorWithMaxSearchStepsMatchSelf() {
var elem = goog.dom.getElement('nestedElement');
var matched = goog.dom.getAncestor(
elem, function() {return true;}, true, 2);
assertEquals(elem, matched);
}
function testGetAncestorWithMaxSearchStepsMatch() {
var elem = goog.dom.getElement('nestedElement');
var searchEl = elem.parentNode.parentNode;
var matched = goog.dom.getAncestor(
elem, function(el) {return el == searchEl;}, false, 1);
assertEquals(searchEl, matched);
}
function testGetAncestorWithMaxSearchStepsNoMatch() {
var elem = goog.dom.getElement('nestedElement');
var searchEl = elem.parentNode.parentNode;
var matched = goog.dom.getAncestor(
elem, function(el) {return el == searchEl;}, false, 0);
assertNull(matched);
}
function testGetAncestorByTagNameNoMatch() {
var elem = goog.dom.getElement('nestedElement');
assertNull(
goog.dom.getAncestorByTagNameAndClass(elem, goog.dom.TagName.IMG));
}
function testGetAncestorByTagNameOnly() {
var elem = goog.dom.getElement('nestedElement');
var expected = goog.dom.getElement('testAncestorDiv');
assertEquals(expected,
goog.dom.getAncestorByTagNameAndClass(elem, goog.dom.TagName.DIV));
assertEquals(expected,
goog.dom.getAncestorByTagNameAndClass(elem, 'div'));
}
function testGetAncestorByClassNameNoMatch() {
var elem = goog.dom.getElement('nestedElement');
assertNull(
goog.dom.getAncestorByClass(elem, 'bogusClassName'));
}
function testGetAncestorByClassName() {
var elem = goog.dom.getElement('nestedElement');
var expected = goog.dom.getElement('testAncestorP');
assertEquals(expected,
goog.dom.getAncestorByClass(elem, 'testAncestor'));
}
function testGetAncestorByTagNameAndClass() {
var elem = goog.dom.getElement('nestedElement');
var expected = goog.dom.getElement('testAncestorDiv');
assertEquals(expected,
goog.dom.getAncestorByTagNameAndClass(elem, goog.dom.TagName.DIV,
'testAncestor'));
assertNull(
'Should return null if no search criteria are given',
goog.dom.getAncestorByTagNameAndClass(elem));
}
function testCreateTable() {
var table = goog.dom.createTable(2, 3, true);
assertEquals(2, table.getElementsByTagName(goog.dom.TagName.TR).length);
assertEquals(3,
table.getElementsByTagName(goog.dom.TagName.TR)[0].childNodes.length);
assertEquals(6, table.getElementsByTagName(goog.dom.TagName.TD).length);
assertEquals(goog.string.Unicode.NBSP,
table.getElementsByTagName(goog.dom.TagName.TD)[0].firstChild.nodeValue);
table = goog.dom.createTable(2, 3, false);
assertEquals(2, table.getElementsByTagName(goog.dom.TagName.TR).length);
assertEquals(3,
table.getElementsByTagName(goog.dom.TagName.TR)[0].childNodes.length);
assertEquals(6, table.getElementsByTagName(goog.dom.TagName.TD).length);
assertEquals(0,
table.getElementsByTagName(goog.dom.TagName.TD)[0].childNodes.length);
}
function testHtmlToDocumentFragment() {
var docFragment = goog.dom.htmlToDocumentFragment('<a>1</a><b>2</b>');
assertNull(docFragment.parentNode);
assertEquals(2, docFragment.childNodes.length);
var div = goog.dom.htmlToDocumentFragment('<div>3</div>');
assertEquals('DIV', div.tagName);
var script = goog.dom.htmlToDocumentFragment('<script></script>');
assertEquals('SCRIPT', script.tagName);
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
// Removing an Element from a DOM tree in IE sets its parentNode to a new
// DocumentFragment. Bizarre!
assertEquals(goog.dom.NodeType.DOCUMENT_FRAGMENT,
goog.dom.removeNode(div).parentNode.nodeType);
} else {
assertNull(div.parentNode);
}
}
function testAppend() {
var div = document.createElement('div');
var b = document.createElement('b');
var c = document.createTextNode('c');
goog.dom.append(div, 'a', b, c);
assertEqualsCaseAndLeadingWhitespaceInsensitive('a<b></b>c', div.innerHTML);
}
function testAppend2() {
var div = myIframeDoc.createElement('div');
var b = myIframeDoc.createElement('b');
var c = myIframeDoc.createTextNode('c');
goog.dom.append(div, 'a', b, c);
assertEqualsCaseAndLeadingWhitespaceInsensitive('a<b></b>c', div.innerHTML);
}
function testAppend3() {
var div = document.createElement('div');
var b = document.createElement('b');
var c = document.createTextNode('c');
goog.dom.append(div, ['a', b, c]);
assertEqualsCaseAndLeadingWhitespaceInsensitive('a<b></b>c', div.innerHTML);
}
function testAppend4() {
var div = document.createElement('div');
var div2 = document.createElement('div');
div2.innerHTML = 'a<b></b>c';
goog.dom.append(div, div2.childNodes);
assertEqualsCaseAndLeadingWhitespaceInsensitive('a<b></b>c', div.innerHTML);
assertFalse(div2.hasChildNodes());
}
function testGetDocumentScroll() {
// setUpPage added divForTestingScrolling to the DOM. It's not init'd here so
// it can be shared amonst other tests.
window.scrollTo(100, 100);
assertEquals(100, goog.dom.getDocumentScroll().x);
assertEquals(100, goog.dom.getDocumentScroll().y);
}
function testGetDocumentScrollOfFixedViewport() {
// iOS and perhaps other environments don't actually support scrolling.
// Instead, you view the document's fixed layout through a screen viewport.
// We need getDocumentScroll to handle this case though.
// In case of IE10 though, we do want to use scrollLeft/scrollTop
// because the rest of the positioning is done off the scrolled away origin.
var fakeDocumentScrollElement = {scrollLeft: 0, scrollTop: 0};
var fakeDocument = {
defaultView: {pageXOffset: 100, pageYOffset: 100},
documentElement: fakeDocumentScrollElement,
body: fakeDocumentScrollElement
};
var dh = goog.dom.getDomHelper(document);
dh.setDocument(fakeDocument);
if (goog.userAgent.IE && goog.userAgent.isVersion(10)) {
assertEquals(0, dh.getDocumentScroll().x);
assertEquals(0, dh.getDocumentScroll().y);
} else {
assertEquals(100, dh.getDocumentScroll().x);
assertEquals(100, dh.getDocumentScroll().y);
}
}
function testActiveElementIE() {
if (!goog.userAgent.IE) {
return;
}
var link = goog.dom.getElement('link');
link.focus();
assertEquals(link.tagName, goog.dom.getActiveElement(document).tagName);
assertEquals(link, goog.dom.getActiveElement(document));
}
function testParentElement() {
var testEl = $('testEl');
var bodyEl = goog.dom.getParentElement(testEl);
assertNotNull(bodyEl);
var htmlEl = goog.dom.getParentElement(bodyEl);
assertNotNull(htmlEl);
var documentNotAnElement = goog.dom.getParentElement(htmlEl);
assertNull(documentNotAnElement);
var tree = goog.dom.htmlToDocumentFragment(
'<div>' +
'<p>Some text</p>' +
'<blockquote>Some <i>special</i> <b>text</b></blockquote>' +
'<address><!-- comment -->Foo</address>' +
'</div>');
assertNull(goog.dom.getParentElement(tree));
pEl = goog.dom.getNextNode(tree);
var fragmentRootEl = goog.dom.getParentElement(pEl);
assertEquals(tree, fragmentRootEl);
var detachedEl = goog.dom.createDom('div');
var detachedHasNoParent = goog.dom.getParentElement(detachedEl);
assertNull(detachedHasNoParent);
}
/**
* @return {boolean} Returns true if the userAgent is IE8 or higher.
*/
function isIE8OrHigher() {
return goog.userAgent.IE && goog.userAgent.product.isVersion('8');
}
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Utilities for working with W3C multi-part ranges.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.MultiRange');
goog.provide('goog.dom.MultiRangeIterator');
goog.require('goog.array');
goog.require('goog.debug.Logger');
goog.require('goog.dom.AbstractMultiRange');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.RangeIterator');
goog.require('goog.dom.RangeType');
goog.require('goog.dom.SavedRange');
goog.require('goog.dom.TextRange');
goog.require('goog.iter.StopIteration');
/**
* Creates a new multi part range with no properties. Do not use this
* constructor: use one of the goog.dom.Range.createFrom* methods instead.
* @constructor
* @extends {goog.dom.AbstractMultiRange}
*/
goog.dom.MultiRange = function() {
/**
* Array of browser sub-ranges comprising this multi-range.
* @type {Array.<Range>}
* @private
*/
this.browserRanges_ = [];
/**
* Lazily initialized array of range objects comprising this multi-range.
* @type {Array.<goog.dom.TextRange>}
* @private
*/
this.ranges_ = [];
/**
* Lazily computed sorted version of ranges_, sorted by start point.
* @type {Array.<goog.dom.TextRange>?}
* @private
*/
this.sortedRanges_ = null;
/**
* Lazily computed container node.
* @type {Node}
* @private
*/
this.container_ = null;
};
goog.inherits(goog.dom.MultiRange, goog.dom.AbstractMultiRange);
/**
* Creates a new range wrapper from the given browser selection object. Do not
* use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Selection} selection The browser selection object.
* @return {goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromBrowserSelection = function(selection) {
var range = new goog.dom.MultiRange();
for (var i = 0, len = selection.rangeCount; i < len; i++) {
range.browserRanges_.push(selection.getRangeAt(i));
}
return range;
};
/**
* Creates a new range wrapper from the given browser ranges. Do not
* use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Array.<Range>} browserRanges The browser ranges.
* @return {goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromBrowserRanges = function(browserRanges) {
var range = new goog.dom.MultiRange();
range.browserRanges_ = goog.array.clone(browserRanges);
return range;
};
/**
* Creates a new range wrapper from the given goog.dom.TextRange objects. Do
* not use this method directly - please use goog.dom.Range.createFrom* instead.
* @param {Array.<goog.dom.TextRange>} textRanges The text range objects.
* @return {goog.dom.MultiRange} A range wrapper object.
*/
goog.dom.MultiRange.createFromTextRanges = function(textRanges) {
var range = new goog.dom.MultiRange();
range.ranges_ = textRanges;
range.browserRanges_ = goog.array.map(textRanges, function(range) {
return range.getBrowserRangeObject();
});
return range;
};
/**
* Logging object.
* @type {goog.debug.Logger}
* @private
*/
goog.dom.MultiRange.prototype.logger_ =
goog.debug.Logger.getLogger('goog.dom.MultiRange');
// Method implementations
/**
* Clears cached values. Should be called whenever this.browserRanges_ is
* modified.
* @private
*/
goog.dom.MultiRange.prototype.clearCachedValues_ = function() {
this.ranges_ = [];
this.sortedRanges_ = null;
this.container_ = null;
};
/**
* @return {goog.dom.MultiRange} A clone of this range.
* @override
*/
goog.dom.MultiRange.prototype.clone = function() {
return goog.dom.MultiRange.createFromBrowserRanges(this.browserRanges_);
};
/** @override */
goog.dom.MultiRange.prototype.getType = function() {
return goog.dom.RangeType.MULTI;
};
/** @override */
goog.dom.MultiRange.prototype.getBrowserRangeObject = function() {
// NOTE(robbyw): This method does not make sense for multi-ranges.
if (this.browserRanges_.length > 1) {
this.logger_.warning(
'getBrowserRangeObject called on MultiRange with more than 1 range');
}
return this.browserRanges_[0];
};
/** @override */
goog.dom.MultiRange.prototype.setBrowserRangeObject = function(nativeRange) {
// TODO(robbyw): Look in to adding setBrowserSelectionObject.
return false;
};
/** @override */
goog.dom.MultiRange.prototype.getTextRangeCount = function() {
return this.browserRanges_.length;
};
/** @override */
goog.dom.MultiRange.prototype.getTextRange = function(i) {
if (!this.ranges_[i]) {
this.ranges_[i] = goog.dom.TextRange.createFromBrowserRange(
this.browserRanges_[i]);
}
return this.ranges_[i];
};
/** @override */
goog.dom.MultiRange.prototype.getContainer = function() {
if (!this.container_) {
var nodes = [];
for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
nodes.push(this.getTextRange(i).getContainer());
}
this.container_ = goog.dom.findCommonAncestor.apply(null, nodes);
}
return this.container_;
};
/**
* @return {Array.<goog.dom.TextRange>} An array of sub-ranges, sorted by start
* point.
*/
goog.dom.MultiRange.prototype.getSortedRanges = function() {
if (!this.sortedRanges_) {
this.sortedRanges_ = this.getTextRanges();
this.sortedRanges_.sort(function(a, b) {
var aStartNode = a.getStartNode();
var aStartOffset = a.getStartOffset();
var bStartNode = b.getStartNode();
var bStartOffset = b.getStartOffset();
if (aStartNode == bStartNode && aStartOffset == bStartOffset) {
return 0;
}
return goog.dom.Range.isReversed(aStartNode, aStartOffset, bStartNode,
bStartOffset) ? 1 : -1;
});
}
return this.sortedRanges_;
};
/** @override */
goog.dom.MultiRange.prototype.getStartNode = function() {
return this.getSortedRanges()[0].getStartNode();
};
/** @override */
goog.dom.MultiRange.prototype.getStartOffset = function() {
return this.getSortedRanges()[0].getStartOffset();
};
/** @override */
goog.dom.MultiRange.prototype.getEndNode = function() {
// NOTE(robbyw): This may return the wrong node if any subranges overlap.
return goog.array.peek(this.getSortedRanges()).getEndNode();
};
/** @override */
goog.dom.MultiRange.prototype.getEndOffset = function() {
// NOTE(robbyw): This may return the wrong value if any subranges overlap.
return goog.array.peek(this.getSortedRanges()).getEndOffset();
};
/** @override */
goog.dom.MultiRange.prototype.isRangeInDocument = function() {
return goog.array.every(this.getTextRanges(), function(range) {
return range.isRangeInDocument();
});
};
/** @override */
goog.dom.MultiRange.prototype.isCollapsed = function() {
return this.browserRanges_.length == 0 ||
this.browserRanges_.length == 1 && this.getTextRange(0).isCollapsed();
};
/** @override */
goog.dom.MultiRange.prototype.getText = function() {
return goog.array.map(this.getTextRanges(), function(range) {
return range.getText();
}).join('');
};
/** @override */
goog.dom.MultiRange.prototype.getHtmlFragment = function() {
return this.getValidHtml();
};
/** @override */
goog.dom.MultiRange.prototype.getValidHtml = function() {
// NOTE(robbyw): This does not behave well if the sub-ranges overlap.
return goog.array.map(this.getTextRanges(), function(range) {
return range.getValidHtml();
}).join('');
};
/** @override */
goog.dom.MultiRange.prototype.getPastableHtml = function() {
// TODO(robbyw): This should probably do something smart like group TR and TD
// selections in to the same table.
return this.getValidHtml();
};
/** @override */
goog.dom.MultiRange.prototype.__iterator__ = function(opt_keys) {
return new goog.dom.MultiRangeIterator(this);
};
// RANGE ACTIONS
/** @override */
goog.dom.MultiRange.prototype.select = function() {
var selection = goog.dom.AbstractRange.getBrowserSelectionForWindow(
this.getWindow());
selection.removeAllRanges();
for (var i = 0, len = this.getTextRangeCount(); i < len; i++) {
selection.addRange(this.getTextRange(i).getBrowserRangeObject());
}
};
/** @override */
goog.dom.MultiRange.prototype.removeContents = function() {
goog.array.forEach(this.getTextRanges(), function(range) {
range.removeContents();
});
};
// SAVE/RESTORE
/** @override */
goog.dom.MultiRange.prototype.saveUsingDom = function() {
return new goog.dom.DomSavedMultiRange_(this);
};
// RANGE MODIFICATION
/**
* Collapses this range to a single point, either the first or last point
* depending on the parameter. This will result in the number of ranges in this
* multi range becoming 1.
* @param {boolean} toAnchor Whether to collapse to the anchor.
* @override
*/
goog.dom.MultiRange.prototype.collapse = function(toAnchor) {
if (!this.isCollapsed()) {
var range = toAnchor ? this.getTextRange(0) : this.getTextRange(
this.getTextRangeCount() - 1);
this.clearCachedValues_();
range.collapse(toAnchor);
this.ranges_ = [range];
this.sortedRanges_ = [range];
this.browserRanges_ = [range.getBrowserRangeObject()];
}
};
// SAVED RANGE OBJECTS
/**
* A SavedRange implementation using DOM endpoints.
* @param {goog.dom.MultiRange} range The range to save.
* @constructor
* @extends {goog.dom.SavedRange}
* @private
*/
goog.dom.DomSavedMultiRange_ = function(range) {
/**
* Array of saved ranges.
* @type {Array.<goog.dom.SavedRange>}
* @private
*/
this.savedRanges_ = goog.array.map(range.getTextRanges(), function(range) {
return range.saveUsingDom();
});
};
goog.inherits(goog.dom.DomSavedMultiRange_, goog.dom.SavedRange);
/**
* @return {goog.dom.MultiRange} The restored range.
* @override
*/
goog.dom.DomSavedMultiRange_.prototype.restoreInternal = function() {
var ranges = goog.array.map(this.savedRanges_, function(savedRange) {
return savedRange.restore();
});
return goog.dom.MultiRange.createFromTextRanges(ranges);
};
/** @override */
goog.dom.DomSavedMultiRange_.prototype.disposeInternal = function() {
goog.dom.DomSavedMultiRange_.superClass_.disposeInternal.call(this);
goog.array.forEach(this.savedRanges_, function(savedRange) {
savedRange.dispose();
});
delete this.savedRanges_;
};
// RANGE ITERATION
/**
* Subclass of goog.dom.TagIterator that iterates over a DOM range. It
* adds functions to determine the portion of each text node that is selected.
*
* @param {goog.dom.MultiRange} range The range to traverse.
* @constructor
* @extends {goog.dom.RangeIterator}
*/
goog.dom.MultiRangeIterator = function(range) {
if (range) {
this.iterators_ = goog.array.map(
range.getSortedRanges(),
function(r) {
return goog.iter.toIterator(r);
});
}
goog.dom.RangeIterator.call(
this, range ? this.getStartNode() : null, false);
};
goog.inherits(goog.dom.MultiRangeIterator, goog.dom.RangeIterator);
/**
* The list of range iterators left to traverse.
* @type {Array.<goog.dom.RangeIterator>?}
* @private
*/
goog.dom.MultiRangeIterator.prototype.iterators_ = null;
/**
* The index of the current sub-iterator being traversed.
* @type {number}
* @private
*/
goog.dom.MultiRangeIterator.prototype.currentIdx_ = 0;
/** @override */
goog.dom.MultiRangeIterator.prototype.getStartTextOffset = function() {
return this.iterators_[this.currentIdx_].getStartTextOffset();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getEndTextOffset = function() {
return this.iterators_[this.currentIdx_].getEndTextOffset();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getStartNode = function() {
return this.iterators_[0].getStartNode();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.getEndNode = function() {
return goog.array.peek(this.iterators_).getEndNode();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.isLast = function() {
return this.iterators_[this.currentIdx_].isLast();
};
/** @override */
goog.dom.MultiRangeIterator.prototype.next = function() {
/** @preserveTry */
try {
var it = this.iterators_[this.currentIdx_];
var next = it.next();
this.setPosition(it.node, it.tagType, it.depth);
return next;
} catch (ex) {
if (ex !== goog.iter.StopIteration ||
this.iterators_.length - 1 == this.currentIdx_) {
throw ex;
} else {
// In case we got a StopIteration, increment counter and try again.
this.currentIdx_++;
return this.next();
}
}
};
/** @override */
goog.dom.MultiRangeIterator.prototype.copyFrom = function(other) {
this.iterators_ = goog.array.clone(other.iterators_);
goog.dom.MultiRangeIterator.superClass_.copyFrom.call(this, other);
};
/**
* @return {goog.dom.MultiRangeIterator} An identical iterator.
* @override
*/
goog.dom.MultiRangeIterator.prototype.clone = function() {
var copy = new goog.dom.MultiRangeIterator(null);
copy.copyFrom(this);
return copy;
};
| JavaScript |
// Copyright 2009 The Closure Library Authors. 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 Utilities for adding, removing and setting values in
* an Element's dataset.
* See {@link http://www.w3.org/TR/html5/Overview.html#dom-dataset}.
*
*/
goog.provide('goog.dom.dataset');
goog.require('goog.string');
/**
* The DOM attribute name prefix that must be present for it to be considered
* for a dataset.
* @type {string}
* @const
* @private
*/
goog.dom.dataset.PREFIX_ = 'data-';
/**
* Sets a custom data attribute on an element. The key should be
* in camelCase format (e.g "keyName" for the "data-key-name" attribute).
* @param {Element} element DOM node to set the custom data attribute on.
* @param {string} key Key for the custom data attribute.
* @param {string} value Value for the custom data attribute.
*/
goog.dom.dataset.set = function(element, key, value) {
if (element.dataset) {
element.dataset[key] = value;
} else {
element.setAttribute(
goog.dom.dataset.PREFIX_ + goog.string.toSelectorCase(key),
value);
}
};
/**
* Gets a custom data attribute from an element. The key should be
* in camelCase format (e.g "keyName" for the "data-key-name" attribute).
* @param {Element} element DOM node to get the custom data attribute from.
* @param {string} key Key for the custom data attribute.
* @return {?string} The attribute value, if it exists.
*/
goog.dom.dataset.get = function(element, key) {
if (element.dataset) {
return element.dataset[key];
} else {
return element.getAttribute(goog.dom.dataset.PREFIX_ +
goog.string.toSelectorCase(key));
}
};
/**
* Removes a custom data attribute from an element. The key should be
* in camelCase format (e.g "keyName" for the "data-key-name" attribute).
* @param {Element} element DOM node to get the custom data attribute from.
* @param {string} key Key for the custom data attribute.
*/
goog.dom.dataset.remove = function(element, key) {
if (element.dataset) {
delete element.dataset[key];
} else {
element.removeAttribute(goog.dom.dataset.PREFIX_ +
goog.string.toSelectorCase(key));
}
};
/**
* Checks whether custom data attribute exists on an element. The key should be
* in camelCase format (e.g "keyName" for the "data-key-name" attribute).
*
* @param {Element} element DOM node to get the custom data attribute from.
* @param {string} key Key for the custom data attribute.
* @return {boolean} Whether the attibute exists.
*/
goog.dom.dataset.has = function(element, key) {
if (element.dataset) {
return key in element.dataset;
} else if (element.hasAttribute) {
return element.hasAttribute(goog.dom.dataset.PREFIX_ +
goog.string.toSelectorCase(key));
} else {
return !!(element.getAttribute(goog.dom.dataset.PREFIX_ +
goog.string.toSelectorCase(key)));
}
};
/**
* Gets all custom data attributes as a string map. The attribute names will be
* camel cased (e.g., data-foo-bar -> dataset['fooBar']). This operation is not
* safe for attributes having camel-cased names clashing with already existing
* properties (e.g., data-to-string -> dataset['toString']).
* @param {!Element} element DOM node to get the data attributes from.
* @return {!Object} The string map containing data attributes and their
* respective values.
*/
goog.dom.dataset.getAll = function(element) {
if (element.dataset) {
return element.dataset;
} else {
var dataset = {};
var attributes = element.attributes;
for (var i = 0; i < attributes.length; ++i) {
var attribute = attributes[i];
if (goog.string.startsWith(attribute.name,
goog.dom.dataset.PREFIX_)) {
// We use substr(5), since it's faster than replacing 'data-' with ''.
var key = goog.string.toCamelCase(attribute.name.substr(5));
dataset[key] = attribute.value;
}
}
return dataset;
}
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 Functions for managing full screen status of the DOM.
*
*/
goog.provide('goog.dom.fullscreen');
goog.provide('goog.dom.fullscreen.EventType');
goog.require('goog.dom');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');
/**
* Event types for full screen.
* @enum {string}
*/
goog.dom.fullscreen.EventType = {
/** Dispatched by the Document when the fullscreen status changes. */
CHANGE: goog.userAgent.WEBKIT ?
'webkitfullscreenchange' :
'mozfullscreenchange'
};
/**
* Determines if full screen is supported.
* @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
* queried. If not provided, use the current DOM.
* @return {boolean} True iff full screen is supported.
*/
goog.dom.fullscreen.isSupported = function(opt_domHelper) {
var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
var body = doc.body;
return !!body.webkitRequestFullScreen ||
(!!body.mozRequestFullScreen && doc.mozFullScreenEnabled);
};
/**
* Requests putting the element in full screen.
* @param {!Element} element The element to put full screen.
*/
goog.dom.fullscreen.requestFullScreen = function(element) {
if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
}
};
/**
* Requests putting the element in full screen with full keyboard access.
* @param {!Element} element The element to put full screen.
*/
goog.dom.fullscreen.requestFullScreenWithKeys = function(
element) {
if (element.mozRequestFullScreenWithKeys) {
element.mozRequestFullScreenWithKeys();
} else if (element.webkitRequestFullScreen &&
element.ALLOW_KEYBOARD_INPUT &&
goog.userAgent.product.CHROME) {
// Safari has the ALLOW_KEYBOARD_INPUT property but using it gives an error.
element.webkitRequestFullScreen(element.ALLOW_KEYBOARD_INPUT);
} else {
goog.dom.fullscreen.requestFullScreen(element);
}
};
/**
* Exits full screen.
* @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
* queried. If not provided, use the current DOM.
*/
goog.dom.fullscreen.exitFullScreen = function(opt_domHelper) {
var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
if (doc.webkitCancelFullScreen) {
doc.webkitCancelFullScreen();
} else if (doc.mozCancelFullScreen) {
doc.mozCancelFullScreen();
}
};
/**
* Determines if the document is full screen.
* @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
* queried. If not provided, use the current DOM.
* @return {boolean} Whether the document is full screen.
*/
goog.dom.fullscreen.isFullScreen = function(opt_domHelper) {
var doc = goog.dom.fullscreen.getDocument_(opt_domHelper);
return !!doc.webkitIsFullScreen || !!doc.mozFullScreen;
};
/**
* Gets the document object of the dom.
* @param {!goog.dom.DomHelper=} opt_domHelper The DomHelper for the DOM being
* queried. If not provided, use the current DOM.
* @return {!Document} The dom document.
* @private
*/
goog.dom.fullscreen.getDocument_ = function(opt_domHelper) {
return opt_domHelper ?
opt_domHelper.getDocument() :
goog.dom.getDomHelper().getDocument();
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 goog.dom.BufferedViewportSizeMonitor.
*
*/
/** @suppress {extraProvide} */
goog.provide('goog.dom.BufferedViewportSizeMonitorTest');
goog.require('goog.dom.BufferedViewportSizeMonitor');
goog.require('goog.dom.ViewportSizeMonitor');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math.Size');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.events');
goog.require('goog.testing.events.Event');
goog.require('goog.testing.jsunit');
goog.setTestOnly('goog.dom.BufferedViewportSizeMonitorTest');
var RESIZE_DELAY = goog.dom.BufferedViewportSizeMonitor.RESIZE_EVENT_DELAY_MS_;
var INITIAL_SIZE = new goog.math.Size(111, 111);
var mockControl;
var viewportSizeMonitor;
var bufferedVsm;
var timer = new goog.testing.MockClock();
var resizeEventCount = 0;
var size;
var resizeCallback = function() {
resizeEventCount++;
};
function setUp() {
timer.install();
size = INITIAL_SIZE;
viewportSizeMonitor = new goog.dom.ViewportSizeMonitor();
viewportSizeMonitor.getSize = function() { return size; };
bufferedVsm = new goog.dom.BufferedViewportSizeMonitor(viewportSizeMonitor);
goog.events.listen(bufferedVsm, goog.events.EventType.RESIZE, resizeCallback);
}
function tearDown() {
goog.events.unlisten(
bufferedVsm, goog.events.EventType.RESIZE, resizeCallback);
resizeEventCount = 0;
timer.uninstall();
}
function testInitialSizes() {
assertTrue(goog.math.Size.equals(INITIAL_SIZE, bufferedVsm.getSize()));
}
function testWindowResize() {
assertEquals(0, resizeEventCount);
resize(100, 100);
timer.tick(RESIZE_DELAY - 1);
assertEquals(
'No resize expected before the delay is fired', 0, resizeEventCount);
timer.tick(1);
assertEquals('Expected resize after delay', 1, resizeEventCount);
assertTrue(goog.math.Size.equals(
new goog.math.Size(100, 100), bufferedVsm.getSize()));
}
function testWindowResize_eventBatching() {
assertEquals('No resize calls expected before resize events',
0, resizeEventCount);
resize(100, 100);
timer.tick(RESIZE_DELAY - 1);
resize(200, 200);
assertEquals(
'No resize expected before the delay is fired', 0, resizeEventCount);
timer.tick(1);
assertEquals(
'No resize expected when delay is restarted', 0, resizeEventCount);
timer.tick(RESIZE_DELAY);
assertEquals('Expected resize after delay', 1, resizeEventCount);
}
function testWindowResize_noChange() {
resize(100, 100);
timer.tick(RESIZE_DELAY);
assertEquals(1, resizeEventCount);
resize(100, 100);
timer.tick(RESIZE_DELAY);
assertEquals(
'No resize expected when size doesn\'t change', 1, resizeEventCount);
assertTrue(goog.math.Size.equals(
new goog.math.Size(100, 100), bufferedVsm.getSize()));
}
function testWindowResize_previousSize() {
resize(100, 100);
timer.tick(RESIZE_DELAY);
assertEquals(1, resizeEventCount);
assertTrue(goog.math.Size.equals(
new goog.math.Size(100, 100), bufferedVsm.getSize()));
resize(200, 200);
timer.tick(RESIZE_DELAY);
assertEquals(2, resizeEventCount);
assertTrue(goog.math.Size.equals(
new goog.math.Size(200, 200), bufferedVsm.getSize()));
}
function resize(width, height) {
size = new goog.math.Size(width, height);
goog.testing.events.fireBrowserEvent(
new goog.testing.events.Event(
goog.events.EventType.RESIZE, viewportSizeMonitor));
}
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 Browser capability checks for the dom package.
*
*/
goog.provide('goog.dom.BrowserFeature');
goog.require('goog.userAgent');
/**
* Enum of browser capabilities.
* @enum {boolean}
*/
goog.dom.BrowserFeature = {
/**
* Whether attributes 'name' and 'type' can be added to an element after it's
* created. False in Internet Explorer prior to version 9.
*/
CAN_ADD_NAME_OR_TYPE_ATTRIBUTES: !goog.userAgent.IE ||
goog.userAgent.isDocumentMode(9),
/**
* Whether we can use element.children to access an element's Element
* children. Available since Gecko 1.9.1, IE 9. (IE<9 also includes comment
* nodes in the collection.)
*/
CAN_USE_CHILDREN_ATTRIBUTE: !goog.userAgent.GECKO && !goog.userAgent.IE ||
goog.userAgent.IE && goog.userAgent.isDocumentMode(9) ||
goog.userAgent.GECKO && goog.userAgent.isVersion('1.9.1'),
/**
* Opera, Safari 3, and Internet Explorer 9 all support innerText but they
* include text nodes in script and style tags. Not document-mode-dependent.
*/
CAN_USE_INNER_TEXT: goog.userAgent.IE && !goog.userAgent.isVersion('9'),
/**
* MSIE, Opera, and Safari>=4 support element.parentElement to access an
* element's parent if it is an Element.
*/
CAN_USE_PARENT_ELEMENT_PROPERTY: goog.userAgent.IE || goog.userAgent.OPERA ||
goog.userAgent.WEBKIT,
/**
* Whether NoScope elements need a scoped element written before them in
* innerHTML.
* MSDN: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx#1
*/
INNER_HTML_NEEDS_SCOPED_ELEMENT: goog.userAgent.IE
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Iterator subclass for DOM tree traversal.
*
* @author robbyw@google.com (Robby Walker)
*/
goog.provide('goog.dom.NodeIterator');
goog.require('goog.dom.TagIterator');
/**
* A DOM tree traversal iterator.
*
* Starting with the given node, the iterator walks the DOM in order, reporting
* events for each node. The iterator acts as a prefix iterator:
*
* <pre>
* <div>1<span>2</span>3</div>
* </pre>
*
* Will return the following nodes:
*
* <code>[div, 1, span, 2, 3]</code>
*
* With the following depths
*
* <code>[1, 1, 2, 2, 1]</code>
*
* Imagining <code>|</code> represents iterator position, the traversal stops at
* each of the following locations:
*
* <pre><div>|1|<span>|2|</span>3|</div></pre>
*
* The iterator can also be used in reverse mode, which will return the nodes
* and states in the opposite order. The depths will be slightly different
* since, like in normal mode, the depth is computed *after* the last move.
*
* Lastly, it is possible to create an iterator that is unconstrained, meaning
* that it will continue iterating until the end of the document instead of
* until exiting the start node.
*
* @param {Node=} opt_node The start node. Defaults to an empty iterator.
* @param {boolean=} opt_reversed Whether to traverse the tree in reverse.
* @param {boolean=} opt_unconstrained Whether the iterator is not constrained
* to the starting node and its children.
* @param {number=} opt_depth The starting tree depth.
* @constructor
* @extends {goog.dom.TagIterator}
*/
goog.dom.NodeIterator = function(opt_node, opt_reversed,
opt_unconstrained, opt_depth) {
goog.dom.TagIterator.call(this, opt_node, opt_reversed, opt_unconstrained,
null, opt_depth);
};
goog.inherits(goog.dom.NodeIterator, goog.dom.TagIterator);
/**
* Moves to the next position in the DOM tree.
* @return {Node} Returns the next node, or throws a goog.iter.StopIteration
* exception if the end of the iterator's range has been reached.
* @override
*/
goog.dom.NodeIterator.prototype.next = function() {
do {
goog.dom.NodeIterator.superClass_.next.call(this);
} while (this.isEndTag());
return this.node;
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Utilities for working with ranges in HTML documents.
*
* @author robbyw@google.com (Robby Walker)
* @author ojan@google.com (Ojan Vafai)
* @author jparent@google.com (Julie Parent)
*/
goog.provide('goog.dom.Range');
goog.require('goog.dom');
goog.require('goog.dom.AbstractRange');
goog.require('goog.dom.ControlRange');
goog.require('goog.dom.MultiRange');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TextRange');
goog.require('goog.userAgent');
/**
* Create a new selection from the given browser window's current selection.
* Note that this object does not auto-update if the user changes their
* selection and should be used as a snapshot.
* @param {Window=} opt_win The window to get the selection of. Defaults to the
* window this class was defined in.
* @return {goog.dom.AbstractRange?} A range wrapper object, or null if there
* was an error.
*/
goog.dom.Range.createFromWindow = function(opt_win) {
var sel = goog.dom.AbstractRange.getBrowserSelectionForWindow(
opt_win || window);
return sel && goog.dom.Range.createFromBrowserSelection(sel);
};
/**
* Create a new range wrapper from the given browser selection object. Note
* that this object does not auto-update if the user changes their selection and
* should be used as a snapshot.
* @param {!Object} selection The browser selection object.
* @return {goog.dom.AbstractRange?} A range wrapper object or null if there
* was an error.
*/
goog.dom.Range.createFromBrowserSelection = function(selection) {
var range;
var isReversed = false;
if (selection.createRange) {
/** @preserveTry */
try {
range = selection.createRange();
} catch (e) {
// Access denied errors can be thrown here in IE if the selection was
// a flash obj or if there are cross domain issues
return null;
}
} else if (selection.rangeCount) {
if (selection.rangeCount > 1) {
return goog.dom.MultiRange.createFromBrowserSelection(
/** @type {Selection} */ (selection));
} else {
range = selection.getRangeAt(0);
isReversed = goog.dom.Range.isReversed(selection.anchorNode,
selection.anchorOffset, selection.focusNode, selection.focusOffset);
}
} else {
return null;
}
return goog.dom.Range.createFromBrowserRange(range, isReversed);
};
/**
* Create a new range wrapper from the given browser range object.
* @param {Range|TextRange} range The browser range object.
* @param {boolean=} opt_isReversed Whether the focus node is before the anchor
* node.
* @return {goog.dom.AbstractRange} A range wrapper object.
*/
goog.dom.Range.createFromBrowserRange = function(range, opt_isReversed) {
// Create an IE control range when appropriate.
return goog.dom.AbstractRange.isNativeControlRange(range) ?
goog.dom.ControlRange.createFromBrowserRange(range) :
goog.dom.TextRange.createFromBrowserRange(range, opt_isReversed);
};
/**
* Create a new range wrapper that selects the given node's text.
* @param {Node} node The node to select.
* @param {boolean=} opt_isReversed Whether the focus node is before the anchor
* node.
* @return {goog.dom.AbstractRange} A range wrapper object.
*/
goog.dom.Range.createFromNodeContents = function(node, opt_isReversed) {
return goog.dom.TextRange.createFromNodeContents(node, opt_isReversed);
};
/**
* Create a new range wrapper that represents a caret at the given node,
* accounting for the given offset. This always creates a TextRange, regardless
* of whether node is an image node or other control range type node.
* @param {Node} node The node to place a caret at.
* @param {number} offset The offset within the node to place the caret at.
* @return {goog.dom.AbstractRange} A range wrapper object.
*/
goog.dom.Range.createCaret = function(node, offset) {
return goog.dom.TextRange.createFromNodes(node, offset, node, offset);
};
/**
* Create a new range wrapper that selects the area between the given nodes,
* accounting for the given offsets.
* @param {Node} startNode The node to start with.
* @param {number} startOffset The offset within the node to start.
* @param {Node} endNode The node to end with.
* @param {number} endOffset The offset within the node to end.
* @return {goog.dom.AbstractRange} A range wrapper object.
*/
goog.dom.Range.createFromNodes = function(startNode, startOffset, endNode,
endOffset) {
return goog.dom.TextRange.createFromNodes(startNode, startOffset, endNode,
endOffset);
};
/**
* Clears the window's selection.
* @param {Window=} opt_win The window to get the selection of. Defaults to the
* window this class was defined in.
*/
goog.dom.Range.clearSelection = function(opt_win) {
var sel = goog.dom.AbstractRange.getBrowserSelectionForWindow(
opt_win || window);
if (!sel) {
return;
}
if (sel.empty) {
// We can't just check that the selection is empty, becuase IE
// sometimes gets confused.
try {
sel.empty();
} catch (e) {
// Emptying an already empty selection throws an exception in IE
}
} else {
try {
sel.removeAllRanges();
} catch (e) {
// This throws in IE9 if the range has been invalidated; for example, if
// the user clicked on an element which disappeared during the event
// handler.
}
}
};
/**
* Tests if the window has a selection.
* @param {Window=} opt_win The window to check the selection of. Defaults to
* the window this class was defined in.
* @return {boolean} Whether the window has a selection.
*/
goog.dom.Range.hasSelection = function(opt_win) {
var sel = goog.dom.AbstractRange.getBrowserSelectionForWindow(
opt_win || window);
return !!sel && (goog.userAgent.IE ? sel.type != 'None' : !!sel.rangeCount);
};
/**
* Returns whether the focus position occurs before the anchor position.
* @param {Node} anchorNode The node to start with.
* @param {number} anchorOffset The offset within the node to start.
* @param {Node} focusNode The node to end with.
* @param {number} focusOffset The offset within the node to end.
* @return {boolean} Whether the focus position occurs before the anchor
* position.
*/
goog.dom.Range.isReversed = function(anchorNode, anchorOffset, focusNode,
focusOffset) {
if (anchorNode == focusNode) {
return focusOffset < anchorOffset;
}
var child;
if (anchorNode.nodeType == goog.dom.NodeType.ELEMENT && anchorOffset) {
child = anchorNode.childNodes[anchorOffset];
if (child) {
anchorNode = child;
anchorOffset = 0;
} else if (goog.dom.contains(anchorNode, focusNode)) {
// If focus node is contained in anchorNode, it must be before the
// end of the node. Hence we are reversed.
return true;
}
}
if (focusNode.nodeType == goog.dom.NodeType.ELEMENT && focusOffset) {
child = focusNode.childNodes[focusOffset];
if (child) {
focusNode = child;
focusOffset = 0;
} else if (goog.dom.contains(focusNode, anchorNode)) {
// If anchor node is contained in focusNode, it must be before the
// end of the node. Hence we are not reversed.
return false;
}
}
return (goog.dom.compareNodeOrder(anchorNode, focusNode) ||
anchorOffset - focusOffset) > 0;
};
| JavaScript |
// Copyright 2008 The Closure Library Authors. 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 Utilities for creating and working with iframes
* cross-browser.
* @author gboyer@google.com (Garry Boyer)
*/
goog.provide('goog.dom.iframe');
goog.require('goog.dom');
/**
* Safe source for a blank iframe.
*
* Intentionally not about:blank, which gives mixed content warnings in IE6
* over HTTPS.
*
* @type {string}
*/
goog.dom.iframe.BLANK_SOURCE = 'javascript:""';
/**
* Styles to help ensure an undecorated iframe.
* @type {string}
* @private
*/
goog.dom.iframe.STYLES_ = 'border:0;vertical-align:bottom;';
/**
* Creates a completely blank iframe element.
*
* The iframe will not caused mixed-content warnings for IE6 under HTTPS.
* The iframe will also have no borders or padding, so that the styled width
* and height will be the actual width and height of the iframe.
*
* This function currently only attempts to create a blank iframe. There
* are no guarantees to the contents of the iframe or whether it is rendered
* in quirks mode.
*
* @param {goog.dom.DomHelper} domHelper The dom helper to use.
* @param {string=} opt_styles CSS styles for the iframe.
* @return {!HTMLIFrameElement} A completely blank iframe.
*/
goog.dom.iframe.createBlank = function(domHelper, opt_styles) {
return /** @type {!HTMLIFrameElement} */ (domHelper.createDom('iframe', {
'frameborder': 0,
// Since iframes are inline elements, we must align to bottom to
// compensate for the line descent.
'style': goog.dom.iframe.STYLES_ + (opt_styles || ''),
'src': goog.dom.iframe.BLANK_SOURCE
}));
};
/**
* Writes the contents of a blank iframe that has already been inserted
* into the document.
* @param {!HTMLIFrameElement} iframe An iframe with no contents, such as
* one created by goog.dom.iframe.createBlank, but already appended to
* a parent document.
* @param {string} content Content to write to the iframe, from doctype to
* the HTML close tag.
*/
goog.dom.iframe.writeContent = function(iframe, content) {
var doc = goog.dom.getFrameContentDocument(iframe);
doc.open();
doc.write(content);
doc.close();
};
// TODO(gboyer): Provide a higher-level API for the most common use case, so
// that you can just provide a list of stylesheets and some content HTML.
/**
* Creates a same-domain iframe containing preloaded content.
*
* This is primarily useful for DOM sandboxing. One use case is to embed
* a trusted Javascript app with potentially conflicting CSS styles. The
* second case is to reduce the cost of layout passes by the browser -- for
* example, you can perform sandbox sizing of characters in an iframe while
* manipulating a heavy DOM in the main window. The iframe and parent frame
* can access each others' properties and functions without restriction.
*
* @param {!Element} parentElement The parent element in which to append the
* iframe.
* @param {string=} opt_headContents Contents to go into the iframe's head.
* @param {string=} opt_bodyContents Contents to go into the iframe's body.
* @param {string=} opt_styles CSS styles for the iframe itself, before adding
* to the parent element.
* @param {boolean=} opt_quirks Whether to use quirks mode (false by default).
* @return {HTMLIFrameElement} An iframe that has the specified contents.
*/
goog.dom.iframe.createWithContent = function(
parentElement, opt_headContents, opt_bodyContents, opt_styles, opt_quirks) {
var domHelper = goog.dom.getDomHelper(parentElement);
// Generate the HTML content.
var contentBuf = [];
if (!opt_quirks) {
contentBuf.push('<!DOCTYPE html>');
}
contentBuf.push('<html><head>', opt_headContents, '</head><body>',
opt_bodyContents, '</body></html>');
var iframe = goog.dom.iframe.createBlank(domHelper, opt_styles);
// Cannot manipulate iframe content until it is in a document.
parentElement.appendChild(iframe);
goog.dom.iframe.writeContent(iframe, contentBuf.join(''));
return iframe;
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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 Utilities for working with selections in input boxes and text
* areas.
*
* @see ../demos/dom_selection.html
*/
goog.provide('goog.dom.selection');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* Sets the place where the selection should start inside a textarea or a text
* input
* @param {Element} textfield A textarea or text input.
* @param {number} pos The position to set the start of the selection at.
*/
goog.dom.selection.setStart = function(textfield, pos) {
if (goog.dom.selection.useSelectionProperties_(textfield)) {
textfield.selectionStart = pos;
} else if (goog.userAgent.IE) {
// destructuring assignment would have been sweet
var tmp = goog.dom.selection.getRangeIe_(textfield);
var range = tmp[0];
var selectionRange = tmp[1];
if (range.inRange(selectionRange)) {
pos = goog.dom.selection.canonicalizePositionIe_(textfield, pos);
range.collapse(true);
range.move('character', pos);
range.select();
}
}
};
/**
* Return the place where the selection starts inside a textarea or a text
* input
* @param {Element} textfield A textarea or text input.
* @return {number} The position where the selection starts or 0 if it was
* unable to find the position or no selection exists. Note that we can't
* reliably tell the difference between an element that has no selection and
* one where it starts at 0.
*/
goog.dom.selection.getStart = function(textfield) {
return goog.dom.selection.getEndPoints_(textfield, true)[0];
};
/**
* Returns the start and end points of the selection within a textarea in IE.
* IE treats newline characters as \r\n characters, and we need to check for
* these characters at the edge of our selection, to ensure that we return the
* right cursor position.
* @param {TextRange} range Complete range object, e.g., "Hello\r\n".
* @param {TextRange} selRange Selected range object.
* @param {boolean} getOnlyStart Value indicating if only start
* cursor position is to be returned. In IE, obtaining the end position
* involves extra work, hence we have this parameter for calls which need
* only start position.
* @return {Array.<number>} An array with the start and end positions where the
* selection starts and ends or [0,0] if it was unable to find the
* positions or no selection exists. Note that we can't reliably tell the
* difference between an element that has no selection and one where
* it starts and ends at 0. If getOnlyStart was true, we return
* -1 as end offset.
* @private
*/
goog.dom.selection.getEndPointsTextareaIe_ = function(
range, selRange, getOnlyStart) {
// Create a duplicate of the selected range object to perform our actions
// against. Example of selectionRange = "" (assuming that the cursor is
// just after the \r\n combination)
var selectionRange = selRange.duplicate();
// Text before the selection start, e.g.,"Hello" (notice how range.text
// excludes the \r\n sequence)
var beforeSelectionText = range.text;
// Text before the selection start, e.g., "Hello" (this will later include
// the \r\n sequences also)
var untrimmedBeforeSelectionText = beforeSelectionText;
// Text within the selection , e.g. "" assuming that the cursor is just after
// the \r\n combination.
var selectionText = selectionRange.text;
// Text within the selection, e.g., "" (this will later include the \r\n
// sequences also)
var untrimmedSelectionText = selectionText;
// Boolean indicating whether we are done dealing with the text before the
// selection's beginning.
var isRangeEndTrimmed = false;
// Go over the range until it becomes a 0-lengthed range or until the range
// text starts changing when we move the end back by one character.
// If after moving the end back by one character, the text remains the same,
// then we need to add a "\r\n" at the end to get the actual text.
while (!isRangeEndTrimmed) {
if (range.compareEndPoints('StartToEnd', range) == 0) {
isRangeEndTrimmed = true;
} else {
range.moveEnd('character', -1);
if (range.text == beforeSelectionText) {
// If the start position of the cursor was after a \r\n string,
// we would skip over it in one go with the moveEnd call, but
// range.text will still show "Hello" (because of the IE range.text
// bug) - this implies that we should add a \r\n to our
// untrimmedBeforeSelectionText string.
untrimmedBeforeSelectionText += '\r\n';
} else {
isRangeEndTrimmed = true;
}
}
}
if (getOnlyStart) {
// We return -1 as end, since the caller is only interested in the start
// value.
return [untrimmedBeforeSelectionText.length, -1];
}
// Boolean indicating whether we are done dealing with the text inside the
// selection.
var isSelectionRangeEndTrimmed = false;
// Go over the selected range until it becomes a 0-lengthed range or until
// the range text starts changing when we move the end back by one character.
// If after moving the end back by one character, the text remains the same,
// then we need to add a "\r\n" at the end to get the actual text.
while (!isSelectionRangeEndTrimmed) {
if (selectionRange.compareEndPoints('StartToEnd', selectionRange) == 0) {
isSelectionRangeEndTrimmed = true;
} else {
selectionRange.moveEnd('character', -1);
if (selectionRange.text == selectionText) {
// If the selection was not empty, and the end point of the selection
// was just after a \r\n, we would have skipped it in one go with the
// moveEnd call, and this implies that we should add a \r\n to the
// untrimmedSelectionText string.
untrimmedSelectionText += '\r\n';
} else {
isSelectionRangeEndTrimmed = true;
}
}
}
return [
untrimmedBeforeSelectionText.length,
untrimmedBeforeSelectionText.length + untrimmedSelectionText.length];
};
/**
* Returns the start and end points of the selection inside a textarea or a
* text input.
* @param {Element} textfield A textarea or text input.
* @return {Array.<number>} An array with the start and end positions where the
* selection starts and ends or [0,0] if it was unable to find the
* positions or no selection exists. Note that we can't reliably tell the
* difference between an element that has no selection and one where
* it starts and ends at 0.
*/
goog.dom.selection.getEndPoints = function(textfield) {
return goog.dom.selection.getEndPoints_(textfield, false);
};
/**
* Returns the start and end points of the selection inside a textarea or a
* text input.
* @param {Element} textfield A textarea or text input.
* @param {boolean} getOnlyStart Value indicating if only start
* cursor position is to be returned. In IE, obtaining the end position
* involves extra work, hence we have this parameter. In FF, there is not
* much extra effort involved.
* @return {Array.<number>} An array with the start and end positions where the
* selection starts and ends or [0,0] if it was unable to find the
* positions or no selection exists. Note that we can't reliably tell the
* difference between an element that has no selection and one where
* it starts and ends at 0. If getOnlyStart was true, we return
* -1 as end offset.
* @private
*/
goog.dom.selection.getEndPoints_ = function(textfield, getOnlyStart) {
var startPos = 0;
var endPos = 0;
if (goog.dom.selection.useSelectionProperties_(textfield)) {
startPos = textfield.selectionStart;
endPos = getOnlyStart ? -1 : textfield.selectionEnd;
} else if (goog.userAgent.IE) {
var tmp = goog.dom.selection.getRangeIe_(textfield);
var range = tmp[0];
var selectionRange = tmp[1];
if (range.inRange(selectionRange)) {
range.setEndPoint('EndToStart', selectionRange);
if (textfield.type == 'textarea') {
return goog.dom.selection.getEndPointsTextareaIe_(
range, selectionRange, getOnlyStart);
}
startPos = range.text.length;
if (!getOnlyStart) {
endPos = range.text.length + selectionRange.text.length;
} else {
endPos = -1; // caller did not ask for end position
}
}
}
return [startPos, endPos];
};
/**
* Sets the place where the selection should end inside a text area or a text
* input
* @param {Element} textfield A textarea or text input.
* @param {number} pos The position to end the selection at.
*/
goog.dom.selection.setEnd = function(textfield, pos) {
if (goog.dom.selection.useSelectionProperties_(textfield)) {
textfield.selectionEnd = pos;
} else if (goog.userAgent.IE) {
var tmp = goog.dom.selection.getRangeIe_(textfield);
var range = tmp[0];
var selectionRange = tmp[1];
if (range.inRange(selectionRange)) {
// Both the current position and the start cursor position need
// to be canonicalized to take care of possible \r\n miscounts.
pos = goog.dom.selection.canonicalizePositionIe_(textfield, pos);
var startCursorPos = goog.dom.selection.canonicalizePositionIe_(
textfield, goog.dom.selection.getStart(textfield));
selectionRange.collapse(true);
selectionRange.moveEnd('character', pos - startCursorPos);
selectionRange.select();
}
}
};
/**
* Returns the place where the selection ends inside a textarea or a text input
* @param {Element} textfield A textarea or text input.
* @return {number} The position where the selection ends or 0 if it was
* unable to find the position or no selection exists.
*/
goog.dom.selection.getEnd = function(textfield) {
return goog.dom.selection.getEndPoints_(textfield, false)[1];
};
/**
* Sets the cursor position within a textfield.
* @param {Element} textfield A textarea or text input.
* @param {number} pos The position within the text field.
*/
goog.dom.selection.setCursorPosition = function(textfield, pos) {
if (goog.dom.selection.useSelectionProperties_(textfield)) {
// Mozilla directly supports this
textfield.selectionStart = pos;
textfield.selectionEnd = pos;
} else if (goog.userAgent.IE) {
pos = goog.dom.selection.canonicalizePositionIe_(textfield, pos);
// IE has textranges. A textfield's textrange encompasses the
// entire textfield's text by default
var sel = textfield.createTextRange();
sel.collapse(true);
sel.move('character', pos);
sel.select();
}
};
/**
* Sets the selected text inside a textarea or a text input
* @param {Element} textfield A textarea or text input.
* @param {string} text The text to change the selection to.
*/
goog.dom.selection.setText = function(textfield, text) {
if (goog.dom.selection.useSelectionProperties_(textfield)) {
var value = textfield.value;
var oldSelectionStart = textfield.selectionStart;
var before = value.substr(0, oldSelectionStart);
var after = value.substr(textfield.selectionEnd);
textfield.value = before + text + after;
textfield.selectionStart = oldSelectionStart;
textfield.selectionEnd = oldSelectionStart + text.length;
} else if (goog.userAgent.IE) {
var tmp = goog.dom.selection.getRangeIe_(textfield);
var range = tmp[0];
var selectionRange = tmp[1];
if (!range.inRange(selectionRange)) {
return;
}
// When we set the selection text the selection range is collapsed to the
// end. We therefore duplicate the current selection so we know where it
// started. Once we've set the selection text we move the start of the
// selection range to the old start
var range2 = selectionRange.duplicate();
selectionRange.text = text;
selectionRange.setEndPoint('StartToStart', range2);
selectionRange.select();
} else {
throw Error('Cannot set the selection end');
}
};
/**
* Returns the selected text inside a textarea or a text input
* @param {Element} textfield A textarea or text input.
* @return {string} The selected text.
*/
goog.dom.selection.getText = function(textfield) {
if (goog.dom.selection.useSelectionProperties_(textfield)) {
var s = textfield.value;
return s.substring(textfield.selectionStart, textfield.selectionEnd);
}
if (goog.userAgent.IE) {
var tmp = goog.dom.selection.getRangeIe_(textfield);
var range = tmp[0];
var selectionRange = tmp[1];
if (!range.inRange(selectionRange)) {
return '';
} else if (textfield.type == 'textarea') {
return goog.dom.selection.getSelectionRangeText_(selectionRange);
}
return selectionRange.text;
}
throw Error('Cannot get the selection text');
};
/**
* Returns the selected text within a textarea in IE.
* IE treats newline characters as \r\n characters, and we need to check for
* these characters at the edge of our selection, to ensure that we return the
* right string.
* @param {TextRange} selRange Selected range object.
* @return {string} Selected text in the textarea.
* @private
*/
goog.dom.selection.getSelectionRangeText_ = function(selRange) {
// Create a duplicate of the selected range object to perform our actions
// against. Suppose the text in the textarea is "Hello\r\nWorld" and the
// selection encompasses the "o\r\n" bit, initial selectionRange will be "o"
// (assuming that the cursor is just after the \r\n combination)
var selectionRange = selRange.duplicate();
// Text within the selection , e.g. "o" assuming that the cursor is just after
// the \r\n combination.
var selectionText = selectionRange.text;
// Text within the selection, e.g., "o" (this will later include the \r\n
// sequences also)
var untrimmedSelectionText = selectionText;
// Boolean indicating whether we are done dealing with the text inside the
// selection.
var isSelectionRangeEndTrimmed = false;
// Go over the selected range until it becomes a 0-lengthed range or until
// the range text starts changing when we move the end back by one character.
// If after moving the end back by one character, the text remains the same,
// then we need to add a "\r\n" at the end to get the actual text.
while (!isSelectionRangeEndTrimmed) {
if (selectionRange.compareEndPoints('StartToEnd', selectionRange) == 0) {
isSelectionRangeEndTrimmed = true;
} else {
selectionRange.moveEnd('character', -1);
if (selectionRange.text == selectionText) {
// If the selection was not empty, and the end point of the selection
// was just after a \r\n, we would have skipped it in one go with the
// moveEnd call, and this implies that we should add a \r\n to the
// untrimmedSelectionText string.
untrimmedSelectionText += '\r\n';
} else {
isSelectionRangeEndTrimmed = true;
}
}
}
return untrimmedSelectionText;
};
/**
* Helper function for returning the range for an object as well as the
* selection range
* @private
* @param {Element} el The element to get the range for.
* @return {Array.<TextRange>} Range of object and selection range in two
* element array.
*/
goog.dom.selection.getRangeIe_ = function(el) {
var doc = el.ownerDocument || el.document;
var selectionRange = doc.selection.createRange();
// el.createTextRange() doesn't work on textareas
var range;
if (el.type == 'textarea') {
range = doc.body.createTextRange();
range.moveToElementText(el);
} else {
range = el.createTextRange();
}
return [range, selectionRange];
};
/**
* Helper function for canonicalizing a position inside a textfield in IE.
* Deals with the issue that \r\n counts as 2 characters, but
* move('character', n) passes over both characters in one move.
* @private
* @param {Element} textfield The text element.
* @param {number} pos The position desired in that element.
* @return {number} The canonicalized position that will work properly with
* move('character', pos).
*/
goog.dom.selection.canonicalizePositionIe_ = function(textfield, pos) {
if (textfield.type == 'textarea') {
// We do this only for textarea because it is the only one which can
// have a \r\n (input cannot have this).
var value = textfield.value.substring(0, pos);
pos = goog.string.canonicalizeNewlines(value).length;
}
return pos;
};
/**
* Helper function to determine whether it's okay to use
* selectionStart/selectionEnd.
*
* @param {Element} el The element to check for.
* @return {boolean} Whether it's okay to use the selectionStart and
* selectionEnd properties on {@code el}.
* @private
*/
goog.dom.selection.useSelectionProperties_ = function(el) {
try {
return typeof el.selectionStart == 'number';
} catch (e) {
// Firefox throws an exception if you try to access selectionStart
// on an element with display: none.
return false;
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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 Utilities for manipulating a form and elements.
*
* @author arv@google.com (Erik Arvidsson)
* @author jonp@google.com (Jon Perlow)
* @author elsigh@google.com (Lindsey Simon)
*/
goog.provide('goog.dom.forms');
goog.require('goog.structs.Map');
/**
* Returns form data as a map of name to value arrays. This doesn't
* support file inputs.
* @param {HTMLFormElement} form The form.
* @return {!goog.structs.Map} A map of the form data as form name to arrays of
* values.
*/
goog.dom.forms.getFormDataMap = function(form) {
var map = new goog.structs.Map();
goog.dom.forms.getFormDataHelper_(form, map,
goog.dom.forms.addFormDataToMap_);
return map;
};
/**
* Returns the form data as an application/x-www-url-encoded string. This
* doesn't support file inputs.
* @param {HTMLFormElement} form The form.
* @return {string} An application/x-www-url-encoded string.
*/
goog.dom.forms.getFormDataString = function(form) {
var sb = [];
goog.dom.forms.getFormDataHelper_(form, sb,
goog.dom.forms.addFormDataToStringBuffer_);
return sb.join('&');
};
/**
* Returns the form data as a map or an application/x-www-url-encoded
* string. This doesn't support file inputs.
* @param {HTMLFormElement} form The form.
* @param {Object} result The object form data is being put in.
* @param {Function} fnAppend Function that takes {@code result}, an element
* name, and an element value, and adds the name/value pair to the result
* object.
* @private
*/
goog.dom.forms.getFormDataHelper_ = function(form, result, fnAppend) {
var els = form.elements;
for (var el, i = 0; el = els[i]; i++) {
if (// Make sure we don't include elements that are not part of the form.
// Some browsers include non-form elements. Check for 'form' property.
// See http://code.google.com/p/closure-library/issues/detail?id=227
// and
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#the-input-element
(el.form != form) ||
el.disabled ||
// HTMLFieldSetElement has a form property but no value.
el.tagName.toLowerCase() == 'fieldset') {
continue;
}
var name = el.name;
switch (el.type.toLowerCase()) {
case 'file':
// file inputs are not supported
case 'submit':
case 'reset':
case 'button':
// don't submit these
break;
case 'select-multiple':
var values = goog.dom.forms.getValue(el);
if (values != null) {
for (var value, j = 0; value = values[j]; j++) {
fnAppend(result, name, value);
}
}
break;
default:
var value = goog.dom.forms.getValue(el);
if (value != null) {
fnAppend(result, name, value);
}
}
}
// input[type=image] are not included in the elements collection
var inputs = form.getElementsByTagName('input');
for (var input, i = 0; input = inputs[i]; i++) {
if (input.form == form && input.type.toLowerCase() == 'image') {
name = input.name;
fnAppend(result, name, input.value);
fnAppend(result, name + '.x', '0');
fnAppend(result, name + '.y', '0');
}
}
};
/**
* Adds the name/value pair to the map.
* @param {goog.structs.Map} map The map to add to.
* @param {string} name The name.
* @param {string} value The value.
* @private
*/
goog.dom.forms.addFormDataToMap_ = function(map, name, value) {
var array = map.get(name);
if (!array) {
array = [];
map.set(name, array);
}
array.push(value);
};
/**
* Adds a name/value pair to an string buffer array in the form 'name=value'.
* @param {Array} sb The string buffer array for storing data.
* @param {string} name The name.
* @param {string} value The value.
* @private
*/
goog.dom.forms.addFormDataToStringBuffer_ = function(sb, name, value) {
sb.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
};
/**
* Whether the form has a file input.
* @param {HTMLFormElement} form The form.
* @return {boolean} Whether the form has a file input.
*/
goog.dom.forms.hasFileInput = function(form) {
var els = form.elements;
for (var el, i = 0; el = els[i]; i++) {
if (!el.disabled && el.type && el.type.toLowerCase() == 'file') {
return true;
}
}
return false;
};
/**
* Enables or disables either all elements in a form or a single form element.
* @param {Element} el The element, either a form or an element within a form.
* @param {boolean} disabled Whether the element should be disabled.
*/
goog.dom.forms.setDisabled = function(el, disabled) {
// disable all elements in a form
if (el.tagName == 'FORM') {
var els = el.elements;
for (var i = 0; el = els[i]; i++) {
goog.dom.forms.setDisabled(el, disabled);
}
} else {
// makes sure to blur buttons, multi-selects, and any elements which
// maintain keyboard/accessibility focus when disabled
if (disabled == true) {
el.blur();
}
el.disabled = disabled;
}
};
/**
* Focuses, and optionally selects the content of, a form element.
* @param {Element} el The form element.
*/
goog.dom.forms.focusAndSelect = function(el) {
el.focus();
if (el.select) {
el.select();
}
};
/**
* Whether a form element has a value.
* @param {Element} el The element.
* @return {boolean} Whether the form has a value.
*/
goog.dom.forms.hasValue = function(el) {
var value = goog.dom.forms.getValue(el);
return !!value;
};
/**
* Whether a named form field has a value.
* @param {HTMLFormElement} form The form element.
* @param {string} name Name of an input to the form.
* @return {boolean} Whether the form has a value.
*/
goog.dom.forms.hasValueByName = function(form, name) {
var value = goog.dom.forms.getValueByName(form, name);
return !!value;
};
/**
* Gets the current value of any element with a type.
* @param {Element} el The element.
* @return {string|Array.<string>|null} The current value of the element
* (or null).
*/
goog.dom.forms.getValue = function(el) {
var type = el.type;
if (!goog.isDef(type)) {
return null;
}
switch (type.toLowerCase()) {
case 'checkbox':
case 'radio':
return goog.dom.forms.getInputChecked_(el);
case 'select-one':
return goog.dom.forms.getSelectSingle_(el);
case 'select-multiple':
return goog.dom.forms.getSelectMultiple_(el);
default:
return goog.isDef(el.value) ? el.value : null;
}
};
/**
* Alias for goog.dom.form.element.getValue
* @type {Function}
* @deprecated Use {@link goog.dom.forms.getValue} instead.
*/
goog.dom.$F = goog.dom.forms.getValue;
/**
* Returns the value of the named form field. In the case of radio buttons,
* returns the value of the checked button with the given name.
*
* @param {HTMLFormElement} form The form element.
* @param {string} name Name of an input to the form.
*
* @return {Array.<string>|string|null} The value of the form element, or
* null if the form element does not exist or has no value.
*/
goog.dom.forms.getValueByName = function(form, name) {
var els = form.elements[name];
if (els.type) {
return goog.dom.forms.getValue(els);
} else {
for (var i = 0; i < els.length; i++) {
var val = goog.dom.forms.getValue(els[i]);
if (val) {
return val;
}
}
return null;
}
};
/**
* Gets the current value of a checkable input element.
* @param {Element} el The element.
* @return {?string} The value of the form element (or null).
* @private
*/
goog.dom.forms.getInputChecked_ = function(el) {
return el.checked ? el.value : null;
};
/**
* Gets the current value of a select-one element.
* @param {Element} el The element.
* @return {?string} The value of the form element (or null).
* @private
*/
goog.dom.forms.getSelectSingle_ = function(el) {
var selectedIndex = el.selectedIndex;
return selectedIndex >= 0 ? el.options[selectedIndex].value : null;
};
/**
* Gets the current value of a select-multiple element.
* @param {Element} el The element.
* @return {Array.<string>?} The value of the form element (or null).
* @private
*/
goog.dom.forms.getSelectMultiple_ = function(el) {
var values = [];
for (var option, i = 0; option = el.options[i]; i++) {
if (option.selected) {
values.push(option.value);
}
}
return values.length ? values : null;
};
/**
* Sets the current value of any element with a type.
* @param {Element} el The element.
* @param {*=} opt_value The value to give to the element, which will be coerced
* by the browser in the default case using toString. This value should be
* an array for setting the value of select multiple elements.
*/
goog.dom.forms.setValue = function(el, opt_value) {
var type = el.type;
if (goog.isDef(type)) {
switch (type.toLowerCase()) {
case 'checkbox':
case 'radio':
goog.dom.forms.setInputChecked_(el,
/** @type {string} */ (opt_value));
break;
case 'select-one':
goog.dom.forms.setSelectSingle_(el,
/** @type {string} */ (opt_value));
break;
case 'select-multiple':
goog.dom.forms.setSelectMultiple_(el,
/** @type {Array} */ (opt_value));
break;
default:
el.value = goog.isDefAndNotNull(opt_value) ? opt_value : '';
}
}
};
/**
* Sets a checkable input element's checked property.
* #TODO(user): This seems potentially unintuitive since it doesn't set
* the value property but my hunch is that the primary use case is to check a
* checkbox, not to reset its value property.
* @param {Element} el The element.
* @param {string|boolean=} opt_value The value, sets the element checked if
* val is set.
* @private
*/
goog.dom.forms.setInputChecked_ = function(el, opt_value) {
el.checked = opt_value ? 'checked' : null;
};
/**
* Sets the value of a select-one element.
* @param {Element} el The element.
* @param {string=} opt_value The value of the selected option element.
* @private
*/
goog.dom.forms.setSelectSingle_ = function(el, opt_value) {
// unset any prior selections
el.selectedIndex = -1;
if (goog.isString(opt_value)) {
for (var option, i = 0; option = el.options[i]; i++) {
if (option.value == opt_value) {
option.selected = true;
break;
}
}
}
};
/**
* Sets the value of a select-multiple element.
* @param {Element} el The element.
* @param {Array.<string>|string=} opt_value The value of the selected option
* element(s).
* @private
*/
goog.dom.forms.setSelectMultiple_ = function(el, opt_value) {
// reset string opt_values as an array
if (goog.isString(opt_value)) {
opt_value = [opt_value];
}
for (var option, i = 0; option = el.options[i]; i++) {
// we have to reset the other options to false for select-multiple
option.selected = false;
if (opt_value) {
for (var value, j = 0; value = opt_value[j]; j++) {
if (option.value == value) {
option.selected = true;
}
}
}
}
};
| JavaScript |
// Copyright 2005 The Closure Library Authors. 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 class that can be used to listen to font size changes.
*/
goog.provide('goog.dom.FontSizeMonitor');
goog.provide('goog.dom.FontSizeMonitor.EventType');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.userAgent');
// TODO(arv): Move this to goog.events instead.
/**
* This class can be used to monitor changes in font size. Instances will
* dispatch a {@code goog.dom.FontSizeMonitor.EventType.CHANGE} event.
* Example usage:
* <pre>
* var fms = new goog.dom.FontSizeMonitor();
* goog.events.listen(fms, goog.dom.FontSizeMonitor.EventType.CHANGE,
* function(e) {
* alert('Font size was changed');
* });
* </pre>
* @param {goog.dom.DomHelper=} opt_domHelper DOM helper object that is used to
* determine where to insert the DOM nodes used to determine when the font
* size changes.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.dom.FontSizeMonitor = function(opt_domHelper) {
goog.events.EventTarget.call(this);
var dom = opt_domHelper || goog.dom.getDomHelper();
/**
* Offscreen iframe which we use to detect resize events.
* @type {Element}
* @private
*/
this.sizeElement_ = dom.createDom(
// The size of the iframe is expressed in em, which are font size relative
// which will cause the iframe to be resized when the font size changes.
// The actual values are not relevant as long as we can ensure that the
// iframe has a non zero size and is completely off screen.
goog.userAgent.IE ? 'div' : 'iframe', {
'style': 'position:absolute;width:9em;height:9em;top:-99em',
'tabIndex': -1,
'aria-hidden': 'true'
});
var p = dom.getDocument().body;
p.insertBefore(this.sizeElement_, p.firstChild);
/**
* The object that we listen to resize events on.
* @type {Element|Window}
* @private
*/
var resizeTarget = this.resizeTarget_ =
goog.userAgent.IE ? this.sizeElement_ :
goog.dom.getFrameContentWindow(
/** @type {HTMLIFrameElement} */ (this.sizeElement_));
// We need to open and close the document to get Firefox 2 to work. We must
// not do this for IE in case we are using HTTPS since accessing the document
// on an about:blank iframe in IE using HTTPS raises a Permission Denied
// error.
if (goog.userAgent.GECKO) {
var doc = resizeTarget.document;
doc.open();
doc.close();
}
// Listen to resize event on the window inside the iframe.
goog.events.listen(resizeTarget, goog.events.EventType.RESIZE,
this.handleResize_, false, this);
/**
* Last measured width of the iframe element.
* @type {number}
* @private
*/
this.lastWidth_ = this.sizeElement_.offsetWidth;
};
goog.inherits(goog.dom.FontSizeMonitor, goog.events.EventTarget);
/**
* The event types that the FontSizeMonitor fires.
* @enum {string}
*/
goog.dom.FontSizeMonitor.EventType = {
// TODO(arv): Change value to 'change' after updating the callers.
CHANGE: 'fontsizechange'
};
/**
* Constant for the change event.
* @type {string}
* @deprecated Use {@code goog.dom.FontSizeMonitor.EventType.CHANGE} instead.
*/
goog.dom.FontSizeMonitor.CHANGE_EVENT =
goog.dom.FontSizeMonitor.EventType.CHANGE;
/** @override */
goog.dom.FontSizeMonitor.prototype.disposeInternal = function() {
goog.dom.FontSizeMonitor.superClass_.disposeInternal.call(this);
goog.events.unlisten(this.resizeTarget_, goog.events.EventType.RESIZE,
this.handleResize_, false, this);
this.resizeTarget_ = null;
// Firefox 2 crashes if the iframe is removed during the unload phase.
if (!goog.userAgent.GECKO || goog.userAgent.isVersion('1.9')) {
goog.dom.removeNode(this.sizeElement_);
}
delete this.sizeElement_;
};
/**
* Handles the onresize event of the iframe and dispatches a change event in
* case its size really changed.
* @param {goog.events.BrowserEvent} e The event object.
* @private
*/
goog.dom.FontSizeMonitor.prototype.handleResize_ = function(e) {
// Only dispatch the event if the size really changed. Some newer browsers do
// not really change the font-size, instead they zoom the whole page. This
// does trigger window resize events on the iframe but the logical pixel size
// remains the same (the device pixel size changes but that is irrelevant).
var currentWidth = this.sizeElement_.offsetWidth;
if (this.lastWidth_ != currentWidth) {
this.lastWidth_ = currentWidth;
this.dispatchEvent(goog.dom.FontSizeMonitor.EventType.CHANGE);
}
};
| JavaScript |
// Copyright 2007 The Closure Library Authors. 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 Utility class that monitors viewport size changes.
*
* @author attila@google.com (Attila Bodis)
* @see ../demos/viewportsizemonitor.html
*/
goog.provide('goog.dom.ViewportSizeMonitor');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
goog.require('goog.math.Size');
/**
* This class can be used to monitor changes in the viewport size. Instances
* dispatch a {@link goog.events.EventType.RESIZE} event when the viewport size
* changes. Handlers can call {@link goog.dom.ViewportSizeMonitor#getSize} to
* get the new viewport size.
*
* Use this class if you want to execute resize/reflow logic each time the
* user resizes the browser window. This class is guaranteed to only dispatch
* {@code RESIZE} events when the pixel dimensions of the viewport change.
* (Internet Explorer fires resize events if any element on the page is resized,
* even if the viewport dimensions are unchanged, which can lead to infinite
* resize loops.)
*
* Example usage:
* <pre>
* var vsm = new goog.dom.ViewportSizeMonitor();
* goog.events.listen(vsm, goog.events.EventType.RESIZE, function(e) {
* alert('Viewport size changed to ' + vsm.getSize());
* });
* </pre>
*
* Manually verified on IE6, IE7, FF2, Opera 11, Safari 4 and Chrome.
*
* @param {Window=} opt_window The window to monitor; defaults to the window in
* which this code is executing.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.dom.ViewportSizeMonitor = function(opt_window) {
goog.events.EventTarget.call(this);
// Default the window to the current window if unspecified.
this.window_ = opt_window || window;
// Listen for window resize events.
this.listenerKey_ = goog.events.listen(this.window_,
goog.events.EventType.RESIZE, this.handleResize_, false, this);
// Set the initial size.
this.size_ = goog.dom.getViewportSize(this.window_);
};
goog.inherits(goog.dom.ViewportSizeMonitor, goog.events.EventTarget);
/**
* Returns a viewport size monitor for the given window. A new one is created
* if it doesn't exist already. This prevents the unnecessary creation of
* multiple spooling monitors for a window.
* @param {Window=} opt_window The window to monitor; defaults to the window in
* which this code is executing.
* @return {goog.dom.ViewportSizeMonitor} Monitor for the given window.
*/
goog.dom.ViewportSizeMonitor.getInstanceForWindow = function(opt_window) {
var currentWindow = opt_window || window;
var uid = goog.getUid(currentWindow);
return goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid] =
goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid] ||
new goog.dom.ViewportSizeMonitor(currentWindow);
};
/**
* Removes and disposes a viewport size monitor for the given window if one
* exists.
* @param {Window=} opt_window The window whose monitor should be removed;
* defaults to the window in which this code is executing.
*/
goog.dom.ViewportSizeMonitor.removeInstanceForWindow = function(opt_window) {
var uid = goog.getUid(opt_window || window);
goog.dispose(goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid]);
delete goog.dom.ViewportSizeMonitor.windowInstanceMap_[uid];
};
/**
* Map of window hash code to viewport size monitor for that window, if
* created.
* @type {Object.<number,goog.dom.ViewportSizeMonitor>}
* @private
*/
goog.dom.ViewportSizeMonitor.windowInstanceMap_ = {};
/**
* Event listener key for window the window resize handler, as returned by
* {@link goog.events.listen}.
* @type {goog.events.Key}
* @private
*/
goog.dom.ViewportSizeMonitor.prototype.listenerKey_ = null;
/**
* The window to monitor. Defaults to the window in which the code is running.
* @type {Window}
* @private
*/
goog.dom.ViewportSizeMonitor.prototype.window_ = null;
/**
* The most recently recorded size of the viewport, in pixels.
* @type {goog.math.Size?}
* @private
*/
goog.dom.ViewportSizeMonitor.prototype.size_ = null;
/**
* Returns the most recently recorded size of the viewport, in pixels. May
* return null if no window resize event has been handled yet.
* @return {goog.math.Size} The viewport dimensions, in pixels.
*/
goog.dom.ViewportSizeMonitor.prototype.getSize = function() {
// Return a clone instead of the original to preserve encapsulation.
return this.size_ ? this.size_.clone() : null;
};
/** @override */
goog.dom.ViewportSizeMonitor.prototype.disposeInternal = function() {
goog.dom.ViewportSizeMonitor.superClass_.disposeInternal.call(this);
if (this.listenerKey_) {
goog.events.unlistenByKey(this.listenerKey_);
this.listenerKey_ = null;
}
this.window_ = null;
this.size_ = null;
};
/**
* Handles window resize events by measuring the dimensions of the
* viewport and dispatching a {@link goog.events.EventType.RESIZE} event if the
* current dimensions are different from the previous ones.
* @param {goog.events.Event} event The window resize event to handle.
* @private
*/
goog.dom.ViewportSizeMonitor.prototype.handleResize_ = function(event) {
var size = goog.dom.getViewportSize(this.window_);
if (!goog.math.Size.equals(size, this.size_)) {
this.size_ = size;
this.dispatchEvent(goog.events.EventType.RESIZE);
}
};
| JavaScript |
// Copyright 2006 The Closure Library Authors. 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 Utilities for manipulating the browser's Document Object Model
* Inspiration taken *heavily* from mochikit (http://mochikit.com/).
*
* You can use {@link goog.dom.DomHelper} to create new dom helpers that refer
* to a different document object. This is useful if you are working with
* frames or multiple windows.
*
*/
// TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem
// is that getTextContent should mimic the DOM3 textContent. We should add a
// getInnerText (or getText) which tries to return the visible text, innerText.
goog.provide('goog.dom');
goog.provide('goog.dom.DomHelper');
goog.provide('goog.dom.NodeType');
goog.require('goog.array');
goog.require('goog.dom.BrowserFeature');
goog.require('goog.dom.TagName');
goog.require('goog.dom.classes');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.userAgent');
/**
* @define {boolean} Whether we know at compile time that the browser is in
* quirks mode.
*/
goog.dom.ASSUME_QUIRKS_MODE = false;
/**
* @define {boolean} Whether we know at compile time that the browser is in
* standards compliance mode.
*/
goog.dom.ASSUME_STANDARDS_MODE = false;
/**
* Whether we know the compatibility mode at compile time.
* @type {boolean}
* @private
*/
goog.dom.COMPAT_MODE_KNOWN_ =
goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;
/**
* Enumeration for DOM node types (for reference)
* @enum {number}
*/
goog.dom.NodeType = {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3,
CDATA_SECTION: 4,
ENTITY_REFERENCE: 5,
ENTITY: 6,
PROCESSING_INSTRUCTION: 7,
COMMENT: 8,
DOCUMENT: 9,
DOCUMENT_TYPE: 10,
DOCUMENT_FRAGMENT: 11,
NOTATION: 12
};
/**
* Gets the DomHelper object for the document where the element resides.
* @param {(Node|Window)=} opt_element If present, gets the DomHelper for this
* element.
* @return {!goog.dom.DomHelper} The DomHelper.
*/
goog.dom.getDomHelper = function(opt_element) {
return opt_element ?
new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :
(goog.dom.defaultDomHelper_ ||
(goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));
};
/**
* Cached default DOM helper.
* @type {goog.dom.DomHelper}
* @private
*/
goog.dom.defaultDomHelper_;
/**
* Gets the document object being used by the dom library.
* @return {!Document} Document object.
*/
goog.dom.getDocument = function() {
return document;
};
/**
* Alias for getElementById. If a DOM node is passed in then we just return
* that.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
*/
goog.dom.getElement = function(element) {
return goog.isString(element) ?
document.getElementById(element) : element;
};
/**
* Alias for getElement.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
* @deprecated Use {@link goog.dom.getElement} instead.
*/
goog.dom.$ = goog.dom.getElement;
/**
* Looks up elements by both tag and class name, using browser native functions
* ({@code querySelectorAll}, {@code getElementsByTagName} or
* {@code getElementsByClassName}) where possible. This function
* is a useful, if limited, way of collecting a list of DOM elements
* with certain characteristics. {@code goog.dom.query} offers a
* more powerful and general solution which allows matching on CSS3
* selector expressions, but at increased cost in code size. If all you
* need is particular tags belonging to a single class, this function
* is fast and sleek.
*
* @see {goog.dom.query}
*
* @param {?string=} opt_tag Element tag name.
* @param {?string=} opt_class Optional class name.
* @param {(Document|Element)=} opt_el Optional element to look in.
* @return { {length: number} } Array-like list of elements (only a length
* property and numerical indices are guaranteed to exist).
*/
goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {
return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class,
opt_el);
};
/**
* Returns an array of all the elements with the provided className.
* @see {goog.dom.query}
* @param {string} className the name of the class to look for.
* @param {(Document|Element)=} opt_el Optional element to look in.
* @return { {length: number} } The items found with the class name provided.
*/
goog.dom.getElementsByClass = function(className, opt_el) {
var parent = opt_el || document;
if (goog.dom.canUseQuerySelector_(parent)) {
return parent.querySelectorAll('.' + className);
} else if (parent.getElementsByClassName) {
return parent.getElementsByClassName(className);
}
return goog.dom.getElementsByTagNameAndClass_(
document, '*', className, opt_el);
};
/**
* Returns the first element with the provided className.
* @see {goog.dom.query}
* @param {string} className the name of the class to look for.
* @param {Element|Document=} opt_el Optional element to look in.
* @return {Element} The first item with the class name provided.
*/
goog.dom.getElementByClass = function(className, opt_el) {
var parent = opt_el || document;
var retVal = null;
if (goog.dom.canUseQuerySelector_(parent)) {
retVal = parent.querySelector('.' + className);
} else {
retVal = goog.dom.getElementsByClass(className, opt_el)[0];
}
return retVal || null;
};
/**
* Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and
* fast W3C Selectors API.
* @param {!(Element|Document)} parent The parent document object.
* @return {boolean} whether or not we can use parent.querySelector* APIs.
* @private
*/
goog.dom.canUseQuerySelector_ = function(parent) {
return !!(parent.querySelectorAll && parent.querySelector);
};
/**
* Helper for {@code getElementsByTagNameAndClass}.
* @param {!Document} doc The document to get the elements in.
* @param {?string=} opt_tag Element tag name.
* @param {?string=} opt_class Optional class name.
* @param {(Document|Element)=} opt_el Optional element to look in.
* @return { {length: number} } Array-like list of elements (only a length
* property and numerical indices are guaranteed to exist).
* @private
*/
goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class,
opt_el) {
var parent = opt_el || doc;
var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : '';
if (goog.dom.canUseQuerySelector_(parent) &&
(tagName || opt_class)) {
var query = tagName + (opt_class ? '.' + opt_class : '');
return parent.querySelectorAll(query);
}
// Use the native getElementsByClassName if available, under the assumption
// that even when the tag name is specified, there will be fewer elements to
// filter through when going by class than by tag name
if (opt_class && parent.getElementsByClassName) {
var els = parent.getElementsByClassName(opt_class);
if (tagName) {
var arrayLike = {};
var len = 0;
// Filter for specific tags if requested.
for (var i = 0, el; el = els[i]; i++) {
if (tagName == el.nodeName) {
arrayLike[len++] = el;
}
}
arrayLike.length = len;
return arrayLike;
} else {
return els;
}
}
var els = parent.getElementsByTagName(tagName || '*');
if (opt_class) {
var arrayLike = {};
var len = 0;
for (var i = 0, el; el = els[i]; i++) {
var className = el.className;
// Check if className has a split function since SVG className does not.
if (typeof className.split == 'function' &&
goog.array.contains(className.split(/\s+/), opt_class)) {
arrayLike[len++] = el;
}
}
arrayLike.length = len;
return arrayLike;
} else {
return els;
}
};
/**
* Alias for {@code getElementsByTagNameAndClass}.
* @param {?string=} opt_tag Element tag name.
* @param {?string=} opt_class Optional class name.
* @param {Element=} opt_el Optional element to look in.
* @return { {length: number} } Array-like list of elements (only a length
* property and numerical indices are guaranteed to exist).
* @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.
*/
goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;
/**
* Sets multiple properties on a node.
* @param {Element} element DOM node to set properties on.
* @param {Object} properties Hash of property:value pairs.
*/
goog.dom.setProperties = function(element, properties) {
goog.object.forEach(properties, function(val, key) {
if (key == 'style') {
element.style.cssText = val;
} else if (key == 'class') {
element.className = val;
} else if (key == 'for') {
element.htmlFor = val;
} else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) {
element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);
} else if (goog.string.startsWith(key, 'aria-') ||
goog.string.startsWith(key, 'data-')) {
element.setAttribute(key, val);
} else {
element[key] = val;
}
});
};
/**
* Map of attributes that should be set using
* element.setAttribute(key, val) instead of element[key] = val. Used
* by goog.dom.setProperties.
*
* @type {Object}
* @private
*/
goog.dom.DIRECT_ATTRIBUTE_MAP_ = {
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'frameborder': 'frameBorder',
'height': 'height',
'maxlength': 'maxLength',
'role': 'role',
'rowspan': 'rowSpan',
'type': 'type',
'usemap': 'useMap',
'valign': 'vAlign',
'width': 'width'
};
/**
* Gets the dimensions of the viewport.
*
* Gecko Standards mode:
* docEl.clientWidth Width of viewport excluding scrollbar.
* win.innerWidth Width of viewport including scrollbar.
* body.clientWidth Width of body element.
*
* docEl.clientHeight Height of viewport excluding scrollbar.
* win.innerHeight Height of viewport including scrollbar.
* body.clientHeight Height of document.
*
* Gecko Backwards compatible mode:
* docEl.clientWidth Width of viewport excluding scrollbar.
* win.innerWidth Width of viewport including scrollbar.
* body.clientWidth Width of viewport excluding scrollbar.
*
* docEl.clientHeight Height of document.
* win.innerHeight Height of viewport including scrollbar.
* body.clientHeight Height of viewport excluding scrollbar.
*
* IE6/7 Standards mode:
* docEl.clientWidth Width of viewport excluding scrollbar.
* win.innerWidth Undefined.
* body.clientWidth Width of body element.
*
* docEl.clientHeight Height of viewport excluding scrollbar.
* win.innerHeight Undefined.
* body.clientHeight Height of document element.
*
* IE5 + IE6/7 Backwards compatible mode:
* docEl.clientWidth 0.
* win.innerWidth Undefined.
* body.clientWidth Width of viewport excluding scrollbar.
*
* docEl.clientHeight 0.
* win.innerHeight Undefined.
* body.clientHeight Height of viewport excluding scrollbar.
*
* Opera 9 Standards and backwards compatible mode:
* docEl.clientWidth Width of viewport excluding scrollbar.
* win.innerWidth Width of viewport including scrollbar.
* body.clientWidth Width of viewport excluding scrollbar.
*
* docEl.clientHeight Height of document.
* win.innerHeight Height of viewport including scrollbar.
* body.clientHeight Height of viewport excluding scrollbar.
*
* WebKit:
* Safari 2
* docEl.clientHeight Same as scrollHeight.
* docEl.clientWidth Same as innerWidth.
* win.innerWidth Width of viewport excluding scrollbar.
* win.innerHeight Height of the viewport including scrollbar.
* frame.innerHeight Height of the viewport exluding scrollbar.
*
* Safari 3 (tested in 522)
*
* docEl.clientWidth Width of viewport excluding scrollbar.
* docEl.clientHeight Height of viewport excluding scrollbar in strict mode.
* body.clientHeight Height of viewport excluding scrollbar in quirks mode.
*
* @param {Window=} opt_window Optional window element to test.
* @return {!goog.math.Size} Object with values 'width' and 'height'.
*/
goog.dom.getViewportSize = function(opt_window) {
// TODO(arv): This should not take an argument
return goog.dom.getViewportSize_(opt_window || window);
};
/**
* Helper for {@code getViewportSize}.
* @param {Window} win The window to get the view port size for.
* @return {!goog.math.Size} Object with values 'width' and 'height'.
* @private
*/
goog.dom.getViewportSize_ = function(win) {
var doc = win.document;
var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;
return new goog.math.Size(el.clientWidth, el.clientHeight);
};
/**
* Calculates the height of the document.
*
* @return {number} The height of the current document.
*/
goog.dom.getDocumentHeight = function() {
return goog.dom.getDocumentHeight_(window);
};
/**
* Calculates the height of the document of the given window.
*
* Function code copied from the opensocial gadget api:
* gadgets.window.adjustHeight(opt_height)
*
* @private
* @param {Window} win The window whose document height to retrieve.
* @return {number} The height of the document of the given window.
*/
goog.dom.getDocumentHeight_ = function(win) {
// NOTE(eae): This method will return the window size rather than the document
// size in webkit quirks mode.
var doc = win.document;
var height = 0;
if (doc) {
// Calculating inner content height is hard and different between
// browsers rendering in Strict vs. Quirks mode. We use a combination of
// three properties within document.body and document.documentElement:
// - scrollHeight
// - offsetHeight
// - clientHeight
// These values differ significantly between browsers and rendering modes.
// But there are patterns. It just takes a lot of time and persistence
// to figure out.
// Get the height of the viewport
var vh = goog.dom.getViewportSize_(win).height;
var body = doc.body;
var docEl = doc.documentElement;
if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {
// In Strict mode:
// The inner content height is contained in either:
// document.documentElement.scrollHeight
// document.documentElement.offsetHeight
// Based on studying the values output by different browsers,
// use the value that's NOT equal to the viewport height found above.
height = docEl.scrollHeight != vh ?
docEl.scrollHeight : docEl.offsetHeight;
} else {
// In Quirks mode:
// documentElement.clientHeight is equal to documentElement.offsetHeight
// except in IE. In most browsers, document.documentElement can be used
// to calculate the inner content height.
// However, in other browsers (e.g. IE), document.body must be used
// instead. How do we know which one to use?
// If document.documentElement.clientHeight does NOT equal
// document.documentElement.offsetHeight, then use document.body.
var sh = docEl.scrollHeight;
var oh = docEl.offsetHeight;
if (docEl.clientHeight != oh) {
sh = body.scrollHeight;
oh = body.offsetHeight;
}
// Detect whether the inner content height is bigger or smaller
// than the bounding box (viewport). If bigger, take the larger
// value. If smaller, take the smaller value.
if (sh > vh) {
// Content is larger
height = sh > oh ? sh : oh;
} else {
// Content is smaller
height = sh < oh ? sh : oh;
}
}
}
return height;
};
/**
* Gets the page scroll distance as a coordinate object.
*
* @param {Window=} opt_window Optional window element to test.
* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
* @deprecated Use {@link goog.dom.getDocumentScroll} instead.
*/
goog.dom.getPageScroll = function(opt_window) {
var win = opt_window || goog.global || window;
return goog.dom.getDomHelper(win.document).getDocumentScroll();
};
/**
* Gets the document scroll distance as a coordinate object.
*
* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
*/
goog.dom.getDocumentScroll = function() {
return goog.dom.getDocumentScroll_(document);
};
/**
* Helper for {@code getDocumentScroll}.
*
* @param {!Document} doc The document to get the scroll for.
* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
* @private
*/
goog.dom.getDocumentScroll_ = function(doc) {
var el = goog.dom.getDocumentScrollElement_(doc);
var win = goog.dom.getWindow_(doc);
if (goog.userAgent.IE && goog.userAgent.isVersion('10') &&
win.pageYOffset != el.scrollTop) {
// The keyboard on IE10 touch devices shifts the page using the pageYOffset
// without modifying scrollTop. For this case, we want the body scroll
// offsets.
return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);
}
return new goog.math.Coordinate(win.pageXOffset || el.scrollLeft,
win.pageYOffset || el.scrollTop);
};
/**
* Gets the document scroll element.
* @return {Element} Scrolling element.
*/
goog.dom.getDocumentScrollElement = function() {
return goog.dom.getDocumentScrollElement_(document);
};
/**
* Helper for {@code getDocumentScrollElement}.
* @param {!Document} doc The document to get the scroll element for.
* @return {Element} Scrolling element.
* @private
*/
goog.dom.getDocumentScrollElement_ = function(doc) {
// Safari (2 and 3) needs body.scrollLeft in both quirks mode and strict mode.
return !goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc) ?
doc.documentElement : doc.body;
};
/**
* Gets the window object associated with the given document.
*
* @param {Document=} opt_doc Document object to get window for.
* @return {!Window} The window associated with the given document.
*/
goog.dom.getWindow = function(opt_doc) {
// TODO(arv): This should not take an argument.
return opt_doc ? goog.dom.getWindow_(opt_doc) : window;
};
/**
* Helper for {@code getWindow}.
*
* @param {!Document} doc Document object to get window for.
* @return {!Window} The window associated with the given document.
* @private
*/
goog.dom.getWindow_ = function(doc) {
return doc.parentWindow || doc.defaultView;
};
/**
* Returns a dom node with a set of attributes. This function accepts varargs
* for subsequent nodes to be added. Subsequent nodes will be added to the
* first node as childNodes.
*
* So:
* <code>createDom('div', null, createDom('p'), createDom('p'));</code>
* would return a div with two child paragraphs
*
* @param {string} tagName Tag to create.
* @param {(Object|Array.<string>|string)=} opt_attributes If object, then a map
* of name-value pairs for attributes. If a string, then this is the
* className of the new element. If an array, the elements will be joined
* together as the className of the new element.
* @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
* strings for text nodes. If one of the var_args is an array or NodeList,i
* its elements will be added as childNodes instead.
* @return {!Element} Reference to a DOM node.
*/
goog.dom.createDom = function(tagName, opt_attributes, var_args) {
return goog.dom.createDom_(document, arguments);
};
/**
* Helper for {@code createDom}.
* @param {!Document} doc The document to create the DOM in.
* @param {!Arguments} args Argument object passed from the callers. See
* {@code goog.dom.createDom} for details.
* @return {!Element} Reference to a DOM node.
* @private
*/
goog.dom.createDom_ = function(doc, args) {
var tagName = args[0];
var attributes = args[1];
// Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/
// dhtml/reference/properties/name_2.asp
// Also does not allow setting of 'type' attribute on 'input' or 'button'.
if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&
(attributes.name || attributes.type)) {
var tagNameArr = ['<', tagName];
if (attributes.name) {
tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name),
'"');
}
if (attributes.type) {
tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type),
'"');
// Clone attributes map to remove 'type' without mutating the input.
var clone = {};
goog.object.extend(clone, attributes);
// JSCompiler can't see how goog.object.extend added this property,
// because it was essentially added by reflection.
// So it needs to be quoted.
delete clone['type'];
attributes = clone;
}
tagNameArr.push('>');
tagName = tagNameArr.join('');
}
var element = doc.createElement(tagName);
if (attributes) {
if (goog.isString(attributes)) {
element.className = attributes;
} else if (goog.isArray(attributes)) {
goog.dom.classes.add.apply(null, [element].concat(attributes));
} else {
goog.dom.setProperties(element, attributes);
}
}
if (args.length > 2) {
goog.dom.append_(doc, element, args, 2);
}
return element;
};
/**
* Appends a node with text or other nodes.
* @param {!Document} doc The document to create new nodes in.
* @param {!Node} parent The node to append nodes to.
* @param {!Arguments} args The values to add. See {@code goog.dom.append}.
* @param {number} startIndex The index of the array to start from.
* @private
*/
goog.dom.append_ = function(doc, parent, args, startIndex) {
function childHandler(child) {
// TODO(user): More coercion, ala MochiKit?
if (child) {
parent.appendChild(goog.isString(child) ?
doc.createTextNode(child) : child);
}
}
for (var i = startIndex; i < args.length; i++) {
var arg = args[i];
// TODO(attila): Fix isArrayLike to return false for a text node.
if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {
// If the argument is a node list, not a real array, use a clone,
// because forEach can't be used to mutate a NodeList.
goog.array.forEach(goog.dom.isNodeList(arg) ?
goog.array.toArray(arg) : arg,
childHandler);
} else {
childHandler(arg);
}
}
};
/**
* Alias for {@code createDom}.
* @param {string} tagName Tag to create.
* @param {(string|Object)=} opt_attributes If object, then a map of name-value
* pairs for attributes. If a string, then this is the className of the new
* element.
* @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
* strings for text nodes. If one of the var_args is an array, its
* children will be added as childNodes instead.
* @return {!Element} Reference to a DOM node.
* @deprecated Use {@link goog.dom.createDom} instead.
*/
goog.dom.$dom = goog.dom.createDom;
/**
* Creates a new element.
* @param {string} name Tag name.
* @return {!Element} The new element.
*/
goog.dom.createElement = function(name) {
return document.createElement(name);
};
/**
* Creates a new text node.
* @param {number|string} content Content.
* @return {!Text} The new text node.
*/
goog.dom.createTextNode = function(content) {
return document.createTextNode(String(content));
};
/**
* Create a table.
* @param {number} rows The number of rows in the table. Must be >= 1.
* @param {number} columns The number of columns in the table. Must be >= 1.
* @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps.
* @return {!Element} The created table.
*/
goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {
return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);
};
/**
* Create a table.
* @param {!Document} doc Document object to use to create the table.
* @param {number} rows The number of rows in the table. Must be >= 1.
* @param {number} columns The number of columns in the table. Must be >= 1.
* @param {boolean} fillWithNbsp If true, fills table entries with nsbps.
* @return {!Element} The created table.
* @private
*/
goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {
var rowHtml = ['<tr>'];
for (var i = 0; i < columns; i++) {
rowHtml.push(fillWithNbsp ? '<td> </td>' : '<td></td>');
}
rowHtml.push('</tr>');
rowHtml = rowHtml.join('');
var totalHtml = ['<table>'];
for (i = 0; i < rows; i++) {
totalHtml.push(rowHtml);
}
totalHtml.push('</table>');
var elem = doc.createElement(goog.dom.TagName.DIV);
elem.innerHTML = totalHtml.join('');
return /** @type {!Element} */ (elem.removeChild(elem.firstChild));
};
/**
* Converts an HTML string into a document fragment. The string must be
* sanitized in order to avoid cross-site scripting. For example
* {@code goog.dom.htmlToDocumentFragment('<img src=x onerror=alert(0)>')}
* triggers an alert in all browsers, even if the returned document fragment
* is thrown away immediately.
*
* @param {string} htmlString The HTML string to convert.
* @return {!Node} The resulting document fragment.
*/
goog.dom.htmlToDocumentFragment = function(htmlString) {
return goog.dom.htmlToDocumentFragment_(document, htmlString);
};
/**
* Helper for {@code htmlToDocumentFragment}.
*
* @param {!Document} doc The document.
* @param {string} htmlString The HTML string to convert.
* @return {!Node} The resulting document fragment.
* @private
*/
goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) {
var tempDiv = doc.createElement('div');
if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
tempDiv.innerHTML = '<br>' + htmlString;
tempDiv.removeChild(tempDiv.firstChild);
} else {
tempDiv.innerHTML = htmlString;
}
if (tempDiv.childNodes.length == 1) {
return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild));
} else {
var fragment = doc.createDocumentFragment();
while (tempDiv.firstChild) {
fragment.appendChild(tempDiv.firstChild);
}
return fragment;
}
};
/**
* Returns the compatMode of the document.
* @return {string} The result is either CSS1Compat or BackCompat.
* @deprecated use goog.dom.isCss1CompatMode instead.
*/
goog.dom.getCompatMode = function() {
return goog.dom.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat';
};
/**
* Returns true if the browser is in "CSS1-compatible" (standards-compliant)
* mode, false otherwise.
* @return {boolean} True if in CSS1-compatible mode.
*/
goog.dom.isCss1CompatMode = function() {
return goog.dom.isCss1CompatMode_(document);
};
/**
* Returns true if the browser is in "CSS1-compatible" (standards-compliant)
* mode, false otherwise.
* @param {Document} doc The document to check.
* @return {boolean} True if in CSS1-compatible mode.
* @private
*/
goog.dom.isCss1CompatMode_ = function(doc) {
if (goog.dom.COMPAT_MODE_KNOWN_) {
return goog.dom.ASSUME_STANDARDS_MODE;
}
return doc.compatMode == 'CSS1Compat';
};
/**
* Determines if the given node can contain children, intended to be used for
* HTML generation.
*
* IE natively supports node.canHaveChildren but has inconsistent behavior.
* Prior to IE8 the base tag allows children and in IE9 all nodes return true
* for canHaveChildren.
*
* In practice all non-IE browsers allow you to add children to any node, but
* the behavior is inconsistent:
*
* <pre>
* var a = document.createElement('br');
* a.appendChild(document.createTextNode('foo'));
* a.appendChild(document.createTextNode('bar'));
* console.log(a.childNodes.length); // 2
* console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"
* </pre>
*
* For more information, see:
* http://dev.w3.org/html5/markup/syntax.html#syntax-elements
*
* TODO(user): Rename shouldAllowChildren() ?
*
* @param {Node} node The node to check.
* @return {boolean} Whether the node can contain children.
*/
goog.dom.canHaveChildren = function(node) {
if (node.nodeType != goog.dom.NodeType.ELEMENT) {
return false;
}
switch (node.tagName) {
case goog.dom.TagName.APPLET:
case goog.dom.TagName.AREA:
case goog.dom.TagName.BASE:
case goog.dom.TagName.BR:
case goog.dom.TagName.COL:
case goog.dom.TagName.COMMAND:
case goog.dom.TagName.EMBED:
case goog.dom.TagName.FRAME:
case goog.dom.TagName.HR:
case goog.dom.TagName.IMG:
case goog.dom.TagName.INPUT:
case goog.dom.TagName.IFRAME:
case goog.dom.TagName.ISINDEX:
case goog.dom.TagName.KEYGEN:
case goog.dom.TagName.LINK:
case goog.dom.TagName.NOFRAMES:
case goog.dom.TagName.NOSCRIPT:
case goog.dom.TagName.META:
case goog.dom.TagName.OBJECT:
case goog.dom.TagName.PARAM:
case goog.dom.TagName.SCRIPT:
case goog.dom.TagName.SOURCE:
case goog.dom.TagName.STYLE:
case goog.dom.TagName.TRACK:
case goog.dom.TagName.WBR:
return false;
}
return true;
};
/**
* Appends a child to a node.
* @param {Node} parent Parent.
* @param {Node} child Child.
*/
goog.dom.appendChild = function(parent, child) {
parent.appendChild(child);
};
/**
* Appends a node with text or other nodes.
* @param {!Node} parent The node to append nodes to.
* @param {...goog.dom.Appendable} var_args The things to append to the node.
* If this is a Node it is appended as is.
* If this is a string then a text node is appended.
* If this is an array like object then fields 0 to length - 1 are appended.
*/
goog.dom.append = function(parent, var_args) {
goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);
};
/**
* Removes all the child nodes on a DOM node.
* @param {Node} node Node to remove children from.
*/
goog.dom.removeChildren = function(node) {
// Note: Iterations over live collections can be slow, this is the fastest
// we could find. The double parenthesis are used to prevent JsCompiler and
// strict warnings.
var child;
while ((child = node.firstChild)) {
node.removeChild(child);
}
};
/**
* Inserts a new node before an existing reference node (i.e. as the previous
* sibling). If the reference node has no parent, then does nothing.
* @param {Node} newNode Node to insert.
* @param {Node} refNode Reference node to insert before.
*/
goog.dom.insertSiblingBefore = function(newNode, refNode) {
if (refNode.parentNode) {
refNode.parentNode.insertBefore(newNode, refNode);
}
};
/**
* Inserts a new node after an existing reference node (i.e. as the next
* sibling). If the reference node has no parent, then does nothing.
* @param {Node} newNode Node to insert.
* @param {Node} refNode Reference node to insert after.
*/
goog.dom.insertSiblingAfter = function(newNode, refNode) {
if (refNode.parentNode) {
refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
}
};
/**
* Insert a child at a given index. If index is larger than the number of child
* nodes that the parent currently has, the node is inserted as the last child
* node.
* @param {Element} parent The element into which to insert the child.
* @param {Node} child The element to insert.
* @param {number} index The index at which to insert the new child node. Must
* not be negative.
*/
goog.dom.insertChildAt = function(parent, child, index) {
// Note that if the second argument is null, insertBefore
// will append the child at the end of the list of children.
parent.insertBefore(child, parent.childNodes[index] || null);
};
/**
* Removes a node from its parent.
* @param {Node} node The node to remove.
* @return {Node} The node removed if removed; else, null.
*/
goog.dom.removeNode = function(node) {
return node && node.parentNode ? node.parentNode.removeChild(node) : null;
};
/**
* Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
* parent.
* @param {Node} newNode Node to insert.
* @param {Node} oldNode Node to replace.
*/
goog.dom.replaceNode = function(newNode, oldNode) {
var parent = oldNode.parentNode;
if (parent) {
parent.replaceChild(newNode, oldNode);
}
};
/**
* Flattens an element. That is, removes it and replace it with its children.
* Does nothing if the element is not in the document.
* @param {Element} element The element to flatten.
* @return {Element|undefined} The original element, detached from the document
* tree, sans children; or undefined, if the element was not in the document
* to begin with.
*/
goog.dom.flattenElement = function(element) {
var child, parent = element.parentNode;
if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
// Use IE DOM method (supported by Opera too) if available
if (element.removeNode) {
return /** @type {Element} */ (element.removeNode(false));
} else {
// Move all children of the original node up one level.
while ((child = element.firstChild)) {
parent.insertBefore(child, element);
}
// Detach the original element.
return /** @type {Element} */ (goog.dom.removeNode(element));
}
}
};
/**
* Returns an array containing just the element children of the given element.
* @param {Element} element The element whose element children we want.
* @return {!(Array|NodeList)} An array or array-like list of just the element
* children of the given element.
*/
goog.dom.getChildren = function(element) {
// We check if the children attribute is supported for child elements
// since IE8 misuses the attribute by also including comments.
if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&
element.children != undefined) {
return element.children;
}
// Fall back to manually filtering the element's child nodes.
return goog.array.filter(element.childNodes, function(node) {
return node.nodeType == goog.dom.NodeType.ELEMENT;
});
};
/**
* Returns the first child node that is an element.
* @param {Node} node The node to get the first child element of.
* @return {Element} The first child node of {@code node} that is an element.
*/
goog.dom.getFirstElementChild = function(node) {
if (node.firstElementChild != undefined) {
return /** @type {Element} */(node).firstElementChild;
}
return goog.dom.getNextElementNode_(node.firstChild, true);
};
/**
* Returns the last child node that is an element.
* @param {Node} node The node to get the last child element of.
* @return {Element} The last child node of {@code node} that is an element.
*/
goog.dom.getLastElementChild = function(node) {
if (node.lastElementChild != undefined) {
return /** @type {Element} */(node).lastElementChild;
}
return goog.dom.getNextElementNode_(node.lastChild, false);
};
/**
* Returns the first next sibling that is an element.
* @param {Node} node The node to get the next sibling element of.
* @return {Element} The next sibling of {@code node} that is an element.
*/
goog.dom.getNextElementSibling = function(node) {
if (node.nextElementSibling != undefined) {
return /** @type {Element} */(node).nextElementSibling;
}
return goog.dom.getNextElementNode_(node.nextSibling, true);
};
/**
* Returns the first previous sibling that is an element.
* @param {Node} node The node to get the previous sibling element of.
* @return {Element} The first previous sibling of {@code node} that is
* an element.
*/
goog.dom.getPreviousElementSibling = function(node) {
if (node.previousElementSibling != undefined) {
return /** @type {Element} */(node).previousElementSibling;
}
return goog.dom.getNextElementNode_(node.previousSibling, false);
};
/**
* Returns the first node that is an element in the specified direction,
* starting with {@code node}.
* @param {Node} node The node to get the next element from.
* @param {boolean} forward Whether to look forwards or backwards.
* @return {Element} The first element.
* @private
*/
goog.dom.getNextElementNode_ = function(node, forward) {
while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {
node = forward ? node.nextSibling : node.previousSibling;
}
return /** @type {Element} */ (node);
};
/**
* Returns the next node in source order from the given node.
* @param {Node} node The node.
* @return {Node} The next node in the DOM tree, or null if this was the last
* node.
*/
goog.dom.getNextNode = function(node) {
if (!node) {
return null;
}
if (node.firstChild) {
return node.firstChild;
}
while (node && !node.nextSibling) {
node = node.parentNode;
}
return node ? node.nextSibling : null;
};
/**
* Returns the previous node in source order from the given node.
* @param {Node} node The node.
* @return {Node} The previous node in the DOM tree, or null if this was the
* first node.
*/
goog.dom.getPreviousNode = function(node) {
if (!node) {
return null;
}
if (!node.previousSibling) {
return node.parentNode;
}
node = node.previousSibling;
while (node && node.lastChild) {
node = node.lastChild;
}
return node;
};
/**
* Whether the object looks like a DOM node.
* @param {*} obj The object being tested for node likeness.
* @return {boolean} Whether the object looks like a DOM node.
*/
goog.dom.isNodeLike = function(obj) {
return goog.isObject(obj) && obj.nodeType > 0;
};
/**
* Whether the object looks like an Element.
* @param {*} obj The object being tested for Element likeness.
* @return {boolean} Whether the object looks like an Element.
*/
goog.dom.isElement = function(obj) {
return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;
};
/**
* Returns true if the specified value is a Window object. This includes the
* global window for HTML pages, and iframe windows.
* @param {*} obj Variable to test.
* @return {boolean} Whether the variable is a window.
*/
goog.dom.isWindow = function(obj) {
return goog.isObject(obj) && obj['window'] == obj;
};
/**
* Returns an element's parent, if it's an Element.
* @param {Element} element The DOM element.
* @return {Element} The parent, or null if not an Element.
*/
goog.dom.getParentElement = function(element) {
if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {
return element.parentElement;
}
var parent = element.parentNode;
return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;
};
/**
* Whether a node contains another node.
* @param {Node} parent The node that should contain the other node.
* @param {Node} descendant The node to test presence of.
* @return {boolean} Whether the parent node contains the descendent node.
*/
goog.dom.contains = function(parent, descendant) {
// We use browser specific methods for this if available since it is faster
// that way.
// IE DOM
if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {
return parent == descendant || parent.contains(descendant);
}
// W3C DOM Level 3
if (typeof parent.compareDocumentPosition != 'undefined') {
return parent == descendant ||
Boolean(parent.compareDocumentPosition(descendant) & 16);
}
// W3C DOM Level 1
while (descendant && parent != descendant) {
descendant = descendant.parentNode;
}
return descendant == parent;
};
/**
* Compares the document order of two nodes, returning 0 if they are the same
* node, a negative number if node1 is before node2, and a positive number if
* node2 is before node1. Note that we compare the order the tags appear in the
* document so in the tree <b><i>text</i></b> the B node is considered to be
* before the I node.
*
* @param {Node} node1 The first node to compare.
* @param {Node} node2 The second node to compare.
* @return {number} 0 if the nodes are the same node, a negative number if node1
* is before node2, and a positive number if node2 is before node1.
*/
goog.dom.compareNodeOrder = function(node1, node2) {
// Fall out quickly for equality.
if (node1 == node2) {
return 0;
}
// Use compareDocumentPosition where available
if (node1.compareDocumentPosition) {
// 4 is the bitmask for FOLLOWS.
return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;
}
// Special case for document nodes on IE 7 and 8.
if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) {
if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {
return -1;
}
if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {
return 1;
}
}
// Process in IE using sourceIndex - we check to see if the first node has
// a source index or if its parent has one.
if ('sourceIndex' in node1 ||
(node1.parentNode && 'sourceIndex' in node1.parentNode)) {
var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;
var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;
if (isElement1 && isElement2) {
return node1.sourceIndex - node2.sourceIndex;
} else {
var parent1 = node1.parentNode;
var parent2 = node2.parentNode;
if (parent1 == parent2) {
return goog.dom.compareSiblingOrder_(node1, node2);
}
if (!isElement1 && goog.dom.contains(parent1, node2)) {
return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);
}
if (!isElement2 && goog.dom.contains(parent2, node1)) {
return goog.dom.compareParentsDescendantNodeIe_(node2, node1);
}
return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -
(isElement2 ? node2.sourceIndex : parent2.sourceIndex);
}
}
// For Safari, we compare ranges.
var doc = goog.dom.getOwnerDocument(node1);
var range1, range2;
range1 = doc.createRange();
range1.selectNode(node1);
range1.collapse(true);
range2 = doc.createRange();
range2.selectNode(node2);
range2.collapse(true);
return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END,
range2);
};
/**
* Utility function to compare the position of two nodes, when
* {@code textNode}'s parent is an ancestor of {@code node}. If this entry
* condition is not met, this function will attempt to reference a null object.
* @param {Node} textNode The textNode to compare.
* @param {Node} node The node to compare.
* @return {number} -1 if node is before textNode, +1 otherwise.
* @private
*/
goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {
var parent = textNode.parentNode;
if (parent == node) {
// If textNode is a child of node, then node comes first.
return -1;
}
var sibling = node;
while (sibling.parentNode != parent) {
sibling = sibling.parentNode;
}
return goog.dom.compareSiblingOrder_(sibling, textNode);
};
/**
* Utility function to compare the position of two nodes known to be non-equal
* siblings.
* @param {Node} node1 The first node to compare.
* @param {Node} node2 The second node to compare.
* @return {number} -1 if node1 is before node2, +1 otherwise.
* @private
*/
goog.dom.compareSiblingOrder_ = function(node1, node2) {
var s = node2;
while ((s = s.previousSibling)) {
if (s == node1) {
// We just found node1 before node2.
return -1;
}
}
// Since we didn't find it, node1 must be after node2.
return 1;
};
/**
* Find the deepest common ancestor of the given nodes.
* @param {...Node} var_args The nodes to find a common ancestor of.
* @return {Node} The common ancestor of the nodes, or null if there is none.
* null will only be returned if two or more of the nodes are from different
* documents.
*/
goog.dom.findCommonAncestor = function(var_args) {
var i, count = arguments.length;
if (!count) {
return null;
} else if (count == 1) {
return arguments[0];
}
var paths = [];
var minLength = Infinity;
for (i = 0; i < count; i++) {
// Compute the list of ancestors.
var ancestors = [];
var node = arguments[i];
while (node) {
ancestors.unshift(node);
node = node.parentNode;
}
// Save the list for comparison.
paths.push(ancestors);
minLength = Math.min(minLength, ancestors.length);
}
var output = null;
for (i = 0; i < minLength; i++) {
var first = paths[0][i];
for (var j = 1; j < count; j++) {
if (first != paths[j][i]) {
return output;
}
}
output = first;
}
return output;
};
/**
* Returns the owner document for a node.
* @param {Node|Window} node The node to get the document for.
* @return {!Document} The document owning the node.
*/
goog.dom.getOwnerDocument = function(node) {
// TODO(arv): Remove IE5 code.
// IE5 uses document instead of ownerDocument
return /** @type {!Document} */ (
node.nodeType == goog.dom.NodeType.DOCUMENT ? node :
node.ownerDocument || node.document);
};
/**
* Cross-browser function for getting the document element of a frame or iframe.
* @param {Element} frame Frame element.
* @return {!Document} The frame content document.
*/
goog.dom.getFrameContentDocument = function(frame) {
var doc = frame.contentDocument || frame.contentWindow.document;
return doc;
};
/**
* Cross-browser function for getting the window of a frame or iframe.
* @param {Element} frame Frame element.
* @return {Window} The window associated with the given frame.
*/
goog.dom.getFrameContentWindow = function(frame) {
return frame.contentWindow ||
goog.dom.getWindow_(goog.dom.getFrameContentDocument(frame));
};
/**
* Cross-browser function for setting the text content of an element.
* @param {Element} element The element to change the text content of.
* @param {string|number} text The string that should replace the current
* element content.
*/
goog.dom.setTextContent = function(element, text) {
if ('textContent' in element) {
element.textContent = text;
} else if (element.firstChild &&
element.firstChild.nodeType == goog.dom.NodeType.TEXT) {
// If the first child is a text node we just change its data and remove the
// rest of the children.
while (element.lastChild != element.firstChild) {
element.removeChild(element.lastChild);
}
element.firstChild.data = text;
} else {
goog.dom.removeChildren(element);
var doc = goog.dom.getOwnerDocument(element);
element.appendChild(doc.createTextNode(String(text)));
}
};
/**
* Gets the outerHTML of a node, which islike innerHTML, except that it
* actually contains the HTML of the node itself.
* @param {Element} element The element to get the HTML of.
* @return {string} The outerHTML of the given element.
*/
goog.dom.getOuterHtml = function(element) {
// IE, Opera and WebKit all have outerHTML.
if ('outerHTML' in element) {
return element.outerHTML;
} else {
var doc = goog.dom.getOwnerDocument(element);
var div = doc.createElement('div');
div.appendChild(element.cloneNode(true));
return div.innerHTML;
}
};
/**
* Finds the first descendant node that matches the filter function, using
* a depth first search. This function offers the most general purpose way
* of finding a matching element. You may also wish to consider
* {@code goog.dom.query} which can express many matching criteria using
* CSS selector expressions. These expressions often result in a more
* compact representation of the desired result.
* @see goog.dom.query
*
* @param {Node} root The root of the tree to search.
* @param {function(Node) : boolean} p The filter function.
* @return {Node|undefined} The found node or undefined if none is found.
*/
goog.dom.findNode = function(root, p) {
var rv = [];
var found = goog.dom.findNodes_(root, p, rv, true);
return found ? rv[0] : undefined;
};
/**
* Finds all the descendant nodes that match the filter function, using a
* a depth first search. This function offers the most general-purpose way
* of finding a set of matching elements. You may also wish to consider
* {@code goog.dom.query} which can express many matching criteria using
* CSS selector expressions. These expressions often result in a more
* compact representation of the desired result.
* @param {Node} root The root of the tree to search.
* @param {function(Node) : boolean} p The filter function.
* @return {!Array.<!Node>} The found nodes or an empty array if none are found.
*/
goog.dom.findNodes = function(root, p) {
var rv = [];
goog.dom.findNodes_(root, p, rv, false);
return rv;
};
/**
* Finds the first or all the descendant nodes that match the filter function,
* using a depth first search.
* @param {Node} root The root of the tree to search.
* @param {function(Node) : boolean} p The filter function.
* @param {!Array.<!Node>} rv The found nodes are added to this array.
* @param {boolean} findOne If true we exit after the first found node.
* @return {boolean} Whether the search is complete or not. True in case findOne
* is true and the node is found. False otherwise.
* @private
*/
goog.dom.findNodes_ = function(root, p, rv, findOne) {
if (root != null) {
var child = root.firstChild;
while (child) {
if (p(child)) {
rv.push(child);
if (findOne) {
return true;
}
}
if (goog.dom.findNodes_(child, p, rv, findOne)) {
return true;
}
child = child.nextSibling;
}
}
return false;
};
/**
* Map of tags whose content to ignore when calculating text length.
* @type {Object}
* @private
*/
goog.dom.TAGS_TO_IGNORE_ = {
'SCRIPT': 1,
'STYLE': 1,
'HEAD': 1,
'IFRAME': 1,
'OBJECT': 1
};
/**
* Map of tags which have predefined values with regard to whitespace.
* @type {Object}
* @private
*/
goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'};
/**
* Returns true if the element has a tab index that allows it to receive
* keyboard focus (tabIndex >= 0), false otherwise. Note that form elements
* natively support keyboard focus, even if they have no tab index.
* @param {Element} element Element to check.
* @return {boolean} Whether the element has a tab index that allows keyboard
* focus.
* @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
*/
goog.dom.isFocusableTabIndex = function(element) {
// IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),
// which returns an object with a 'specified' property if tabIndex is
// specified. This works on other browsers, too.
var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
if (attrNode && attrNode.specified) {
var index = element.tabIndex;
// NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.
return goog.isNumber(index) && index >= 0 && index < 32768;
}
return false;
};
/**
* Enables or disables keyboard focus support on the element via its tab index.
* Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
* (or elements that natively support keyboard focus, like form elements) can
* receive keyboard focus. See http://go/tabindex for more info.
* @param {Element} element Element whose tab index is to be changed.
* @param {boolean} enable Whether to set or remove a tab index on the element
* that supports keyboard focus.
*/
goog.dom.setFocusableTabIndex = function(element, enable) {
if (enable) {
element.tabIndex = 0;
} else {
// Set tabIndex to -1 first, then remove it. This is a workaround for
// Safari (confirmed in version 4 on Windows). When removing the attribute
// without setting it to -1 first, the element remains keyboard focusable
// despite not having a tabIndex attribute anymore.
element.tabIndex = -1;
element.removeAttribute('tabIndex'); // Must be camelCase!
}
};
/**
* Returns the text content of the current node, without markup and invisible
* symbols. New lines are stripped and whitespace is collapsed,
* such that each character would be visible.
*
* In browsers that support it, innerText is used. Other browsers attempt to
* simulate it via node traversal. Line breaks are canonicalized in IE.
*
* @param {Node} node The node from which we are getting content.
* @return {string} The text content.
*/
goog.dom.getTextContent = function(node) {
var textContent;
// Note(arv): IE9, Opera, and Safari 3 support innerText but they include
// text nodes in script tags. So we revert to use a user agent test here.
if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) {
textContent = goog.string.canonicalizeNewlines(node.innerText);
// Unfortunately .innerText() returns text with ­ symbols
// We need to filter it out and then remove duplicate whitespaces
} else {
var buf = [];
goog.dom.getTextContent_(node, buf, true);
textContent = buf.join('');
}
// Strip ­ entities. goog.format.insertWordBreaks inserts them in Opera.
textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');
// Strip ​ entities. goog.format.insertWordBreaks inserts them in IE8.
textContent = textContent.replace(/\u200B/g, '');
// Skip this replacement on old browsers with working innerText, which
// automatically turns into ' ' and / +/ into ' ' when reading
// innerText.
if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {
textContent = textContent.replace(/ +/g, ' ');
}
if (textContent != ' ') {
textContent = textContent.replace(/^\s*/, '');
}
return textContent;
};
/**
* Returns the text content of the current node, without markup.
*
* Unlike {@code getTextContent} this method does not collapse whitespaces
* or normalize lines breaks.
*
* @param {Node} node The node from which we are getting content.
* @return {string} The raw text content.
*/
goog.dom.getRawTextContent = function(node) {
var buf = [];
goog.dom.getTextContent_(node, buf, false);
return buf.join('');
};
/**
* Recursive support function for text content retrieval.
*
* @param {Node} node The node from which we are getting content.
* @param {Array} buf string buffer.
* @param {boolean} normalizeWhitespace Whether to normalize whitespace.
* @private
*/
goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {
if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {
// ignore certain tags
} else if (node.nodeType == goog.dom.NodeType.TEXT) {
if (normalizeWhitespace) {
buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
} else {
buf.push(node.nodeValue);
}
} else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);
} else {
var child = node.firstChild;
while (child) {
goog.dom.getTextContent_(child, buf, normalizeWhitespace);
child = child.nextSibling;
}
}
};
/**
* Returns the text length of the text contained in a node, without markup. This
* is equivalent to the selection length if the node was selected, or the number
* of cursor movements to traverse the node. Images & BRs take one space. New
* lines are ignored.
*
* @param {Node} node The node whose text content length is being calculated.
* @return {number} The length of {@code node}'s text content.
*/
goog.dom.getNodeTextLength = function(node) {
return goog.dom.getTextContent(node).length;
};
/**
* Returns the text offset of a node relative to one of its ancestors. The text
* length is the same as the length calculated by goog.dom.getNodeTextLength.
*
* @param {Node} node The node whose offset is being calculated.
* @param {Node=} opt_offsetParent The node relative to which the offset will
* be calculated. Defaults to the node's owner document's body.
* @return {number} The text offset.
*/
goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {
var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;
var buf = [];
while (node && node != root) {
var cur = node;
while ((cur = cur.previousSibling)) {
buf.unshift(goog.dom.getTextContent(cur));
}
node = node.parentNode;
}
// Trim left to deal with FF cases when there might be line breaks and empty
// nodes at the front of the text
return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;
};
/**
* Returns the node at a given offset in a parent node. If an object is
* provided for the optional third parameter, the node and the remainder of the
* offset will stored as properties of this object.
* @param {Node} parent The parent node.
* @param {number} offset The offset into the parent node.
* @param {Object=} opt_result Object to be used to store the return value. The
* return value will be stored in the form {node: Node, remainder: number}
* if this object is provided.
* @return {Node} The node at the given offset.
*/
goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {
var stack = [parent], pos = 0, cur = null;
while (stack.length > 0 && pos < offset) {
cur = stack.pop();
if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {
// ignore certain tags
} else if (cur.nodeType == goog.dom.NodeType.TEXT) {
var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');
pos += text.length;
} else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;
} else {
for (var i = cur.childNodes.length - 1; i >= 0; i--) {
stack.push(cur.childNodes[i]);
}
}
}
if (goog.isObject(opt_result)) {
opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;
opt_result.node = cur;
}
return cur;
};
/**
* Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
* the object must have a numeric length property and an item function (which
* has type 'string' on IE for some reason).
* @param {Object} val Object to test.
* @return {boolean} Whether the object is a NodeList.
*/
goog.dom.isNodeList = function(val) {
// TODO(attila): Now the isNodeList is part of goog.dom we can use
// goog.userAgent to make this simpler.
// A NodeList must have a length property of type 'number' on all platforms.
if (val && typeof val.length == 'number') {
// A NodeList is an object everywhere except Safari, where it's a function.
if (goog.isObject(val)) {
// A NodeList must have an item function (on non-IE platforms) or an item
// property of type 'string' (on IE).
return typeof val.item == 'function' || typeof val.item == 'string';
} else if (goog.isFunction(val)) {
// On Safari, a NodeList is a function with an item property that is also
// a function.
return typeof val.item == 'function';
}
}
// Not a NodeList.
return false;
};
/**
* Walks up the DOM hierarchy returning the first ancestor that has the passed
* tag name and/or class name. If the passed element matches the specified
* criteria, the element itself is returned.
* @param {Node} element The DOM node to start with.
* @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
* null/undefined to match only based on class name).
* @param {?string=} opt_class The class name to match (or null/undefined to
* match only based on tag name).
* @return {Element} The first ancestor that matches the passed criteria, or
* null if no match is found.
*/
goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class) {
if (!opt_tag && !opt_class) {
return null;
}
var tagName = opt_tag ? opt_tag.toUpperCase() : null;
return /** @type {Element} */ (goog.dom.getAncestor(element,
function(node) {
return (!tagName || node.nodeName == tagName) &&
(!opt_class || goog.dom.classes.has(node, opt_class));
}, true));
};
/**
* Walks up the DOM hierarchy returning the first ancestor that has the passed
* class name. If the passed element matches the specified criteria, the
* element itself is returned.
* @param {Node} element The DOM node to start with.
* @param {string} className The class name to match.
* @return {Element} The first ancestor that matches the passed criteria, or
* null if none match.
*/
goog.dom.getAncestorByClass = function(element, className) {
return goog.dom.getAncestorByTagNameAndClass(element, null, className);
};
/**
* Walks up the DOM hierarchy returning the first ancestor that passes the
* matcher function.
* @param {Node} element The DOM node to start with.
* @param {function(Node) : boolean} matcher A function that returns true if the
* passed node matches the desired criteria.
* @param {boolean=} opt_includeNode If true, the node itself is included in
* the search (the first call to the matcher will pass startElement as
* the node to test).
* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
* dom.
* @return {Node} DOM node that matched the matcher, or null if there was
* no match.
*/
goog.dom.getAncestor = function(
element, matcher, opt_includeNode, opt_maxSearchSteps) {
if (!opt_includeNode) {
element = element.parentNode;
}
var ignoreSearchSteps = opt_maxSearchSteps == null;
var steps = 0;
while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) {
if (matcher(element)) {
return element;
}
element = element.parentNode;
steps++;
}
// Reached the root of the DOM without a match
return null;
};
/**
* Determines the active element in the given document.
* @param {Document} doc The document to look in.
* @return {Element} The active element.
*/
goog.dom.getActiveElement = function(doc) {
try {
return doc && doc.activeElement;
} catch (e) {
// NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE
// throws an exception. I'm not 100% sure why, but I suspect it chokes
// on document.activeElement if the activeElement has been recently
// removed from the DOM by a JS operation.
//
// We assume that an exception here simply means
// "there is no active element."
}
return null;
};
/**
* Create an instance of a DOM helper with a new document object.
* @param {Document=} opt_document Document object to associate with this
* DOM helper.
* @constructor
*/
goog.dom.DomHelper = function(opt_document) {
/**
* Reference to the document object to use
* @type {!Document}
* @private
*/
this.document_ = opt_document || goog.global.document || document;
};
/**
* Gets the dom helper object for the document where the element resides.
* @param {Node=} opt_node If present, gets the DomHelper for this node.
* @return {!goog.dom.DomHelper} The DomHelper.
*/
goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;
/**
* Sets the document object.
* @param {!Document} document Document object.
*/
goog.dom.DomHelper.prototype.setDocument = function(document) {
this.document_ = document;
};
/**
* Gets the document object being used by the dom library.
* @return {!Document} Document object.
*/
goog.dom.DomHelper.prototype.getDocument = function() {
return this.document_;
};
/**
* Alias for {@code getElementById}. If a DOM node is passed in then we just
* return that.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
*/
goog.dom.DomHelper.prototype.getElement = function(element) {
if (goog.isString(element)) {
return this.document_.getElementById(element);
} else {
return element;
}
};
/**
* Alias for {@code getElement}.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
* @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.
*/
goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;
/**
* Looks up elements by both tag and class name, using browser native functions
* ({@code querySelectorAll}, {@code getElementsByTagName} or
* {@code getElementsByClassName}) where possible. The returned array is a live
* NodeList or a static list depending on the code path taken.
*
* @see goog.dom.query
*
* @param {?string=} opt_tag Element tag name or * for all tags.
* @param {?string=} opt_class Optional class name.
* @param {(Document|Element)=} opt_el Optional element to look in.
* @return { {length: number} } Array-like list of elements (only a length
* property and numerical indices are guaranteed to exist).
*/
goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag,
opt_class,
opt_el) {
return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag,
opt_class, opt_el);
};
/**
* Returns an array of all the elements with the provided className.
* @see {goog.dom.query}
* @param {string} className the name of the class to look for.
* @param {Element|Document=} opt_el Optional element to look in.
* @return { {length: number} } The items found with the class name provided.
*/
goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {
var doc = opt_el || this.document_;
return goog.dom.getElementsByClass(className, doc);
};
/**
* Returns the first element we find matching the provided class name.
* @see {goog.dom.query}
* @param {string} className the name of the class to look for.
* @param {(Element|Document)=} opt_el Optional element to look in.
* @return {Element} The first item found with the class name provided.
*/
goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {
var doc = opt_el || this.document_;
return goog.dom.getElementByClass(className, doc);
};
/**
* Alias for {@code getElementsByTagNameAndClass}.
* @deprecated Use DomHelper getElementsByTagNameAndClass.
* @see goog.dom.query
*
* @param {?string=} opt_tag Element tag name.
* @param {?string=} opt_class Optional class name.
* @param {Element=} opt_el Optional element to look in.
* @return { {length: number} } Array-like list of elements (only a length
* property and numerical indices are guaranteed to exist).
*/
goog.dom.DomHelper.prototype.$$ =
goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;
/**
* Sets a number of properties on a node.
* @param {Element} element DOM node to set properties on.
* @param {Object} properties Hash of property:value pairs.
*/
goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;
/**
* Gets the dimensions of the viewport.
* @param {Window=} opt_window Optional window element to test. Defaults to
* the window of the Dom Helper.
* @return {!goog.math.Size} Object with values 'width' and 'height'.
*/
goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {
// TODO(arv): This should not take an argument. That breaks the rule of a
// a DomHelper representing a single frame/window/document.
return goog.dom.getViewportSize(opt_window || this.getWindow());
};
/**
* Calculates the height of the document.
*
* @return {number} The height of the document.
*/
goog.dom.DomHelper.prototype.getDocumentHeight = function() {
return goog.dom.getDocumentHeight_(this.getWindow());
};
/**
* Typedef for use with goog.dom.createDom and goog.dom.append.
* @typedef {Object|string|Array|NodeList}
*/
goog.dom.Appendable;
/**
* Returns a dom node with a set of attributes. This function accepts varargs
* for subsequent nodes to be added. Subsequent nodes will be added to the
* first node as childNodes.
*
* So:
* <code>createDom('div', null, createDom('p'), createDom('p'));</code>
* would return a div with two child paragraphs
*
* An easy way to move all child nodes of an existing element to a new parent
* element is:
* <code>createDom('div', null, oldElement.childNodes);</code>
* which will remove all child nodes from the old element and add them as
* child nodes of the new DIV.
*
* @param {string} tagName Tag to create.
* @param {Object|string=} opt_attributes If object, then a map of name-value
* pairs for attributes. If a string, then this is the className of the new
* element.
* @param {...goog.dom.Appendable} var_args Further DOM nodes or
* strings for text nodes. If one of the var_args is an array or
* NodeList, its elements will be added as childNodes instead.
* @return {!Element} Reference to a DOM node.
*/
goog.dom.DomHelper.prototype.createDom = function(tagName,
opt_attributes,
var_args) {
return goog.dom.createDom_(this.document_, arguments);
};
/**
* Alias for {@code createDom}.
* @param {string} tagName Tag to create.
* @param {(Object|string)=} opt_attributes If object, then a map of name-value
* pairs for attributes. If a string, then this is the className of the new
* element.
* @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for
* text nodes. If one of the var_args is an array, its children will be
* added as childNodes instead.
* @return {!Element} Reference to a DOM node.
* @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.
*/
goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;
/**
* Creates a new element.
* @param {string} name Tag name.
* @return {!Element} The new element.
*/
goog.dom.DomHelper.prototype.createElement = function(name) {
return this.document_.createElement(name);
};
/**
* Creates a new text node.
* @param {number|string} content Content.
* @return {!Text} The new text node.
*/
goog.dom.DomHelper.prototype.createTextNode = function(content) {
return this.document_.createTextNode(String(content));
};
/**
* Create a table.
* @param {number} rows The number of rows in the table. Must be >= 1.
* @param {number} columns The number of columns in the table. Must be >= 1.
* @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps.
* @return {!Element} The created table.
*/
goog.dom.DomHelper.prototype.createTable = function(rows, columns,
opt_fillWithNbsp) {
return goog.dom.createTable_(this.document_, rows, columns,
!!opt_fillWithNbsp);
};
/**
* Converts an HTML string into a node or a document fragment. A single Node
* is used if the {@code htmlString} only generates a single node. If the
* {@code htmlString} generates multiple nodes then these are put inside a
* {@code DocumentFragment}.
*
* @param {string} htmlString The HTML string to convert.
* @return {!Node} The resulting node.
*/
goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) {
return goog.dom.htmlToDocumentFragment_(this.document_, htmlString);
};
/**
* Returns the compatMode of the document.
* @return {string} The result is either CSS1Compat or BackCompat.
* @deprecated use goog.dom.DomHelper.prototype.isCss1CompatMode instead.
*/
goog.dom.DomHelper.prototype.getCompatMode = function() {
return this.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat';
};
/**
* Returns true if the browser is in "CSS1-compatible" (standards-compliant)
* mode, false otherwise.
* @return {boolean} True if in CSS1-compatible mode.
*/
goog.dom.DomHelper.prototype.isCss1CompatMode = function() {
return goog.dom.isCss1CompatMode_(this.document_);
};
/**
* Gets the window object associated with the document.
* @return {!Window} The window associated with the given document.
*/
goog.dom.DomHelper.prototype.getWindow = function() {
return goog.dom.getWindow_(this.document_);
};
/**
* Gets the document scroll element.
* @return {Element} Scrolling element.
*/
goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {
return goog.dom.getDocumentScrollElement_(this.document_);
};
/**
* Gets the document scroll distance as a coordinate object.
* @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.
*/
goog.dom.DomHelper.prototype.getDocumentScroll = function() {
return goog.dom.getDocumentScroll_(this.document_);
};
/**
* Determines the active element in the given document.
* @param {Document=} opt_doc The document to look in.
* @return {Element} The active element.
*/
goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {
return goog.dom.getActiveElement(opt_doc || this.document_);
};
/**
* Appends a child to a node.
* @param {Node} parent Parent.
* @param {Node} child Child.
*/
goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;
/**
* Appends a node with text or other nodes.
* @param {!Node} parent The node to append nodes to.
* @param {...goog.dom.Appendable} var_args The things to append to the node.
* If this is a Node it is appended as is.
* If this is a string then a text node is appended.
* If this is an array like object then fields 0 to length - 1 are appended.
*/
goog.dom.DomHelper.prototype.append = goog.dom.append;
/**
* Determines if the given node can contain children, intended to be used for
* HTML generation.
*
* @param {Node} node The node to check.
* @return {boolean} Whether the node can contain children.
*/
goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;
/**
* Removes all the child nodes on a DOM node.
* @param {Node} node Node to remove children from.
*/
goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;
/**
* Inserts a new node before an existing reference node (i.e., as the previous
* sibling). If the reference node has no parent, then does nothing.
* @param {Node} newNode Node to insert.
* @param {Node} refNode Reference node to insert before.
*/
goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;
/**
* Inserts a new node after an existing reference node (i.e., as the next
* sibling). If the reference node has no parent, then does nothing.
* @param {Node} newNode Node to insert.
* @param {Node} refNode Reference node to insert after.
*/
goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;
/**
* Insert a child at a given index. If index is larger than the number of child
* nodes that the parent currently has, the node is inserted as the last child
* node.
* @param {Element} parent The element into which to insert the child.
* @param {Node} child The element to insert.
* @param {number} index The index at which to insert the new child node. Must
* not be negative.
*/
goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;
/**
* Removes a node from its parent.
* @param {Node} node The node to remove.
* @return {Node} The node removed if removed; else, null.
*/
goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;
/**
* Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
* parent.
* @param {Node} newNode Node to insert.
* @param {Node} oldNode Node to replace.
*/
goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;
/**
* Flattens an element. That is, removes it and replace it with its children.
* @param {Element} element The element to flatten.
* @return {Element|undefined} The original element, detached from the document
* tree, sans children, or undefined if the element was already not in the
* document.
*/
goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;
/**
* Returns an array containing just the element children of the given element.
* @param {Element} element The element whose element children we want.
* @return {!(Array|NodeList)} An array or array-like list of just the element
* children of the given element.
*/
goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;
/**
* Returns the first child node that is an element.
* @param {Node} node The node to get the first child element of.
* @return {Element} The first child node of {@code node} that is an element.
*/
goog.dom.DomHelper.prototype.getFirstElementChild =
goog.dom.getFirstElementChild;
/**
* Returns the last child node that is an element.
* @param {Node} node The node to get the last child element of.
* @return {Element} The last child node of {@code node} that is an element.
*/
goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;
/**
* Returns the first next sibling that is an element.
* @param {Node} node The node to get the next sibling element of.
* @return {Element} The next sibling of {@code node} that is an element.
*/
goog.dom.DomHelper.prototype.getNextElementSibling =
goog.dom.getNextElementSibling;
/**
* Returns the first previous sibling that is an element.
* @param {Node} node The node to get the previous sibling element of.
* @return {Element} The first previous sibling of {@code node} that is
* an element.
*/
goog.dom.DomHelper.prototype.getPreviousElementSibling =
goog.dom.getPreviousElementSibling;
/**
* Returns the next node in source order from the given node.
* @param {Node} node The node.
* @return {Node} The next node in the DOM tree, or null if this was the last
* node.
*/
goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;
/**
* Returns the previous node in source order from the given node.
* @param {Node} node The node.
* @return {Node} The previous node in the DOM tree, or null if this was the
* first node.
*/
goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;
/**
* Whether the object looks like a DOM node.
* @param {*} obj The object being tested for node likeness.
* @return {boolean} Whether the object looks like a DOM node.
*/
goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;
/**
* Whether the object looks like an Element.
* @param {*} obj The object being tested for Element likeness.
* @return {boolean} Whether the object looks like an Element.
*/
goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;
/**
* Returns true if the specified value is a Window object. This includes the
* global window for HTML pages, and iframe windows.
* @param {*} obj Variable to test.
* @return {boolean} Whether the variable is a window.
*/
goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;
/**
* Returns an element's parent, if it's an Element.
* @param {Element} element The DOM element.
* @return {Element} The parent, or null if not an Element.
*/
goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;
/**
* Whether a node contains another node.
* @param {Node} parent The node that should contain the other node.
* @param {Node} descendant The node to test presence of.
* @return {boolean} Whether the parent node contains the descendent node.
*/
goog.dom.DomHelper.prototype.contains = goog.dom.contains;
/**
* Compares the document order of two nodes, returning 0 if they are the same
* node, a negative number if node1 is before node2, and a positive number if
* node2 is before node1. Note that we compare the order the tags appear in the
* document so in the tree <b><i>text</i></b> the B node is considered to be
* before the I node.
*
* @param {Node} node1 The first node to compare.
* @param {Node} node2 The second node to compare.
* @return {number} 0 if the nodes are the same node, a negative number if node1
* is before node2, and a positive number if node2 is before node1.
*/
goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;
/**
* Find the deepest common ancestor of the given nodes.
* @param {...Node} var_args The nodes to find a common ancestor of.
* @return {Node} The common ancestor of the nodes, or null if there is none.
* null will only be returned if two or more of the nodes are from different
* documents.
*/
goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;
/**
* Returns the owner document for a node.
* @param {Node} node The node to get the document for.
* @return {!Document} The document owning the node.
*/
goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;
/**
* Cross browser function for getting the document element of an iframe.
* @param {Element} iframe Iframe element.
* @return {!Document} The frame content document.
*/
goog.dom.DomHelper.prototype.getFrameContentDocument =
goog.dom.getFrameContentDocument;
/**
* Cross browser function for getting the window of a frame or iframe.
* @param {Element} frame Frame element.
* @return {Window} The window associated with the given frame.
*/
goog.dom.DomHelper.prototype.getFrameContentWindow =
goog.dom.getFrameContentWindow;
/**
* Cross browser function for setting the text content of an element.
* @param {Element} element The element to change the text content of.
* @param {string} text The string that should replace the current element
* content with.
*/
goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;
/**
* Gets the outerHTML of a node, which islike innerHTML, except that it
* actually contains the HTML of the node itself.
* @param {Element} element The element to get the HTML of.
* @return {string} The outerHTML of the given element.
*/
goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;
/**
* Finds the first descendant node that matches the filter function. This does
* a depth first search.
* @param {Node} root The root of the tree to search.
* @param {function(Node) : boolean} p The filter function.
* @return {Node|undefined} The found node or undefined if none is found.
*/
goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;
/**
* Finds all the descendant nodes that matches the filter function. This does a
* depth first search.
* @param {Node} root The root of the tree to search.
* @param {function(Node) : boolean} p The filter function.
* @return {Array.<Node>} The found nodes or an empty array if none are found.
*/
goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;
/**
* Returns true if the element has a tab index that allows it to receive
* keyboard focus (tabIndex >= 0), false otherwise. Note that form elements
* natively support keyboard focus, even if they have no tab index.
* @param {Element} element Element to check.
* @return {boolean} Whether the element has a tab index that allows keyboard
* focus.
*/
goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;
/**
* Enables or disables keyboard focus support on the element via its tab index.
* Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
* (or elements that natively support keyboard focus, like form elements) can
* receive keyboard focus. See http://go/tabindex for more info.
* @param {Element} element Element whose tab index is to be changed.
* @param {boolean} enable Whether to set or remove a tab index on the element
* that supports keyboard focus.
*/
goog.dom.DomHelper.prototype.setFocusableTabIndex =
goog.dom.setFocusableTabIndex;
/**
* Returns the text contents of the current node, without markup. New lines are
* stripped and whitespace is collapsed, such that each character would be
* visible.
*
* In browsers that support it, innerText is used. Other browsers attempt to
* simulate it via node traversal. Line breaks are canonicalized in IE.
*
* @param {Node} node The node from which we are getting content.
* @return {string} The text content.
*/
goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;
/**
* Returns the text length of the text contained in a node, without markup. This
* is equivalent to the selection length if the node was selected, or the number
* of cursor movements to traverse the node. Images & BRs take one space. New
* lines are ignored.
*
* @param {Node} node The node whose text content length is being calculated.
* @return {number} The length of {@code node}'s text content.
*/
goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;
/**
* Returns the text offset of a node relative to one of its ancestors. The text
* length is the same as the length calculated by
* {@code goog.dom.getNodeTextLength}.
*
* @param {Node} node The node whose offset is being calculated.
* @param {Node=} opt_offsetParent Defaults to the node's owner document's body.
* @return {number} The text offset.
*/
goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;
/**
* Returns the node at a given offset in a parent node. If an object is
* provided for the optional third parameter, the node and the remainder of the
* offset will stored as properties of this object.
* @param {Node} parent The parent node.
* @param {number} offset The offset into the parent node.
* @param {Object=} opt_result Object to be used to store the return value. The
* return value will be stored in the form {node: Node, remainder: number}
* if this object is provided.
* @return {Node} The node at the given offset.
*/
goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;
/**
* Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
* the object must have a numeric length property and an item function (which
* has type 'string' on IE for some reason).
* @param {Object} val Object to test.
* @return {boolean} Whether the object is a NodeList.
*/
goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;
/**
* Walks up the DOM hierarchy returning the first ancestor that has the passed
* tag name and/or class name. If the passed element matches the specified
* criteria, the element itself is returned.
* @param {Node} element The DOM node to start with.
* @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
* null/undefined to match only based on class name).
* @param {?string=} opt_class The class name to match (or null/undefined to
* match only based on tag name).
* @return {Element} The first ancestor that matches the passed criteria, or
* null if no match is found.
*/
goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =
goog.dom.getAncestorByTagNameAndClass;
/**
* Walks up the DOM hierarchy returning the first ancestor that has the passed
* class name. If the passed element matches the specified criteria, the
* element itself is returned.
* @param {Node} element The DOM node to start with.
* @param {string} class The class name to match.
* @return {Element} The first ancestor that matches the passed criteria, or
* null if none match.
*/
goog.dom.DomHelper.prototype.getAncestorByClass =
goog.dom.getAncestorByClass;
/**
* Walks up the DOM hierarchy returning the first ancestor that passes the
* matcher function.
* @param {Node} element The DOM node to start with.
* @param {function(Node) : boolean} matcher A function that returns true if the
* passed node matches the desired criteria.
* @param {boolean=} opt_includeNode If true, the node itself is included in
* the search (the first call to the matcher will pass startElement as
* the node to test).
* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
* dom.
* @return {Node} DOM node that matched the matcher, or null if there was
* no match.
*/
goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 SimpleResult object that implements goog.result.Result.
* See below for a more detailed description.
*/
goog.provide('goog.result.SimpleResult');
goog.provide('goog.result.SimpleResult.StateError');
goog.require('goog.debug.Error');
goog.require('goog.result.Result');
/**
* A SimpleResult object is a basic implementation of the
* goog.result.Result interface. This could be subclassed(e.g. XHRResult)
* or instantiated and returned by another class as a form of result. The caller
* receiving the result could then attach handlers to be called when the result
* is resolved(success or error).
*
* @constructor
* @implements {goog.result.Result}
*/
goog.result.SimpleResult = function() {
/**
* The current state of this Result.
* @type {goog.result.Result.State}
* @private
*/
this.state_ = goog.result.Result.State.PENDING;
/**
* The list of handlers to call when this Result is resolved.
* @type {!Array.<!function(goog.result.SimpleResult)>}
* @private
*/
this.handlers_ = [];
// The value_ and error_ properties are initialized in the constructor to
// ensure that all SimpleResult instances share the same hidden class in
// modern JavaScript engines.
/**
* The 'value' of this Result.
* @type {*}
* @private
*/
this.value_ = undefined;
/**
* The error slug for this Result.
* @type {*}
* @private
*/
this.error_ = undefined;
};
/**
* Error thrown if there is an attempt to set the value or error for this result
* more than once.
*
* @constructor
* @extends {goog.debug.Error}
*/
goog.result.SimpleResult.StateError = function() {
goog.base(this, 'Multiple attempts to set the state of this Result');
};
goog.inherits(goog.result.SimpleResult.StateError, goog.debug.Error);
/** @override */
goog.result.SimpleResult.prototype.getState = function() {
return this.state_;
};
/** @override */
goog.result.SimpleResult.prototype.getValue = function() {
return this.value_;
};
/** @override */
goog.result.SimpleResult.prototype.getError = function() {
return this.error_;
};
/**
* Attaches handlers to be called when the value of this Result is available.
*
* @param {!function(!goog.result.SimpleResult)} handler The function
* called when the value is available. The function is passed the Result
* object as the only argument.
* @override
*/
goog.result.SimpleResult.prototype.wait = function(handler) {
if (this.isPending_()) {
this.handlers_.push(handler);
} else {
handler(this);
}
};
/**
* Sets the value of this Result, changing the state.
*
* @param {*} value The value to set for this Result.
*/
goog.result.SimpleResult.prototype.setValue = function(value) {
if (this.isPending_()) {
this.value_ = value;
this.state_ = goog.result.Result.State.SUCCESS;
this.callHandlers_();
} else if (!this.isCanceled()) {
// setValue is a no-op if this Result has been canceled.
throw new goog.result.SimpleResult.StateError();
}
};
/**
* Sets the Result to be an error Result.
*
* @param {*=} opt_error Optional error slug to set for this Result.
*/
goog.result.SimpleResult.prototype.setError = function(opt_error) {
if (this.isPending_()) {
this.error_ = opt_error;
this.state_ = goog.result.Result.State.ERROR;
this.callHandlers_();
} else if (!this.isCanceled()) {
// setError is a no-op if this Result has been canceled.
throw new goog.result.SimpleResult.StateError();
}
};
/**
* Calls the handlers registered for this Result.
*
* @private
*/
goog.result.SimpleResult.prototype.callHandlers_ = function() {
while (this.handlers_.length) {
var callback = this.handlers_.shift();
callback(this);
}
};
/**
* @return {boolean} Whether the Result is pending.
* @private
*/
goog.result.SimpleResult.prototype.isPending_ = function() {
return this.state_ == goog.result.Result.State.PENDING;
};
/**
* Cancels the Result.
*
* @return {boolean} Whether the result was canceled. It will not be canceled if
* the result was already canceled or has already resolved.
* @override
*/
goog.result.SimpleResult.prototype.cancel = function() {
// cancel is a no-op if the result has been resolved.
if (this.isPending_()) {
this.setError(new goog.result.Result.CancelError());
return true;
}
return false;
};
/** @override */
goog.result.SimpleResult.prototype.isCanceled = function() {
return this.state_ == goog.result.Result.State.ERROR &&
this.error_ instanceof goog.result.Result.CancelError;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 an interface that represents a Result.
*/
goog.provide('goog.result.Result');
goog.require('goog.debug.Error');
/**
* A Result object represents a value returned by an asynchronous
* operation at some point in the future (e.g. a network fetch). This is akin
* to a 'Promise' or a 'Future' in other languages and frameworks.
*
* @interface
*/
goog.result.Result = function() {};
/**
* Attaches handlers to be called when the value of this Result is available.
*
* @param {!function(!goog.result.Result)} handler The function called when
* the value is available. The function is passed the Result object as the
* only argument.
*/
goog.result.Result.prototype.wait = function(handler) {};
/**
* The States this object can be in.
*
* @enum {string}
*/
goog.result.Result.State = {
/** The operation was a success and the value is available. */
SUCCESS: 'success',
/** The operation resulted in an error. */
ERROR: 'error',
/** The operation is incomplete and the value is not yet available. */
PENDING: 'pending'
};
/**
* @return {!goog.result.Result.State} The state of this Result.
*/
goog.result.Result.prototype.getState = function() {};
/**
* @return {*} The value of this Result. Will return undefined if the Result is
* pending or was an error.
*/
goog.result.Result.prototype.getValue = function() {};
/**
* @return {*} The error slug for this Result. Will return undefined if the
* Result was a success, the error slug was not set, or if the Result is
* pending.
*/
goog.result.Result.prototype.getError = function() {};
/**
* Cancels the current Result, invoking the canceler function, if set.
*
* @return {boolean} Whether the Result was canceled.
*/
goog.result.Result.prototype.cancel = function() {};
/**
* @return {boolean} Whether this Result was canceled.
*/
goog.result.Result.prototype.isCanceled = function() {};
/**
* The value to be passed to the error handlers invoked upon cancellation.
* @constructor
* @param {string=} opt_msg The error message for CancelError.
* @extends {goog.debug.Error}
*/
goog.result.Result.CancelError = function(opt_msg) {
var msg = opt_msg || 'Result canceled';
goog.base(this, msg);
};
goog.inherits(goog.result.Result.CancelError, goog.debug.Error);
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 provides primitives and tools (wait, transform,
* chain, combine) that make it easier to work with Results. This section
* gives an overview of their functionality along with some examples and the
* actual definitions have detailed descriptions next to them.
*
*/
goog.provide('goog.result');
goog.require('goog.array');
goog.require('goog.result.DependentResult');
goog.require('goog.result.Result');
goog.require('goog.result.SimpleResult');
/**
* Returns a successful result containing the provided value.
*
* Example:
* <pre>
*
* var value = 'some-value';
* var result = goog.result.immediateResult(value);
* assertEquals(goog.result.Result.State.SUCCESS, result.getState());
* assertEquals(value, result.getValue());
*
* </pre>
*
* @param {*} value The value of the result.
* @return {!goog.result.Result} A Result object that has already been resolved
* to the supplied value.
*/
goog.result.successfulResult = function(value) {
var result = new goog.result.SimpleResult();
result.setValue(value);
return result;
};
/**
* Returns a failed result with the optional error slug set.
*
* Example:
* <pre>
*
* var error = new Error('something-failed');
* var result = goog.result.failedResult(error);
* assertEquals(goog.result.Result.State.ERROR, result.getState());
* assertEquals(error, result.getError());
*
* </pre>
*
* @param {*=} opt_error The error to which the result should resolve.
* @return {!goog.result.Result} A Result object that has already been resolved
* to the supplied Error.
*/
goog.result.failedResult = function(opt_error) {
var result = new goog.result.SimpleResult();
result.setError(opt_error);
return result;
};
/**
* Returns a canceled result.
* The result will be resolved to an error of type CancelError.
*
* Example:
* <pre>
*
* var result = goog.result.canceledResult();
* assertEquals(goog.result.Result.State.ERROR, result.getState());
* var error = result.getError();
* assertTrue(error instanceof goog.result.Result.CancelError);
*
* </pre>
*
* @return {!goog.result.Result} A canceled Result.
*/
goog.result.canceledResult = function() {
var result = new goog.result.SimpleResult();
result.cancel();
return result;
};
/**
* Calls the handler on resolution of the result (success or failure).
* The handler is passed the result object as the only parameter. The call will
* be immediate if the result is no longer pending.
*
* Example:
* <pre>
*
* var result = xhr.get('testdata/xhr_test_text.data');
*
* // Wait for the result to be resolved and alert it's state.
* goog.result.wait(result, function(result) {
* alert('State: ' + result.getState());
* });
* </pre>
*
* @param {!goog.result.Result} result The result to install the handlers.
* @param {function(this:T, !goog.result.Result)} handler The handler to be
* called. The handler is passed the result object as the only parameter.
* @param {!T=} opt_scope Optional scope for the handler.
* @template T
*/
goog.result.wait = function(result, handler, opt_scope) {
result.wait(opt_scope ? goog.bind(handler, opt_scope) : handler);
};
/**
* Calls the handler if the result succeeds. The result object is the only
* parameter passed to the handler. The call will be immediate if the result
* has already succeeded.
*
* Example:
* <pre>
*
* var result = xhr.get('testdata/xhr_test_text.data');
*
* // attach a success handler.
* goog.result.waitOnSuccess(result, function(resultValue, result) {
* var datavalue = result.getvalue();
* alert('value: ' + datavalue + ' == ' + resultValue);
* });
* </pre>
*
* @param {!goog.result.Result} result The result to install the handlers.
* @param {function(this:T, ?, !goog.result.Result)} handler The handler to be
* called. The handler is passed the result value and the result as
* parameters.
* @param {!T=} opt_scope Optional scope for the handler.
* @template T
*/
goog.result.waitOnSuccess = function(result, handler, opt_scope) {
goog.result.wait(result, function(res) {
if (res.getState() == goog.result.Result.State.SUCCESS) {
// 'this' refers to opt_scope
handler.call(this, res.getValue(), res);
}
}, opt_scope);
};
/**
* Calls the handler if the result action errors. The result object is passed as
* the only parameter to the handler. The call will be immediate if the result
* object has already resolved to an error.
*
* Example:
*
* <pre>
*
* var result = xhr.get('testdata/xhr_test_text.data');
*
* // Attach a failure handler.
* goog.result.waitOnError(result, function(error) {
* // Failed asynchronous call!
* });
* </pre>
*
* @param {!goog.result.Result} result The result to install the handlers.
* @param {function(this:T, ?, !goog.result.Result)} handler The handler to be
* called. The handler is passed the error and the result object as
* parameters.
* @param {!T=} opt_scope Optional scope for the handler.
* @template T
*/
goog.result.waitOnError = function(result, handler, opt_scope) {
goog.result.wait(result, function(res) {
if (res.getState() == goog.result.Result.State.ERROR) {
// 'this' refers to opt_scope
handler.call(this, res.getError(), res);
}
}, opt_scope);
};
/**
* Given a result and a transform function, returns a new result whose value,
* on success, will be the value of the given result after having been passed
* through the transform function.
*
* If the given result is an error, the returned result is also an error and the
* transform will not be called.
*
* Example:
* <pre>
*
* var result = xhr.getJson('testdata/xhr_test_json.data');
*
* // Transform contents of returned data using 'processJson' and create a
* // transformed result to use returned JSON.
* var transformedResult = goog.result.transform(result, processJson);
*
* // Attach success and failure handlers to the tranformed result.
* goog.result.waitOnSuccess(transformedResult, function(result) {
* var jsonData = result.getValue();
* assertEquals('ok', jsonData['stat']);
* });
*
* goog.result.waitOnError(transformedResult, function(error) {
* // Failed getJson call
* });
* </pre>
*
* @param {!goog.result.Result} result The result whose value will be
* transformed.
* @param {function(?):?} transformer The transformer
* function. The return value of this function will become the value of the
* returned result.
*
* @return {!goog.result.DependentResult} A new Result whose eventual value will
* be the returned value of the transformer function.
*/
goog.result.transform = function(result, transformer) {
var returnedResult = new goog.result.DependentResultImpl_([result]);
goog.result.wait(result, function(res) {
if (res.getState() == goog.result.Result.State.SUCCESS) {
returnedResult.setValue(transformer(res.getValue()));
} else {
returnedResult.setError(res.getError());
}
});
return returnedResult;
};
/**
* The chain function aids in chaining of asynchronous Results. This provides a
* convenience for use cases where asynchronous operations must happen serially
* i.e. subsequent asynchronous operations are dependent on data returned by
* prior asynchronous operations.
*
* It accepts a result and an action callback as arguments and returns a
* result. The action callback is called when the first result succeeds and is
* supposed to return a second result. The returned result is resolved when one
* of both of the results resolve (depending on their success or failure.) The
* state and value of the returned result in the various cases is documented
* below:
*
* First Result State: Second Result State: Returned Result State:
* SUCCESS SUCCESS SUCCESS
* SUCCESS ERROR ERROR
* ERROR Not created ERROR
*
* The value of the returned result, in the case both results succeed, is the
* value of the second result (the result returned by the action callback.)
*
* Example:
* <pre>
*
* var testDataResult = xhr.get('testdata/xhr_test_text.data');
*
* // Chain this result to perform another asynchronous operation when this
* // Result is resolved.
* var chainedResult = goog.result.chain(testDataResult,
* function(testDataResult) {
*
* // The result value of testDataResult is the URL for JSON data.
* var jsonDataUrl = testDataResult.getValue();
*
* // Create a new Result object when the original result is resolved.
* var jsonResult = xhr.getJson(jsonDataUrl);
*
* // Return the newly created Result.
* return jsonResult;
* });
*
* // The chained result resolves to success when both results resolve to
* // success.
* goog.result.waitOnSuccess(chainedResult, function(result) {
*
* // At this point, both results have succeeded and we can use the JSON
* // data returned by the second asynchronous call.
* var jsonData = result.getValue();
* assertEquals('ok', jsonData['stat']);
* });
*
* // Attach the error handler to be called when either Result fails.
* goog.result.waitOnError(chainedResult, function(result) {
* alert('chained result failed!');
* });
* </pre>
*
* @param {!goog.result.Result} result The result to chain.
* @param {function(!goog.result.Result):!goog.result.Result}
* actionCallback The callback called when the result is resolved. This
* callback must return a Result.
*
* @return {!goog.result.DependentResult} A result that is resolved when both
* the given Result and the Result returned by the actionCallback have
* resolved.
*/
goog.result.chain = function(result, actionCallback) {
var dependentResult = new goog.result.DependentResultImpl_([result]);
// Wait for the first action.
goog.result.wait(result, function(result) {
if (result.getState() == goog.result.Result.State.SUCCESS) {
// The first action succeeded. Chain the contingent action.
var contingentResult = actionCallback(result);
dependentResult.addParentResult(contingentResult);
goog.result.wait(contingentResult, function(contingentResult) {
// The contingent action completed. Set the dependent result based on
// the contingent action's outcome.
if (contingentResult.getState() ==
goog.result.Result.State.SUCCESS) {
dependentResult.setValue(contingentResult.getValue());
} else {
dependentResult.setError(contingentResult.getError());
}
});
} else {
// First action failed, the dependent result should also fail.
dependentResult.setError(result.getError());
}
});
return dependentResult;
};
/**
* Returns a result that waits on all given results to resolve. Once all have
* resolved, the returned result will succeed (and never error).
*
* Example:
* <pre>
*
* var result1 = xhr.get('testdata/xhr_test_text.data');
*
* // Get a second independent Result.
* var result2 = xhr.getJson('testdata/xhr_test_json.data');
*
* // Create a Result that resolves when both prior results resolve.
* var combinedResult = goog.result.combine(result1, result2);
*
* // Process data after resolution of both results.
* goog.result.waitOnSuccess(combinedResult, function(results) {
* goog.array.forEach(results, function(result) {
* alert(result.getState());
* });
* });
* </pre>
*
* @param {...!goog.result.Result} var_args The results to wait on.
*
* @return {!goog.result.DependentResult} A new Result whose eventual value will
* be the resolved given Result objects.
*/
goog.result.combine = function(var_args) {
/** @type {!Array.<!goog.result.Result>} */
var results = goog.array.clone(arguments);
var combinedResult = new goog.result.DependentResultImpl_(results);
var isResolved = function(res) {
return res.getState() != goog.result.Result.State.PENDING;
};
var checkResults = function() {
if (combinedResult.getState() == goog.result.Result.State.PENDING &&
goog.array.every(results, isResolved)) {
combinedResult.setValue(results);
}
};
goog.array.forEach(results, function(result) {
goog.result.wait(result, checkResults);
});
return combinedResult;
};
/**
* Returns a result that waits on all given results to resolve. Once all have
* resolved, the returned result will succeed if and only if all given results
* succeeded. Otherwise it will error.
*
* Example:
* <pre>
*
* var result1 = xhr.get('testdata/xhr_test_text.data');
*
* // Get a second independent Result.
* var result2 = xhr.getJson('testdata/xhr_test_json.data');
*
* // Create a Result that resolves when both prior results resolve.
* var combinedResult = goog.result.combineOnSuccess(result1, result2);
*
* // Process data after successful resolution of both results.
* goog.result.waitOnSuccess(combinedResult, function(results) {
* var textData = results[0].getValue();
* var jsonData = results[1].getValue();
* assertEquals('Just some data.', textData);
* assertEquals('ok', jsonData['stat']);
* });
*
* // Handle errors when either or both results failed.
* goog.result.waitOnError(combinedResult, function(combined) {
* var results = combined.getError();
*
* if (results[0].getState() == goog.result.Result.State.ERROR) {
* alert('result1 failed');
* }
*
* if (results[1].getState() == goog.result.Result.State.ERROR) {
* alert('result2 failed');
* }
* });
* </pre>
*
* @param {...!goog.result.Result} var_args The results to wait on.
*
* @return {!goog.result.DependentResult} A new Result whose eventual value will
* be an array of values of the given Result objects.
*/
goog.result.combineOnSuccess = function(var_args) {
var results = goog.array.clone(arguments);
var combinedResult = new goog.result.DependentResultImpl_(results);
var resolvedSuccessfully = function(res) {
return res.getState() == goog.result.Result.State.SUCCESS;
};
goog.result.wait(
goog.result.combine.apply(goog.result.combine, results),
// The combined result never ERRORs
function(res) {
var results = /** @type {Array.<!goog.result.Result>} */ (
res.getValue());
if (goog.array.every(results, resolvedSuccessfully)) {
combinedResult.setValue(results);
} else {
combinedResult.setError(results);
}
});
return combinedResult;
};
/**
* Given a DependentResult, cancels the Results it depends on (that is, the
* results returned by getParentResults). This function does not recurse,
* so e.g. parents of parents are not canceled; only the immediate parents of
* the given Result are canceled.
*
* Example using @see goog.result.combine:
* <pre>
* var result1 = xhr.get('testdata/xhr_test_text.data');
*
* // Get a second independent Result.
* var result2 = xhr.getJson('testdata/xhr_test_json.data');
*
* // Create a Result that resolves when both prior results resolve.
* var combinedResult = goog.result.combineOnSuccess(result1, result2);
*
* combinedResult.wait(function() {
* if (combinedResult.isCanceled()) {
* goog.result.cancelParentResults(combinedResult);
* }
* });
*
* // Now, canceling combinedResult will cancel both result1 and result2.
* combinedResult.cancel();
* </pre>
* @param {!goog.result.DependentResult} dependentResult A Result that is
* dependent on the values of other Results (for example the Result of a
* goog.result.combine, goog.result.chain, or goog.result.transform call).
* @return {boolean} True if any results were successfully canceled; otherwise
* false.
* TODO(user): Implement a recursive version of this that cancels all
* ancestor results.
*/
goog.result.cancelParentResults = function(dependentResult) {
var anyCanceled = false;
goog.array.forEach(dependentResult.getParentResults(), function(result) {
anyCanceled |= result.cancel();
});
return !!anyCanceled;
};
/**
* A DependentResult represents a Result whose eventual value depends on the
* value of one or more other Results. For example, the Result returned by
* @see goog.result.chain or @see goog.result.combine is dependent on the
* Results given as arguments.
*
* @param {!Array.<!goog.result.Result>} parentResults A list of Results that
* will affect the eventual value of this Result.
* @constructor
* @implements {goog.result.DependentResult}
* @extends {goog.result.SimpleResult}
* @private
*/
goog.result.DependentResultImpl_ = function(parentResults) {
goog.base(this);
/**
* A list of Results that will affect the eventual value of this Result.
* @type {!Array.<!goog.result.Result>}
* @private
*/
this.parentResults_ = parentResults;
};
goog.inherits(goog.result.DependentResultImpl_, goog.result.SimpleResult);
/**
* Adds a Result to the list of Results that affect this one.
* @param {!goog.result.Result} parentResult A result whose value affects the
* value of this Result.
*/
goog.result.DependentResultImpl_.prototype.addParentResult = function(
parentResult) {
this.parentResults_.push(parentResult);
};
/** @override */
goog.result.DependentResultImpl_.prototype.getParentResults = function() {
return this.parentResults_;
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 An adaptor from a Result to a Deferred.
*
* TODO (vbhasin): cancel() support.
* TODO (vbhasin): See if we can make this a static.
* TODO (gboyer, vbhasin): Rename to "Adapter" once this graduates; this is the
* proper programmer spelling.
*/
goog.provide('goog.result.DeferredAdaptor');
goog.require('goog.async.Deferred');
goog.require('goog.result');
goog.require('goog.result.Result');
/**
* An adaptor from Result to a Deferred, for use with existing Deferred chains.
*
* @param {!goog.result.Result} result A result.
* @constructor
* @extends {goog.async.Deferred}
*/
goog.result.DeferredAdaptor = function(result) {
goog.base(this);
goog.result.wait(result, function(result) {
if (this.hasFired()) {
return;
}
if (result.getState() == goog.result.Result.State.SUCCESS) {
this.callback(result.getValue());
} else if (result.getState() == goog.result.Result.State.ERROR) {
if (result.getError() instanceof goog.result.Result.CancelError) {
this.cancel();
} else {
this.errback(result.getError());
}
}
}, this);
};
goog.inherits(goog.result.DeferredAdaptor, goog.async.Deferred);
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 An interface for Results whose eventual value depends on the
* value of one or more other Results.
*/
goog.provide('goog.result.DependentResult');
goog.require('goog.result.Result');
/**
* A DependentResult represents a Result whose eventual value depends on the
* value of one or more other Results. For example, the Result returned by
* @see goog.result.chain or @see goog.result.combine is dependent on the
* Results given as arguments.
* @interface
* @extends {goog.result.Result}
*/
goog.result.DependentResult = function() {};
/**
*
* @return {!Array.<!goog.result.Result>} A list of Results which will affect
* the eventual value of this Result. The returned Results may themselves
* have parent results, which would be grandparents of this Result;
* grandparents (and any other ancestors) are not included in this list.
*/
goog.result.DependentResult.prototype.getParentResults = function() {};
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 Definition of the disposable interface. A disposable object
* has a dispose method to to clean up references and resources.
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.disposable.IDisposable');
/**
* Interface for a disposable object. If a instance requires cleanup
* (references COM objects, DOM notes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
* @interface
*/
goog.disposable.IDisposable = function() {};
/**
* Disposes of the object and its resources.
* @return {void} Nothing.
*/
goog.disposable.IDisposable.prototype.dispose;
/**
* @return {boolean} Whether the object has been disposed of.
*/
goog.disposable.IDisposable.prototype.isDisposed;
| JavaScript |
// Copyright 2005 The Closure Library Authors. 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 Implements the disposable interface. The dispose method is used
* to clean up references and resources.
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.Disposable');
goog.provide('goog.dispose');
goog.require('goog.disposable.IDisposable');
/**
* Class that provides the basic implementation for disposable objects. If your
* class holds one or more references to COM objects, DOM nodes, or other
* disposable objects, it should extend this class or implement the disposable
* interface (defined in goog.disposable.IDisposable).
* @constructor
* @implements {goog.disposable.IDisposable}
*/
goog.Disposable = function() {
if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {
this.creationStack = new Error().stack;
goog.Disposable.instances_[goog.getUid(this)] = this;
}
};
/**
* @enum {number} Different monitoring modes for Disposable.
*/
goog.Disposable.MonitoringMode = {
/**
* No monitoring.
*/
OFF: 0,
/**
* Creating and disposing the goog.Disposable instances is monitored. All
* disposable objects need to call the {@code goog.Disposable} base
* constructor. The PERMANENT mode must bet switched on before creating any
* goog.Disposable instances.
*/
PERMANENT: 1,
/**
* INTERACTIVE mode can be switched on and off on the fly without producing
* errors. It also doesn't warn if the disposable objects don't call the
* {@code goog.Disposable} base constructor.
*/
INTERACTIVE: 2
};
/**
* @define {number} The monitoring mode of the goog.Disposable
* instances. Default is OFF. Switching on the monitoring is only
* recommended for debugging because it has a significant impact on
* performance and memory usage. If switched off, the monitoring code
* compiles down to 0 bytes.
*/
goog.Disposable.MONITORING_MODE = 0;
/**
* Maps the unique ID of every undisposed {@code goog.Disposable} object to
* the object itself.
* @type {!Object.<number, !goog.Disposable>}
* @private
*/
goog.Disposable.instances_ = {};
/**
* @return {!Array.<!goog.Disposable>} All {@code goog.Disposable} objects that
* haven't been disposed of.
*/
goog.Disposable.getUndisposedObjects = function() {
var ret = [];
for (var id in goog.Disposable.instances_) {
if (goog.Disposable.instances_.hasOwnProperty(id)) {
ret.push(goog.Disposable.instances_[Number(id)]);
}
}
return ret;
};
/**
* Clears the registry of undisposed objects but doesn't dispose of them.
*/
goog.Disposable.clearUndisposedObjects = function() {
goog.Disposable.instances_ = {};
};
/**
* Whether the object has been disposed of.
* @type {boolean}
* @private
*/
goog.Disposable.prototype.disposed_ = false;
/**
* Callbacks to invoke when this object is disposed.
* @type {Array.<!Function>}
* @private
*/
goog.Disposable.prototype.onDisposeCallbacks_;
/**
* If monitoring the goog.Disposable instances is enabled, stores the creation
* stack trace of the Disposable instance.
* @type {string}
*/
goog.Disposable.prototype.creationStack;
/**
* @return {boolean} Whether the object has been disposed of.
* @override
*/
goog.Disposable.prototype.isDisposed = function() {
return this.disposed_;
};
/**
* @return {boolean} Whether the object has been disposed of.
* @deprecated Use {@link #isDisposed} instead.
*/
goog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;
/**
* Disposes of the object. If the object hasn't already been disposed of, calls
* {@link #disposeInternal}. Classes that extend {@code goog.Disposable} should
* override {@link #disposeInternal} in order to delete references to COM
* objects, DOM nodes, and other disposable objects. Reentrant.
*
* @return {void} Nothing.
* @override
*/
goog.Disposable.prototype.dispose = function() {
if (!this.disposed_) {
// Set disposed_ to true first, in case during the chain of disposal this
// gets disposed recursively.
this.disposed_ = true;
this.disposeInternal();
if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {
var uid = goog.getUid(this);
if (goog.Disposable.MONITORING_MODE ==
goog.Disposable.MonitoringMode.PERMANENT &&
!goog.Disposable.instances_.hasOwnProperty(uid)) {
throw Error(this + ' did not call the goog.Disposable base ' +
'constructor or was disposed of after a clearUndisposedObjects ' +
'call');
}
delete goog.Disposable.instances_[uid];
}
}
};
/**
* Associates a disposable object with this object so that they will be disposed
* together.
* @param {goog.disposable.IDisposable} disposable that will be disposed when
* this object is disposed.
*/
goog.Disposable.prototype.registerDisposable = function(disposable) {
this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));
};
/**
* Invokes a callback function when this object is disposed. Callbacks are
* invoked in the order in which they were added.
* @param {function(this:T):?} callback The callback function.
* @param {T=} opt_scope An optional scope to call the callback in.
* @template T
*/
goog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {
if (!this.onDisposeCallbacks_) {
this.onDisposeCallbacks_ = [];
}
this.onDisposeCallbacks_.push(goog.bind(callback, opt_scope));
};
/**
* Deletes or nulls out any references to COM objects, DOM nodes, or other
* disposable objects. Classes that extend {@code goog.Disposable} should
* override this method.
* Not reentrant. To avoid calling it twice, it must only be called from the
* subclass' {@code disposeInternal} method. Everywhere else the public
* {@code dispose} method must be used.
* For example:
* <pre>
* mypackage.MyClass = function() {
* goog.base(this);
* // Constructor logic specific to MyClass.
* ...
* };
* goog.inherits(mypackage.MyClass, goog.Disposable);
*
* mypackage.MyClass.prototype.disposeInternal = function() {
* // Dispose logic specific to MyClass.
* ...
* // Call superclass's disposeInternal at the end of the subclass's, like
* // in C++, to avoid hard-to-catch issues.
* goog.base(this, 'disposeInternal');
* };
* </pre>
* @protected
*/
goog.Disposable.prototype.disposeInternal = function() {
if (this.onDisposeCallbacks_) {
while (this.onDisposeCallbacks_.length) {
this.onDisposeCallbacks_.shift()();
}
}
};
/**
* Returns True if we can verify the object is disposed.
* Calls {@code isDisposed} on the argument if it supports it. If obj
* is not an object with an isDisposed() method, return false.
* @param {*} obj The object to investigate.
* @return {boolean} True if we can verify the object is disposed.
*/
goog.Disposable.isDisposed = function(obj) {
if (obj && typeof obj.isDisposed == 'function') {
return obj.isDisposed();
}
return false;
};
/**
* Calls {@code dispose} on the argument if it supports it. If obj is not an
* object with a dispose() method, this is a no-op.
* @param {*} obj The object to dispose of.
*/
goog.dispose = function(obj) {
if (obj && typeof obj.dispose == 'function') {
obj.dispose();
}
};
/**
* Calls {@code dispose} on each member of the list that supports it. (If the
* member is an ArrayLike, then {@code goog.disposeAll()} will be called
* recursively on each of its members.) If the member is not an object with a
* {@code dispose()} method, then it is ignored.
* @param {...*} var_args The list.
*/
goog.disposeAll = function(var_args) {
for (var i = 0, len = arguments.length; i < len; ++i) {
var disposable = arguments[i];
if (goog.isArrayLike(disposable)) {
goog.disposeAll.apply(null, disposable);
} else {
goog.dispose(disposable);
}
}
};
| JavaScript |
// Copyright 2012 The Closure Library Authors. 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 Definition of goog.messaging.RespondingChannel, which wraps a
* MessageChannel and allows the user to get the response from the services.
*
*/
goog.provide('goog.messaging.RespondingChannel');
goog.require('goog.Disposable');
goog.require('goog.debug.Logger');
goog.require('goog.messaging.MessageChannel'); // interface
goog.require('goog.messaging.MultiChannel');
goog.require('goog.messaging.MultiChannel.VirtualChannel');
/**
* Creates a new RespondingChannel wrapping a single MessageChannel.
* @param {goog.messaging.MessageChannel} messageChannel The messageChannel to
* to wrap and allow for responses. This channel must not have any existing
* services registered. All service registration must be done through the
* {@link RespondingChannel#registerService} api instead. The other end of
* channel must also be a RespondingChannel.
* @constructor
* @extends {goog.Disposable}
*/
goog.messaging.RespondingChannel = function(messageChannel) {
goog.base(this);
/**
* The message channel wrapped in a MultiChannel so we can send private and
* public messages on it.
* @type {goog.messaging.MultiChannel}
* @private
*/
this.messageChannel_ = new goog.messaging.MultiChannel(messageChannel);
/**
* Map of invocation signatures to function callbacks. These are used to keep
* track of the asyncronous service invocations so the result of a service
* call can be passed back to a callback in the calling frame.
* @type {Object.<number, function(Object)>}
* @private
*/
this.sigCallbackMap_ = {};
/**
* The virtual channel to send private messages on.
* @type {goog.messaging.MultiChannel.VirtualChannel}
* @private
*/
this.privateChannel_ = this.messageChannel_.createVirtualChannel(
goog.messaging.RespondingChannel.PRIVATE_CHANNEL_);
/**
* The virtual channel to send public messages on.
* @type {goog.messaging.MultiChannel.VirtualChannel}
* @private
*/
this.publicChannel_ = this.messageChannel_.createVirtualChannel(
goog.messaging.RespondingChannel.PUBLIC_CHANNEL_);
this.privateChannel_.registerService(
goog.messaging.RespondingChannel.CALLBACK_SERVICE_,
goog.bind(this.callbackServiceHandler_, this),
true);
};
goog.inherits(goog.messaging.RespondingChannel, goog.Disposable);
/**
* The name of the method invocation callback service (used internally).
* @type {string}
* @const
* @private
*/
goog.messaging.RespondingChannel.CALLBACK_SERVICE_ = 'mics';
/**
* The name of the channel to send private control messages on.
* @type {string}
* @const
* @private
*/
goog.messaging.RespondingChannel.PRIVATE_CHANNEL_ = 'private';
/**
* The name of the channel to send public messages on.
* @type {string}
* @const
* @private
*/
goog.messaging.RespondingChannel.PUBLIC_CHANNEL_ = 'public';
/**
* The next signature index to save the callback against.
* @type {number}
* @private
*/
goog.messaging.RespondingChannel.prototype.nextSignatureIndex_ = 0;
/**
* Logger object for goog.messaging.RespondingChannel.
* @type {goog.debug.Logger}
* @private
*/
goog.messaging.RespondingChannel.prototype.logger_ =
goog.debug.Logger.getLogger('goog.messaging.RespondingChannel');
/**
* Gets a random number to use for method invocation results.
* @return {number} A unique random signature.
* @private
*/
goog.messaging.RespondingChannel.prototype.getNextSignature_ = function() {
return this.nextSignatureIndex_++;
};
/** @override */
goog.messaging.RespondingChannel.prototype.disposeInternal = function() {
goog.dispose(this.messageChannel_);
delete this.messageChannel_;
// Note: this.publicChannel_ and this.privateChannel_ get disposed by
// this.messageChannel_
delete this.publicChannel_;
delete this.privateChannel_;
};
/**
* Sends a message over the channel.
* @param {string} serviceName The name of the service this message should be
* delivered to.
* @param {string|!Object} payload The value of the message. If this is an
* Object, it is serialized to a string before sending if necessary.
* @param {function(?Object)} callback The callback invoked with
* the result of the service call.
*/
goog.messaging.RespondingChannel.prototype.send = function(
serviceName,
payload,
callback) {
var signature = this.getNextSignature_();
this.sigCallbackMap_[signature] = callback;
var message = {};
message['signature'] = signature;
message['data'] = payload;
this.publicChannel_.send(serviceName, message);
};
/**
* Receives the results of the peer's service results.
* @param {!Object|string} message The results from the remote service
* invocation.
* @private
*/
goog.messaging.RespondingChannel.prototype.callbackServiceHandler_ = function(
message) {
var signature = message['signature'];
var result = message['data'];
if (signature in this.sigCallbackMap_) {
var callback = /** @type {function(Object)} */ (this.sigCallbackMap_[
signature]);
callback(result);
delete this.sigCallbackMap_[signature];
} else {
this.logger_.warning('Received signature is invalid');
}
};
/**
* Registers a service to be called when a message is received.
* @param {string} serviceName The name of the service.
* @param {function(!Object)} callback The callback to process the
* incoming messages. Passed the payload.
*/
goog.messaging.RespondingChannel.prototype.registerService = function(
serviceName, callback) {
this.publicChannel_.registerService(
serviceName,
goog.bind(this.callbackProxy_, this, callback),
true);
};
/**
* A intermediary proxy for service callbacks to be invoked and return their
* their results to the remote caller's callback.
* @param {function((string|!Object))} callback The callback to process the
* incoming messages. Passed the payload.
* @param {!Object|string} message The message containing the signature and
* the data to invoke the service callback with.
* @private
*/
goog.messaging.RespondingChannel.prototype.callbackProxy_ = function(
callback, message) {
var resultMessage = {};
resultMessage['data'] = callback(message['data']);
resultMessage['signature'] = message['signature'];
// The callback invoked above may have disposed the channel so check if it
// exists.
if (this.privateChannel_) {
this.privateChannel_.send(
goog.messaging.RespondingChannel.CALLBACK_SERVICE_,
resultMessage);
}
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 MessageChannel decorator that wraps a deferred MessageChannel
* and enqueues messages and service registrations until that channel exists.
*
*/
goog.provide('goog.messaging.DeferredChannel');
goog.require('goog.Disposable');
goog.require('goog.async.Deferred');
goog.require('goog.messaging.MessageChannel'); // interface
/**
* Creates a new DeferredChannel, which wraps a deferred MessageChannel and
* enqueues messages to be sent once the wrapped channel is resolved.
*
* @param {!goog.async.Deferred} deferredChannel The underlying deferred
* MessageChannel.
* @constructor
* @extends {goog.Disposable}
* @implements {goog.messaging.MessageChannel}
*/
goog.messaging.DeferredChannel = function(deferredChannel) {
goog.base(this);
this.deferred_ = deferredChannel;
};
goog.inherits(goog.messaging.DeferredChannel, goog.Disposable);
/**
* Cancels the wrapped Deferred.
*/
goog.messaging.DeferredChannel.prototype.cancel = function() {
this.deferred_.cancel();
};
/** @override */
goog.messaging.DeferredChannel.prototype.connect = function(opt_connectCb) {
if (opt_connectCb) {
opt_connectCb();
}
};
/** @override */
goog.messaging.DeferredChannel.prototype.isConnected = function() {
return true;
};
/** @override */
goog.messaging.DeferredChannel.prototype.registerService = function(
serviceName, callback, opt_objectPayload) {
this.deferred_.addCallback(function(resolved) {
resolved.registerService(serviceName, callback, opt_objectPayload);
});
};
/** @override */
goog.messaging.DeferredChannel.prototype.registerDefaultService =
function(callback) {
this.deferred_.addCallback(function(resolved) {
resolved.registerDefaultService(callback);
});
};
/** @override */
goog.messaging.DeferredChannel.prototype.send = function(serviceName, payload) {
this.deferred_.addCallback(function(resolved) {
resolved.send(serviceName, payload);
});
};
/** @override */
goog.messaging.DeferredChannel.prototype.disposeInternal = function() {
this.cancel();
goog.base(this, 'disposeInternal');
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 class that wraps several types of HTML5 message-passing
* entities ({@link MessagePort}s, {@link WebWorker}s, and {@link Window}s),
* providing a unified interface.
*
* This is tested under Chrome, Safari, and Firefox. Since Firefox 3.6 has an
* incomplete implementation of web workers, it doesn't support sending ports
* over Window connections. IE has no web worker support at all, and so is
* unsupported by this class.
*
*/
goog.provide('goog.messaging.PortChannel');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.async.Deferred');
goog.require('goog.debug');
goog.require('goog.debug.Logger');
goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.json');
goog.require('goog.messaging.AbstractChannel');
goog.require('goog.messaging.DeferredChannel');
goog.require('goog.object');
goog.require('goog.string');
/**
* A wrapper for several types of HTML5 message-passing entities
* ({@link MessagePort}s and {@link WebWorker}s). This class implements the
* {@link goog.messaging.MessageChannel} interface.
*
* This class can be used in conjunction with other communication on the port.
* It sets {@link goog.messaging.PortChannel.FLAG} to true on all messages it
* sends.
*
* @param {!MessagePort|!WebWorker} underlyingPort The message-passing
* entity to wrap. If this is a {@link MessagePort}, it should be started.
* The remote end should also be wrapped in a PortChannel. This will be
* disposed along with the PortChannel; this means terminating it if it's a
* worker or removing it from the DOM if it's an iframe.
* @constructor
* @extends {goog.messaging.AbstractChannel}
*/
goog.messaging.PortChannel = function(underlyingPort) {
goog.base(this);
/**
* The wrapped message-passing entity.
* @type {!MessagePort|!WebWorker}
* @private
*/
this.port_ = underlyingPort;
/**
* The key for the event listener.
* @type {goog.events.Key}
* @private
*/
this.listenerKey_ = goog.events.listen(
this.port_, goog.events.EventType.MESSAGE, this.deliver_, false, this);
};
goog.inherits(goog.messaging.PortChannel, goog.messaging.AbstractChannel);
/**
* Create a PortChannel that communicates with a window embedded in the current
* page (e.g. an iframe contentWindow). The code within the window should call
* {@link forGlobalWindow} to establish the connection.
*
* It's possible to use this channel in conjunction with other messages to the
* embedded window. However, only one PortChannel should be used for a given
* window at a time.
*
* @param {!Window} window The window object to communicate with.
* @param {string} peerOrigin The expected origin of the window. See
* http://dev.w3.org/html5/postmsg/#dom-window-postmessage.
* @param {goog.Timer=} opt_timer The timer that regulates how often the initial
* connection message is attempted. This will be automatically disposed once
* the connection is established, or when the connection is cancelled.
* @return {!goog.messaging.DeferredChannel} The PortChannel. Although this is
* not actually an instance of the PortChannel class, it will behave like
* one in that MessagePorts may be sent across it. The DeferredChannel may
* be cancelled before a connection is established in order to abort the
* attempt to make a connection.
*/
goog.messaging.PortChannel.forEmbeddedWindow = function(
window, peerOrigin, opt_timer) {
var timer = opt_timer || new goog.Timer(50);
var disposeTimer = goog.partial(goog.dispose, timer);
var deferred = new goog.async.Deferred(disposeTimer);
deferred.addBoth(disposeTimer);
timer.start();
// Every tick, attempt to set up a connection by sending in one end of an
// HTML5 MessageChannel. If the inner window posts a response along a channel,
// then we'll use that channel to create the PortChannel.
//
// As per http://dev.w3.org/html5/postmsg/#ports-and-garbage-collection, any
// ports that are not ultimately used to set up the channel will be garbage
// collected (since there are no references in this context, and the remote
// context hasn't seen them).
goog.events.listen(timer, goog.Timer.TICK, function() {
var channel = new MessageChannel();
var gotMessage = function(e) {
channel.port1.removeEventListener(
goog.events.EventType.MESSAGE, gotMessage, true);
// If the connection has been cancelled, don't create the channel.
if (!timer.isDisposed()) {
deferred.callback(new goog.messaging.PortChannel(channel.port1));
}
};
channel.port1.start();
// Don't use goog.events because we don't want any lingering references to
// the ports to prevent them from getting GCed. Only modern browsers support
// these APIs anyway, so we don't need to worry about event API
// compatibility.
channel.port1.addEventListener(
goog.events.EventType.MESSAGE, gotMessage, true);
var msg = {};
msg[goog.messaging.PortChannel.FLAG] = true;
window.postMessage(msg, [channel.port2], peerOrigin);
});
return new goog.messaging.DeferredChannel(deferred);
};
/**
* Create a PortChannel that communicates with the document in which this window
* is embedded (e.g. within an iframe). The enclosing document should call
* {@link forEmbeddedWindow} to establish the connection.
*
* It's possible to use this channel in conjunction with other messages posted
* to the global window. However, only one PortChannel should be used for the
* global window at a time.
*
* @param {string} peerOrigin The expected origin of the enclosing document. See
* http://dev.w3.org/html5/postmsg/#dom-window-postmessage.
* @return {!goog.messaging.MessageChannel} The PortChannel. Although this may
* not actually be an instance of the PortChannel class, it will behave like
* one in that MessagePorts may be sent across it.
*/
goog.messaging.PortChannel.forGlobalWindow = function(peerOrigin) {
var deferred = new goog.async.Deferred();
// Wait for the external page to post a message containing the message port
// which we'll use to set up the PortChannel. Ignore all other messages. Once
// we receive the port, notify the other end and then set up the PortChannel.
var key = goog.events.listen(
window, goog.events.EventType.MESSAGE, function(e) {
var browserEvent = e.getBrowserEvent();
var data = browserEvent.data;
if (!goog.isObject(data) || !data[goog.messaging.PortChannel.FLAG]) {
return;
}
if (peerOrigin != '*' && peerOrigin != browserEvent.origin) {
return;
}
var port = browserEvent.ports[0];
// Notify the other end of the channel that we've received our port
port.postMessage({});
port.start();
deferred.callback(new goog.messaging.PortChannel(port));
goog.events.unlistenByKey(key);
});
return new goog.messaging.DeferredChannel(deferred);
};
/**
* The flag added to messages that are sent by a PortChannel, and are meant to
* be handled by one on the other side.
* @type {string}
*/
goog.messaging.PortChannel.FLAG = '--goog.messaging.PortChannel';
/**
* Whether the messages sent across the channel must be JSON-serialized. This is
* required for older versions of Webkit, which can only send string messages.
*
* Although Safari and Chrome have separate implementations of message passing,
* both of them support passing objects by Webkit 533.
*
* @type {boolean}
* @private
*/
goog.messaging.PortChannel.REQUIRES_SERIALIZATION_ = goog.userAgent.WEBKIT &&
goog.string.compareVersions(goog.userAgent.VERSION, '533') < 0;
/**
* Logger for this class.
* @type {goog.debug.Logger}
* @protected
* @override
*/
goog.messaging.PortChannel.prototype.logger =
goog.debug.Logger.getLogger('goog.messaging.PortChannel');
/**
* Sends a message over the channel.
*
* As an addition to the basic MessageChannel send API, PortChannels can send
* objects that contain MessagePorts. Note that only plain Objects and Arrays,
* not their subclasses, can contain MessagePorts.
*
* As per {@link http://www.w3.org/TR/html5/comms.html#clone-a-port}, once a
* port is copied to be sent across a channel, the original port will cease
* being able to send or receive messages.
*
* @override
* @param {string} serviceName The name of the service this message should be
* delivered to.
* @param {string|!Object|!MessagePort} payload The value of the message. May
* contain MessagePorts or be a MessagePort.
*/
goog.messaging.PortChannel.prototype.send = function(serviceName, payload) {
var ports = [];
payload = this.extractPorts_(ports, payload);
var message = {'serviceName': serviceName, 'payload': payload};
message[goog.messaging.PortChannel.FLAG] = true;
if (goog.messaging.PortChannel.REQUIRES_SERIALIZATION_) {
message = goog.json.serialize(message);
}
this.port_.postMessage(message, ports);
};
/**
* Delivers a message to the appropriate service handler. If this message isn't
* a GearsWorkerChannel message, it's ignored and passed on to other handlers.
*
* @param {goog.events.Event} e The event.
* @private
*/
goog.messaging.PortChannel.prototype.deliver_ = function(e) {
var browserEvent = e.getBrowserEvent();
var data = browserEvent.data;
if (goog.messaging.PortChannel.REQUIRES_SERIALIZATION_) {
try {
data = goog.json.parse(data);
} catch (error) {
// Ignore any non-JSON messages.
return;
}
}
if (!goog.isObject(data) || !data[goog.messaging.PortChannel.FLAG]) {
return;
}
if (this.validateMessage_(data)) {
var serviceName = data['serviceName'];
var payload = data['payload'];
var service = this.getService(serviceName, payload);
if (!service) {
return;
}
payload = this.decodePayload(
serviceName,
this.injectPorts_(browserEvent.ports || [], payload),
service.objectPayload);
if (goog.isDefAndNotNull(payload)) {
service.callback(payload);
}
}
};
/**
* Checks whether the message is invalid in some way.
*
* @param {Object} data The contents of the message.
* @return {boolean} True if the message is valid, false otherwise.
* @private
*/
goog.messaging.PortChannel.prototype.validateMessage_ = function(data) {
if (!('serviceName' in data)) {
this.logger.warning('Message object doesn\'t contain service name: ' +
goog.debug.deepExpose(data));
return false;
}
if (!('payload' in data)) {
this.logger.warning('Message object doesn\'t contain payload: ' +
goog.debug.deepExpose(data));
return false;
}
return true;
};
/**
* Extracts all MessagePort objects from a message to be sent into an array.
*
* The message ports are replaced by placeholder objects that will be replaced
* with the ports again on the other side of the channel.
*
* @param {Array.<MessagePort>} ports The array that will contain ports
* extracted from the message. Will be destructively modified. Should be
* empty initially.
* @param {string|!Object} message The message from which ports will be
* extracted.
* @return {string|!Object} The message with ports extracted.
* @private
*/
goog.messaging.PortChannel.prototype.extractPorts_ = function(ports, message) {
// Can't use instanceof here because MessagePort is undefined in workers
if (message &&
Object.prototype.toString.call(/** @type {!Object} */ (message)) ==
'[object MessagePort]') {
ports.push(message);
return {'_port': {'type': 'real', 'index': ports.length - 1}};
} else if (goog.isArray(message)) {
return goog.array.map(message, goog.bind(this.extractPorts_, this, ports));
// We want to compare the exact constructor here because we only want to
// recurse into object literals, not native objects like Date.
} else if (message && message.constructor == Object) {
return goog.object.map(/** @type {Object} */ (message), function(val, key) {
val = this.extractPorts_(ports, val);
return key == '_port' ? {'type': 'escaped', 'val': val} : val;
}, this);
} else {
return message;
}
};
/**
* Injects MessagePorts back into a message received from across the channel.
*
* @param {Array.<MessagePort>} ports The array of ports to be injected into the
* message.
* @param {string|!Object} message The message into which the ports will be
* injected.
* @return {string|!Object} The message with ports injected.
* @private
*/
goog.messaging.PortChannel.prototype.injectPorts_ = function(ports, message) {
if (goog.isArray(message)) {
return goog.array.map(message, goog.bind(this.injectPorts_, this, ports));
} else if (message && message.constructor == Object) {
message = /** @type {!Object} */ (message);
if (message['_port'] && message['_port']['type'] == 'real') {
return /** @type {!MessagePort} */ (ports[message['_port']['index']]);
}
return goog.object.map(message, function(val, key) {
return this.injectPorts_(ports, key == '_port' ? val['val'] : val);
}, this);
} else {
return message;
}
};
/** @override */
goog.messaging.PortChannel.prototype.disposeInternal = function() {
goog.events.unlistenByKey(this.listenerKey_);
// Can't use instanceof here because MessagePort is undefined in workers and
// in Firefox
if (Object.prototype.toString.call(this.port_) == '[object MessagePort]') {
this.port_.close();
// Worker is undefined in workers as well as of Chrome 9
} else if (Object.prototype.toString.call(this.port_) == '[object Worker]') {
this.port_.terminate();
}
delete this.port_;
goog.base(this, 'disposeInternal');
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 leaf node of a {@link goog.messaging.PortNetwork}. Callers
* connect to the operator, and request connections with other contexts from it.
*
*/
goog.provide('goog.messaging.PortCaller');
goog.require('goog.Disposable');
goog.require('goog.async.Deferred');
goog.require('goog.messaging.DeferredChannel');
goog.require('goog.messaging.PortChannel');
goog.require('goog.messaging.PortNetwork'); // interface
goog.require('goog.object');
/**
* The leaf node of a network.
*
* @param {!goog.messaging.MessageChannel} operatorPort The channel for
* communicating with the operator. The other side of this channel should be
* passed to {@link goog.messaging.PortOperator#addPort}. Must be either a
* {@link goog.messaging.PortChannel} or a decorator wrapping a PortChannel;
* in particular, it must be able to send and receive {@link MessagePort}s.
* @constructor
* @extends {goog.Disposable}
* @implements {goog.messaging.PortNetwork}
*/
goog.messaging.PortCaller = function(operatorPort) {
goog.base(this);
/**
* The channel to the {@link goog.messaging.PortOperator} for this network.
*
* @type {!goog.messaging.MessageChannel}
* @private
*/
this.operatorPort_ = operatorPort;
/**
* The collection of channels for communicating with other contexts in the
* network. Each value can contain a {@link goog.aync.Deferred} and/or a
* {@link goog.messaging.MessageChannel}.
*
* If the value contains a Deferred, then the channel is a
* {@link goog.messaging.DeferredChannel} wrapping that Deferred. The Deferred
* will be resolved with a {@link goog.messaging.PortChannel} once we receive
* the appropriate port from the operator. This is the situation when this
* caller requests a connection to another context; the DeferredChannel is
* used to queue up messages until we receive the port from the operator.
*
* If the value does not contain a Deferred, then the channel is simply a
* {@link goog.messaging.PortChannel} communicating with the given context.
* This is the situation when this context received a port for the other
* context before it was requested.
*
* If a value exists for a given key, it must contain a channel, but it
* doesn't necessarily contain a Deferred.
*
* @type {!Object.<{deferred: goog.async.Deferred,
* channel: !goog.messaging.MessageChannel}>}
* @private
*/
this.connections_ = {};
this.operatorPort_.registerService(
goog.messaging.PortNetwork.GRANT_CONNECTION_SERVICE,
goog.bind(this.connectionGranted_, this),
true /* opt_json */);
};
goog.inherits(goog.messaging.PortCaller, goog.Disposable);
/** @override */
goog.messaging.PortCaller.prototype.dial = function(name) {
if (name in this.connections_) {
return this.connections_[name].channel;
}
this.operatorPort_.send(
goog.messaging.PortNetwork.REQUEST_CONNECTION_SERVICE, name);
var deferred = new goog.async.Deferred();
var channel = new goog.messaging.DeferredChannel(deferred);
this.connections_[name] = {deferred: deferred, channel: channel};
return channel;
};
/**
* Registers a connection to another context in the network. This is called when
* the operator sends us one end of a {@link MessageChannel}, either because
* this caller requested a connection with another context, or because that
* context requested a connection with this caller.
*
* It's possible that the remote context and this one request each other roughly
* concurrently. The operator doesn't keep track of which contexts have been
* connected, so it will create two separate {@link MessageChannel}s in this
* case. However, the first channel created will reach both contexts first, so
* we simply ignore all connections with a given context after the first.
*
* @param {!Object|string} message The name of the context
* being connected and the port connecting the context.
* @private
*/
goog.messaging.PortCaller.prototype.connectionGranted_ = function(message) {
var args = /** @type {{name: string, port: MessagePort}} */ (message);
var port = args['port'];
var entry = this.connections_[args['name']];
if (entry && (!entry.deferred || entry.deferred.hasFired())) {
// If two PortCallers request one another at the same time, the operator may
// send out a channel for connecting them multiple times. Since both callers
// will receive the first channel's ports first, we can safely ignore and
// close any future ports.
port.close();
} else if (!args['success']) {
throw Error(args['message']);
} else {
port.start();
var channel = new goog.messaging.PortChannel(port);
if (entry) {
entry.deferred.callback(channel);
} else {
this.connections_[args['name']] = {channel: channel, deferred: null};
}
}
};
/** @override */
goog.messaging.PortCaller.prototype.disposeInternal = function() {
goog.dispose(this.operatorPort_);
goog.object.forEach(this.connections_, goog.dispose);
delete this.operatorPort_;
delete this.connections_;
goog.base(this, 'disposeInternal');
};
| JavaScript |
// Copyright 2010 The Closure Library Authors. 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 Functions for manipulating message channels.
*
*/
goog.provide('goog.messaging');
goog.require('goog.messaging.MessageChannel');
/**
* Creates a bidirectional pipe between two message channels.
*
* @param {goog.messaging.MessageChannel} channel1 The first channel.
* @param {goog.messaging.MessageChannel} channel2 The second channel.
*/
goog.messaging.pipe = function(channel1, channel2) {
channel1.registerDefaultService(goog.bind(channel2.send, channel2));
channel2.registerDefaultService(goog.bind(channel1.send, channel1));
};
| JavaScript |
// Copyright 2011 The Closure Library Authors. 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 An interface for classes that connect a collection of HTML5
* message-passing entities ({@link MessagePort}s, {@link Worker}s, and
* {@link Window}s) and allow them to seamlessly communicate with one another.
*
* Conceptually, a PortNetwork is a collection of JS contexts, such as pages (in
* or outside of iframes) or web workers. Each context has a unique name, and
* each one can communicate with any of the others in the same network. This
* communication takes place through a {@link goog.messaging.PortChannel} that
* is retrieved via {#link goog.messaging.PortNetwork#dial}.
*
* One context (usually the main page) has a
* {@link goog.messaging.PortOperator}, which is in charge of connecting each
* context to each other context. All other contexts have
* {@link goog.messaging.PortCaller}s which connect to the operator.
*
*/
goog.provide('goog.messaging.PortNetwork');
/**
* @interface
*/
goog.messaging.PortNetwork = function() {};
/**
* Returns a message channel that communicates with the named context. If no
* such port exists, an error will either be thrown immediately or after a round
* trip with the operator, depending on whether this pool is the operator or a
* caller.
*
* If context A calls dial('B') and context B calls dial('A'), the two
* ports returned will be connected to one another.
*
* @param {string} name The name of the context to get.
* @return {goog.messaging.MessageChannel} The channel communicating with the
* given context. This is either a {@link goog.messaging.PortChannel} or a
* decorator around a PortChannel, so it's safe to send {@link MessagePorts}
* across it. This will be disposed along with the PortNetwork.
*/
goog.messaging.PortNetwork.prototype.dial = function(name) {};
/**
* The name of the service exported by the operator for creating a connection
* between two callers.
*
* @type {string}
* @const
*/
goog.messaging.PortNetwork.REQUEST_CONNECTION_SERVICE = 'requestConnection';
/**
* The name of the service exported by the callers for adding a connection to
* another context.
*
* @type {string}
* @const
*/
goog.messaging.PortNetwork.GRANT_CONNECTION_SERVICE = 'grantConnection';
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.