fix bugs in page
This commit is contained in:
1 parent
6ed638a1cc
commit
e654fdfea6
387 files changed
+13618
-88879
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,369 @@
|
||||
// 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 to check the preconditions, postconditions and
|
||||
* invariants runtime.
|
||||
*
|
||||
* Methods in this package should be given special treatment by the compiler
|
||||
* for type-inference. For example, <code>goog.asserts.assert(foo)</code>
|
||||
* will restrict <code>foo</code> to a truthy value.
|
||||
*
|
||||
* The compiler has an option to disable asserts. So code like:
|
||||
* <code>
|
||||
* var x = goog.asserts.assert(foo()); goog.asserts.assert(bar());
|
||||
* </code>
|
||||
* will be transformed into:
|
||||
* <code>
|
||||
* var x = foo();
|
||||
* </code>
|
||||
* The compiler will leave in foo() (because its return value is used),
|
||||
* but it will remove bar() because it assumes it does not have side-effects.
|
||||
*
|
||||
* @author agrieve@google.com (Andrew Grieve)
|
||||
*/
|
||||
|
||||
goog.provide('goog.asserts');
|
||||
goog.provide('goog.asserts.AssertionError');
|
||||
|
||||
goog.require('goog.debug.Error');
|
||||
goog.require('goog.dom.NodeType');
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether to strip out asserts or to leave them in.
|
||||
*/
|
||||
goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Error object for failed assertions.
|
||||
* @param {string} messagePattern The pattern that was used to form message.
|
||||
* @param {!Array<*>} messageArgs The items to substitute into the pattern.
|
||||
* @constructor
|
||||
* @extends {goog.debug.Error}
|
||||
* @final
|
||||
*/
|
||||
goog.asserts.AssertionError = function(messagePattern, messageArgs) {
|
||||
messageArgs.unshift(messagePattern);
|
||||
goog.debug.Error.call(this, goog.string.subs.apply(null, messageArgs));
|
||||
// Remove the messagePattern afterwards to avoid permanently modifying the
|
||||
// passed in array.
|
||||
messageArgs.shift();
|
||||
|
||||
/**
|
||||
* The message pattern used to format the error message. Error handlers can
|
||||
* use this to uniquely identify the assertion.
|
||||
* @type {string}
|
||||
*/
|
||||
this.messagePattern = messagePattern;
|
||||
};
|
||||
goog.inherits(goog.asserts.AssertionError, goog.debug.Error);
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.asserts.AssertionError.prototype.name = 'AssertionError';
|
||||
|
||||
|
||||
/**
|
||||
* The default error handler.
|
||||
* @param {!goog.asserts.AssertionError} e The exception to be handled.
|
||||
*/
|
||||
goog.asserts.DEFAULT_ERROR_HANDLER = function(e) {
|
||||
throw e;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The handler responsible for throwing or logging assertion errors.
|
||||
* @private {function(!goog.asserts.AssertionError)}
|
||||
*/
|
||||
goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;
|
||||
|
||||
|
||||
/**
|
||||
* Throws an exception with the given message and "Assertion failed" prefixed
|
||||
* onto it.
|
||||
* @param {string} defaultMessage The message to use if givenMessage is empty.
|
||||
* @param {Array<*>} defaultArgs The substitution arguments for defaultMessage.
|
||||
* @param {string|undefined} givenMessage Message supplied by the caller.
|
||||
* @param {Array<*>} givenArgs The substitution arguments for givenMessage.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not a number.
|
||||
* @private
|
||||
*/
|
||||
goog.asserts.doAssertFailure_ = function(
|
||||
defaultMessage, defaultArgs, givenMessage, givenArgs) {
|
||||
var message = 'Assertion failed';
|
||||
if (givenMessage) {
|
||||
message += ': ' + givenMessage;
|
||||
var args = givenArgs;
|
||||
} else if (defaultMessage) {
|
||||
message += ': ' + defaultMessage;
|
||||
args = defaultArgs;
|
||||
}
|
||||
// The '' + works around an Opera 10 bug in the unit tests. Without it,
|
||||
// a stack trace is added to var message above. With this, a stack trace is
|
||||
// not added until this line (it causes the extra garbage to be added after
|
||||
// the assertion message instead of in the middle of it).
|
||||
var e = new goog.asserts.AssertionError('' + message, args || []);
|
||||
goog.asserts.errorHandler_(e);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets a custom error handler that can be used to customize the behavior of
|
||||
* assertion failures, for example by turning all assertion failures into log
|
||||
* messages.
|
||||
* @param {function(!goog.asserts.AssertionError)} errorHandler
|
||||
*/
|
||||
goog.asserts.setErrorHandler = function(errorHandler) {
|
||||
if (goog.asserts.ENABLE_ASSERTS) {
|
||||
goog.asserts.errorHandler_ = errorHandler;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is
|
||||
* true.
|
||||
* @template T
|
||||
* @param {T} condition The condition to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {T} The value of the condition.
|
||||
* @throws {goog.asserts.AssertionError} When the condition evaluates to false.
|
||||
*/
|
||||
goog.asserts.assert = function(condition, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !condition) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'', null, opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return condition;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case
|
||||
* when we want to add a check in the unreachable area like switch-case
|
||||
* statement:
|
||||
*
|
||||
* <pre>
|
||||
* switch(type) {
|
||||
* case FOO: doSomething(); break;
|
||||
* case BAR: doSomethingElse(); break;
|
||||
* default: goog.asserts.fail('Unrecognized type: ' + type);
|
||||
* // We have only 2 types - "default:" section is unreachable code.
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @throws {goog.asserts.AssertionError} Failure.
|
||||
*/
|
||||
goog.asserts.fail = function(opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS) {
|
||||
goog.asserts.errorHandler_(
|
||||
new goog.asserts.AssertionError(
|
||||
'Failure' + (opt_message ? ': ' + opt_message : ''),
|
||||
Array.prototype.slice.call(arguments, 1)));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {number} The value, guaranteed to be a number when asserts enabled.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not a number.
|
||||
*/
|
||||
goog.asserts.assertNumber = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected number but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {number} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {string} The value, guaranteed to be a string when asserts enabled.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not a string.
|
||||
*/
|
||||
goog.asserts.assertString = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected string but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {string} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {!Function} The value, guaranteed to be a function when asserts
|
||||
* enabled.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not a function.
|
||||
*/
|
||||
goog.asserts.assertFunction = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected function but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {!Function} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {!Object} The value, guaranteed to be a non-null object.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not an object.
|
||||
*/
|
||||
goog.asserts.assertObject = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected object but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {!Object} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {!Array<?>} The value, guaranteed to be a non-null array.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not an array.
|
||||
*/
|
||||
goog.asserts.assertArray = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected array but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {!Array<?>} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {boolean} The value, guaranteed to be a boolean when asserts are
|
||||
* enabled.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not a boolean.
|
||||
*/
|
||||
goog.asserts.assertBoolean = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected boolean but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {boolean} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.
|
||||
* @param {*} value The value to check.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @return {!Element} The value, likely to be a DOM Element when asserts are
|
||||
* enabled.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not an Element.
|
||||
*/
|
||||
goog.asserts.assertElement = function(value, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS &&
|
||||
(!goog.isObject(value) || value.nodeType != goog.dom.NodeType.ELEMENT)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected Element but got %s: %s.', [goog.typeOf(value), value],
|
||||
opt_message, Array.prototype.slice.call(arguments, 2));
|
||||
}
|
||||
return /** @type {!Element} */ (value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the value is an instance of the user-defined type if
|
||||
* goog.asserts.ENABLE_ASSERTS is true.
|
||||
*
|
||||
* The compiler may tighten the type returned by this function.
|
||||
*
|
||||
* @param {?} value The value to check.
|
||||
* @param {function(new: T, ...)} type A user-defined constructor.
|
||||
* @param {string=} opt_message Error message in case of failure.
|
||||
* @param {...*} var_args The items to substitute into the failure message.
|
||||
* @throws {goog.asserts.AssertionError} When the value is not an instance of
|
||||
* type.
|
||||
* @return {T}
|
||||
* @template T
|
||||
*/
|
||||
goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {
|
||||
if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {
|
||||
goog.asserts.doAssertFailure_(
|
||||
'Expected instanceof %s but got %s.',
|
||||
[goog.asserts.getType_(type), goog.asserts.getType_(value)],
|
||||
opt_message, Array.prototype.slice.call(arguments, 3));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Checks that no enumerable keys are present in Object.prototype. Such keys
|
||||
* would break most code that use {@code for (var ... in ...)} loops.
|
||||
*/
|
||||
goog.asserts.assertObjectPrototypeIsIntact = function() {
|
||||
for (var key in Object.prototype) {
|
||||
goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the type of a value. If a constructor is passed, and a suitable
|
||||
* string cannot be found, 'unknown type name' will be returned.
|
||||
* @param {*} value A constructor, object, or primitive.
|
||||
* @return {string} The best display name for the value, or 'unknown type name'.
|
||||
* @private
|
||||
*/
|
||||
goog.asserts.getType_ = function(value) {
|
||||
if (value instanceof Function) {
|
||||
return value.displayName || value.name || 'unknown type name';
|
||||
} else if (value instanceof Object) {
|
||||
return value.constructor.displayName || value.constructor.name ||
|
||||
Object.prototype.toString.call(value);
|
||||
} else {
|
||||
return value === null ? 'null' : typeof value;
|
||||
}
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,159 @@
|
||||
// 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 global registry for entry points into a program,
|
||||
* so that they can be instrumented. Each module should register their
|
||||
* entry points with this registry. Designed to be compiled out
|
||||
* if no instrumentation is requested.
|
||||
*
|
||||
* Entry points may be registered before or after a call to
|
||||
* goog.debug.entryPointRegistry.monitorAll. If an entry point is registered
|
||||
* later, the existing monitor will instrument the new entry point.
|
||||
*
|
||||
* @author nicksantos@google.com (Nick Santos)
|
||||
*/
|
||||
|
||||
goog.provide('goog.debug.EntryPointMonitor');
|
||||
goog.provide('goog.debug.entryPointRegistry');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
goog.debug.EntryPointMonitor = function() {};
|
||||
|
||||
|
||||
/**
|
||||
* Instruments a function.
|
||||
*
|
||||
* @param {!Function} fn A function to instrument.
|
||||
* @return {!Function} The instrumented function.
|
||||
*/
|
||||
goog.debug.EntryPointMonitor.prototype.wrap;
|
||||
|
||||
|
||||
/**
|
||||
* Try to remove an instrumentation wrapper created by this monitor.
|
||||
* If the function passed to unwrap is not a wrapper created by this
|
||||
* monitor, then we will do nothing.
|
||||
*
|
||||
* Notice that some wrappers may not be unwrappable. For example, if other
|
||||
* monitors have applied their own wrappers, then it will be impossible to
|
||||
* unwrap them because their wrappers will have captured our wrapper.
|
||||
*
|
||||
* So it is important that entry points are unwrapped in the reverse
|
||||
* order that they were wrapped.
|
||||
*
|
||||
* @param {!Function} fn A function to unwrap.
|
||||
* @return {!Function} The unwrapped function, or {@code fn} if it was not
|
||||
* a wrapped function created by this monitor.
|
||||
*/
|
||||
goog.debug.EntryPointMonitor.prototype.unwrap;
|
||||
|
||||
|
||||
/**
|
||||
* An array of entry point callbacks.
|
||||
* @type {!Array<function(!Function)>}
|
||||
* @private
|
||||
*/
|
||||
goog.debug.entryPointRegistry.refList_ = [];
|
||||
|
||||
|
||||
/**
|
||||
* Monitors that should wrap all the entry points.
|
||||
* @type {!Array<!goog.debug.EntryPointMonitor>}
|
||||
* @private
|
||||
*/
|
||||
goog.debug.entryPointRegistry.monitors_ = [];
|
||||
|
||||
|
||||
/**
|
||||
* Whether goog.debug.entryPointRegistry.monitorAll has ever been called.
|
||||
* Checking this allows the compiler to optimize out the registrations.
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.debug.entryPointRegistry.monitorsMayExist_ = false;
|
||||
|
||||
|
||||
/**
|
||||
* Register an entry point with this module.
|
||||
*
|
||||
* The entry point will be instrumented when a monitor is passed to
|
||||
* goog.debug.entryPointRegistry.monitorAll. If this has already occurred, the
|
||||
* entry point is instrumented immediately.
|
||||
*
|
||||
* @param {function(!Function)} callback A callback function which is called
|
||||
* with a transforming function to instrument the entry point. The callback
|
||||
* is responsible for wrapping the relevant entry point with the
|
||||
* transforming function.
|
||||
*/
|
||||
goog.debug.entryPointRegistry.register = function(callback) {
|
||||
// Don't use push(), so that this can be compiled out.
|
||||
goog.debug.entryPointRegistry
|
||||
.refList_[goog.debug.entryPointRegistry.refList_.length] = callback;
|
||||
// If no one calls monitorAll, this can be compiled out.
|
||||
if (goog.debug.entryPointRegistry.monitorsMayExist_) {
|
||||
var monitors = goog.debug.entryPointRegistry.monitors_;
|
||||
for (var i = 0; i < monitors.length; i++) {
|
||||
callback(goog.bind(monitors[i].wrap, monitors[i]));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Configures a monitor to wrap all entry points.
|
||||
*
|
||||
* Entry points that have already been registered are immediately wrapped by
|
||||
* the monitor. When an entry point is registered in the future, it will also
|
||||
* be wrapped by the monitor when it is registered.
|
||||
*
|
||||
* @param {!goog.debug.EntryPointMonitor} monitor An entry point monitor.
|
||||
*/
|
||||
goog.debug.entryPointRegistry.monitorAll = function(monitor) {
|
||||
goog.debug.entryPointRegistry.monitorsMayExist_ = true;
|
||||
var transformer = goog.bind(monitor.wrap, monitor);
|
||||
for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) {
|
||||
goog.debug.entryPointRegistry.refList_[i](transformer);
|
||||
}
|
||||
goog.debug.entryPointRegistry.monitors_.push(monitor);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Try to unmonitor all the entry points that have already been registered. If
|
||||
* an entry point is registered in the future, it will not be wrapped by the
|
||||
* monitor when it is registered. Note that this may fail if the entry points
|
||||
* have additional wrapping.
|
||||
*
|
||||
* @param {!goog.debug.EntryPointMonitor} monitor The last monitor to wrap
|
||||
* the entry points.
|
||||
* @throws {Error} If the monitor is not the most recently configured monitor.
|
||||
*/
|
||||
goog.debug.entryPointRegistry.unmonitorAllIfPossible = function(monitor) {
|
||||
var monitors = goog.debug.entryPointRegistry.monitors_;
|
||||
goog.asserts.assert(
|
||||
monitor == monitors[monitors.length - 1],
|
||||
'Only the most recent monitor can be unwrapped.');
|
||||
var transformer = goog.bind(monitor.unwrap, monitor);
|
||||
for (var i = 0; i < goog.debug.entryPointRegistry.refList_.length; i++) {
|
||||
goog.debug.entryPointRegistry.refList_[i](transformer);
|
||||
}
|
||||
monitors.length--;
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
// 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 Provides a base class for custom Error objects such that the
|
||||
* stack is correctly maintained.
|
||||
*
|
||||
* You should never need to throw goog.debug.Error(msg) directly, Error(msg) is
|
||||
* sufficient.
|
||||
*
|
||||
*/
|
||||
|
||||
goog.provide('goog.debug.Error');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Base class for custom error objects.
|
||||
* @param {*=} opt_msg The message associated with the error.
|
||||
* @constructor
|
||||
* @extends {Error}
|
||||
*/
|
||||
goog.debug.Error = function(opt_msg) {
|
||||
|
||||
// Attempt to ensure there is a stack trace.
|
||||
if (Error.captureStackTrace) {
|
||||
Error.captureStackTrace(this, goog.debug.Error);
|
||||
} else {
|
||||
var stack = new Error().stack;
|
||||
if (stack) {
|
||||
this.stack = stack;
|
||||
}
|
||||
}
|
||||
|
||||
if (opt_msg) {
|
||||
this.message = String(opt_msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to report this error to the server. Setting this to false will
|
||||
* cause the error reporter to not report the error back to the server,
|
||||
* which can be useful if the client knows that the error has already been
|
||||
* logged on the server.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.reportErrorToServer = true;
|
||||
};
|
||||
goog.inherits(goog.debug.Error, Error);
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.debug.Error.prototype.name = 'CustomError';
|
||||
@@ -0,0 +1,305 @@
|
||||
// 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.provide('goog.disposeAll');
|
||||
|
||||
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 monitoring the goog.Disposable instances is enabled, stores the creation
|
||||
* stack trace of the Disposable instance.
|
||||
* @type {string|undefined}
|
||||
*/
|
||||
this.creationStack;
|
||||
|
||||
if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {
|
||||
if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {
|
||||
this.creationStack = new Error().stack;
|
||||
}
|
||||
goog.Disposable.instances_[goog.getUid(this)] = this;
|
||||
}
|
||||
// Support sealing
|
||||
this.disposed_ = this.disposed_;
|
||||
this.onDisposeCallbacks_ = this.onDisposeCallbacks_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @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 be 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.define('goog.Disposable.MONITORING_MODE', 0);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether to attach creation stack to each created disposable
|
||||
* instance; This is only relevant for when MonitoringMode != OFF.
|
||||
*/
|
||||
goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);
|
||||
|
||||
|
||||
/**
|
||||
* 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_;
|
||||
|
||||
|
||||
/**
|
||||
* @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. If a callback is added to
|
||||
* an already disposed Disposable, it will be called immediately.
|
||||
* @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.disposed_) {
|
||||
goog.isDef(opt_scope) ? callback.call(opt_scope) : callback();
|
||||
return;
|
||||
}
|
||||
if (!this.onDisposeCallbacks_) {
|
||||
this.onDisposeCallbacks_ = [];
|
||||
}
|
||||
|
||||
this.onDisposeCallbacks_.push(
|
||||
goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
* mypackage.MyClass.base(this, 'constructor');
|
||||
* // 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.
|
||||
* mypackage.MyClass.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);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// 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 nodes, or other disposable objects), it should
|
||||
* implement this interface (it may subclass goog.Disposable).
|
||||
* @record
|
||||
*/
|
||||
goog.disposable.IDisposable = function() {};
|
||||
|
||||
|
||||
/**
|
||||
* Disposes of the object and its resources.
|
||||
* @return {void} Nothing.
|
||||
*/
|
||||
goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the object has been disposed of.
|
||||
*/
|
||||
goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
|
||||
@@ -0,0 +1,48 @@
|
||||
// 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 Definition of goog.dom.NodeType.
|
||||
*/
|
||||
|
||||
goog.provide('goog.dom.NodeType');
|
||||
|
||||
|
||||
/**
|
||||
* Constants for the nodeType attribute in the Node interface.
|
||||
*
|
||||
* These constants match those specified in the Node interface. These are
|
||||
* usually present on the Node object in recent browsers, but not in older
|
||||
* browsers (specifically, early IEs) and thus are given here.
|
||||
*
|
||||
* In some browsers (early IEs), these are not defined on the Node object,
|
||||
* so they are provided here.
|
||||
*
|
||||
* See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247
|
||||
* @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
|
||||
};
|
||||
@@ -0,0 +1,409 @@
|
||||
// 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 patched, standardized event object for browser events.
|
||||
*
|
||||
* <pre>
|
||||
* The patched event object contains the following members:
|
||||
* - type {string} Event type, e.g. 'click'
|
||||
* - target {Object} The element that actually triggered the event
|
||||
* - currentTarget {Object} The element the listener is attached to
|
||||
* - relatedTarget {Object} For mouseover and mouseout, the previous object
|
||||
* - offsetX {number} X-coordinate relative to target
|
||||
* - offsetY {number} Y-coordinate relative to target
|
||||
* - clientX {number} X-coordinate relative to viewport
|
||||
* - clientY {number} Y-coordinate relative to viewport
|
||||
* - screenX {number} X-coordinate relative to the edge of the screen
|
||||
* - screenY {number} Y-coordinate relative to the edge of the screen
|
||||
* - button {number} Mouse button. Use isButton() to test.
|
||||
* - keyCode {number} Key-code
|
||||
* - ctrlKey {boolean} Was ctrl key depressed
|
||||
* - altKey {boolean} Was alt key depressed
|
||||
* - shiftKey {boolean} Was shift key depressed
|
||||
* - metaKey {boolean} Was meta key depressed
|
||||
* - defaultPrevented {boolean} Whether the default action has been prevented
|
||||
* - state {Object} History state object
|
||||
*
|
||||
* NOTE: The keyCode member contains the raw browser keyCode. For normalized
|
||||
* key and character code use {@link goog.events.KeyHandler}.
|
||||
* </pre>
|
||||
*
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
*/
|
||||
|
||||
goog.provide('goog.events.BrowserEvent');
|
||||
goog.provide('goog.events.BrowserEvent.MouseButton');
|
||||
|
||||
goog.require('goog.events.BrowserFeature');
|
||||
goog.require('goog.events.Event');
|
||||
goog.require('goog.events.EventType');
|
||||
goog.require('goog.reflect');
|
||||
goog.require('goog.userAgent');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Accepts a browser event object and creates a patched, cross browser event
|
||||
* object.
|
||||
* The content of this object will not be initialized if no event object is
|
||||
* provided. If this is the case, init() needs to be invoked separately.
|
||||
* @param {Event=} opt_e Browser event object.
|
||||
* @param {EventTarget=} opt_currentTarget Current target for event.
|
||||
* @constructor
|
||||
* @extends {goog.events.Event}
|
||||
*/
|
||||
goog.events.BrowserEvent = function(opt_e, opt_currentTarget) {
|
||||
goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');
|
||||
|
||||
/**
|
||||
* Target that fired the event.
|
||||
* @override
|
||||
* @type {Node}
|
||||
*/
|
||||
this.target = null;
|
||||
|
||||
/**
|
||||
* Node that had the listener attached.
|
||||
* @override
|
||||
* @type {Node|undefined}
|
||||
*/
|
||||
this.currentTarget = null;
|
||||
|
||||
/**
|
||||
* For mouseover and mouseout events, the related object for the event.
|
||||
* @type {Node}
|
||||
*/
|
||||
this.relatedTarget = null;
|
||||
|
||||
/**
|
||||
* X-coordinate relative to target.
|
||||
* @type {number}
|
||||
*/
|
||||
this.offsetX = 0;
|
||||
|
||||
/**
|
||||
* Y-coordinate relative to target.
|
||||
* @type {number}
|
||||
*/
|
||||
this.offsetY = 0;
|
||||
|
||||
/**
|
||||
* X-coordinate relative to the window.
|
||||
* @type {number}
|
||||
*/
|
||||
this.clientX = 0;
|
||||
|
||||
/**
|
||||
* Y-coordinate relative to the window.
|
||||
* @type {number}
|
||||
*/
|
||||
this.clientY = 0;
|
||||
|
||||
/**
|
||||
* X-coordinate relative to the monitor.
|
||||
* @type {number}
|
||||
*/
|
||||
this.screenX = 0;
|
||||
|
||||
/**
|
||||
* Y-coordinate relative to the monitor.
|
||||
* @type {number}
|
||||
*/
|
||||
this.screenY = 0;
|
||||
|
||||
/**
|
||||
* Which mouse button was pressed.
|
||||
* @type {number}
|
||||
*/
|
||||
this.button = 0;
|
||||
|
||||
/**
|
||||
* Key of key press.
|
||||
* @type {string}
|
||||
*/
|
||||
this.key = '';
|
||||
|
||||
/**
|
||||
* Keycode of key press.
|
||||
* @type {number}
|
||||
*/
|
||||
this.keyCode = 0;
|
||||
|
||||
/**
|
||||
* Keycode of key press.
|
||||
* @type {number}
|
||||
*/
|
||||
this.charCode = 0;
|
||||
|
||||
/**
|
||||
* Whether control was pressed at time of event.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.ctrlKey = false;
|
||||
|
||||
/**
|
||||
* Whether alt was pressed at time of event.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.altKey = false;
|
||||
|
||||
/**
|
||||
* Whether shift was pressed at time of event.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.shiftKey = false;
|
||||
|
||||
/**
|
||||
* Whether the meta key was pressed at time of event.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.metaKey = false;
|
||||
|
||||
/**
|
||||
* History state object, only set for PopState events where it's a copy of the
|
||||
* state object provided to pushState or replaceState.
|
||||
* @type {Object}
|
||||
*/
|
||||
this.state = null;
|
||||
|
||||
/**
|
||||
* Whether the default platform modifier key was pressed at time of event.
|
||||
* (This is control for all platforms except Mac, where it's Meta.)
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.platformModifierKey = false;
|
||||
|
||||
/**
|
||||
* The browser event object.
|
||||
* @private {Event}
|
||||
*/
|
||||
this.event_ = null;
|
||||
|
||||
if (opt_e) {
|
||||
this.init(opt_e, opt_currentTarget);
|
||||
}
|
||||
};
|
||||
goog.inherits(goog.events.BrowserEvent, goog.events.Event);
|
||||
|
||||
|
||||
/**
|
||||
* Normalized button constants for the mouse.
|
||||
* @enum {number}
|
||||
*/
|
||||
goog.events.BrowserEvent.MouseButton = {
|
||||
LEFT: 0,
|
||||
MIDDLE: 1,
|
||||
RIGHT: 2
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Static data for mapping mouse buttons.
|
||||
* @type {!Array<number>}
|
||||
*/
|
||||
goog.events.BrowserEvent.IEButtonMap = [
|
||||
1, // LEFT
|
||||
4, // MIDDLE
|
||||
2 // RIGHT
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Accepts a browser event object and creates a patched, cross browser event
|
||||
* object.
|
||||
* @param {Event} e Browser event object.
|
||||
* @param {EventTarget=} opt_currentTarget Current target for event.
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {
|
||||
var type = this.type = e.type;
|
||||
|
||||
/**
|
||||
* On touch devices use the first "changed touch" as the relevant touch.
|
||||
* @type {Touch}
|
||||
*/
|
||||
var relevantTouch = e.changedTouches ? e.changedTouches[0] : null;
|
||||
|
||||
// TODO(nicksantos): Change this.target to type EventTarget.
|
||||
this.target = /** @type {Node} */ (e.target) || e.srcElement;
|
||||
|
||||
// TODO(nicksantos): Change this.currentTarget to type EventTarget.
|
||||
this.currentTarget = /** @type {Node} */ (opt_currentTarget);
|
||||
|
||||
var relatedTarget = /** @type {Node} */ (e.relatedTarget);
|
||||
if (relatedTarget) {
|
||||
// There's a bug in FireFox where sometimes, relatedTarget will be a
|
||||
// chrome element, and accessing any property of it will get a permission
|
||||
// denied exception. See:
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=497780
|
||||
if (goog.userAgent.GECKO) {
|
||||
if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {
|
||||
relatedTarget = null;
|
||||
}
|
||||
}
|
||||
// TODO(arv): Use goog.events.EventType when it has been refactored into its
|
||||
// own file.
|
||||
} else if (type == goog.events.EventType.MOUSEOVER) {
|
||||
relatedTarget = e.fromElement;
|
||||
} else if (type == goog.events.EventType.MOUSEOUT) {
|
||||
relatedTarget = e.toElement;
|
||||
}
|
||||
|
||||
this.relatedTarget = relatedTarget;
|
||||
|
||||
if (!goog.isNull(relevantTouch)) {
|
||||
this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :
|
||||
relevantTouch.pageX;
|
||||
this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :
|
||||
relevantTouch.pageY;
|
||||
this.screenX = relevantTouch.screenX || 0;
|
||||
this.screenY = relevantTouch.screenY || 0;
|
||||
} else {
|
||||
// Webkit emits a lame warning whenever layerX/layerY is accessed.
|
||||
// http://code.google.com/p/chromium/issues/detail?id=101733
|
||||
this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?
|
||||
e.offsetX :
|
||||
e.layerX;
|
||||
this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?
|
||||
e.offsetY :
|
||||
e.layerY;
|
||||
this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;
|
||||
this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;
|
||||
this.screenX = e.screenX || 0;
|
||||
this.screenY = e.screenY || 0;
|
||||
}
|
||||
|
||||
this.button = e.button;
|
||||
|
||||
this.keyCode = e.keyCode || 0;
|
||||
this.key = e.key || '';
|
||||
this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);
|
||||
this.ctrlKey = e.ctrlKey;
|
||||
this.altKey = e.altKey;
|
||||
this.shiftKey = e.shiftKey;
|
||||
this.metaKey = e.metaKey;
|
||||
this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;
|
||||
this.state = e.state;
|
||||
this.event_ = e;
|
||||
if (e.defaultPrevented) {
|
||||
this.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Tests to see which button was pressed during the event. This is really only
|
||||
* useful in IE and Gecko browsers. And in IE, it's only useful for
|
||||
* mousedown/mouseup events, because click only fires for the left mouse button.
|
||||
*
|
||||
* Safari 2 only reports the left button being clicked, and uses the value '1'
|
||||
* instead of 0. Opera only reports a mousedown event for the middle button, and
|
||||
* no mouse events for the right button. Opera has default behavior for left and
|
||||
* middle click that can only be overridden via a configuration setting.
|
||||
*
|
||||
* There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.
|
||||
*
|
||||
* @param {goog.events.BrowserEvent.MouseButton} button The button
|
||||
* to test for.
|
||||
* @return {boolean} True if button was pressed.
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.isButton = function(button) {
|
||||
if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {
|
||||
if (this.type == 'click') {
|
||||
return button == goog.events.BrowserEvent.MouseButton.LEFT;
|
||||
} else {
|
||||
return !!(
|
||||
this.event_.button & goog.events.BrowserEvent.IEButtonMap[button]);
|
||||
}
|
||||
} else {
|
||||
return this.event_.button == button;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether this has an "action"-producing mouse button.
|
||||
*
|
||||
* By definition, this includes left-click on windows/linux, and left-click
|
||||
* without the ctrl key on Macs.
|
||||
*
|
||||
* @return {boolean} The result.
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.isMouseActionButton = function() {
|
||||
// Webkit does not ctrl+click to be a right-click, so we
|
||||
// normalize it to behave like Gecko and Opera.
|
||||
return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&
|
||||
!(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.stopPropagation = function() {
|
||||
goog.events.BrowserEvent.superClass_.stopPropagation.call(this);
|
||||
if (this.event_.stopPropagation) {
|
||||
this.event_.stopPropagation();
|
||||
} else {
|
||||
this.event_.cancelBubble = true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.preventDefault = function() {
|
||||
goog.events.BrowserEvent.superClass_.preventDefault.call(this);
|
||||
var be = this.event_;
|
||||
if (!be.preventDefault) {
|
||||
be.returnValue = false;
|
||||
if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {
|
||||
|
||||
try {
|
||||
// Most keys can be prevented using returnValue. Some special keys
|
||||
// require setting the keyCode to -1 as well:
|
||||
//
|
||||
// In IE7:
|
||||
// F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)
|
||||
//
|
||||
// In IE8:
|
||||
// Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)
|
||||
//
|
||||
// We therefore do this for all function keys as well as when Ctrl key
|
||||
// is pressed.
|
||||
var VK_F1 = 112;
|
||||
var VK_F12 = 123;
|
||||
if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {
|
||||
be.keyCode = -1;
|
||||
}
|
||||
} catch (ex) {
|
||||
// IE throws an 'access denied' exception when trying to change
|
||||
// keyCode in some situations (e.g. srcElement is input[type=file],
|
||||
// or srcElement is an anchor tag rewritten by parent's innerHTML).
|
||||
// Do nothing in this case.
|
||||
}
|
||||
}
|
||||
} else {
|
||||
be.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {Event} The underlying browser event object.
|
||||
*/
|
||||
goog.events.BrowserEvent.prototype.getBrowserEvent = function() {
|
||||
return this.event_;
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
// 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 events package.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.events.BrowserFeature');
|
||||
|
||||
goog.require('goog.userAgent');
|
||||
goog.scope(function() {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Enum of browser capabilities.
|
||||
* @enum {boolean}
|
||||
*/
|
||||
goog.events.BrowserFeature = {
|
||||
/**
|
||||
* Whether the button attribute of the event is W3C compliant. False in
|
||||
* Internet Explorer prior to version 9; document-version dependent.
|
||||
*/
|
||||
HAS_W3C_BUTTON:
|
||||
!goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),
|
||||
|
||||
/**
|
||||
* Whether the browser supports full W3C event model.
|
||||
*/
|
||||
HAS_W3C_EVENT_SUPPORT:
|
||||
!goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),
|
||||
|
||||
/**
|
||||
* To prevent default in IE7-8 for certain keydown events we need set the
|
||||
* keyCode to -1.
|
||||
*/
|
||||
SET_KEY_CODE_TO_PREVENT_DEFAULT:
|
||||
goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),
|
||||
|
||||
/**
|
||||
* Whether the {@code navigator.onLine} property is supported.
|
||||
*/
|
||||
HAS_NAVIGATOR_ONLINE_PROPERTY:
|
||||
!goog.userAgent.WEBKIT || goog.userAgent.isVersionOrHigher('528'),
|
||||
|
||||
/**
|
||||
* Whether HTML5 network online/offline events are supported.
|
||||
*/
|
||||
HAS_HTML5_NETWORK_EVENT_SUPPORT:
|
||||
goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') ||
|
||||
goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') ||
|
||||
goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') ||
|
||||
goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'),
|
||||
|
||||
/**
|
||||
* Whether HTML5 network events fire on document.body, or otherwise the
|
||||
* window.
|
||||
*/
|
||||
HTML5_NETWORK_EVENTS_FIRE_ON_BODY:
|
||||
goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') ||
|
||||
goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),
|
||||
|
||||
/**
|
||||
* Whether touch is enabled in the browser.
|
||||
*/
|
||||
TOUCH_ENABLED:
|
||||
('ontouchstart' in goog.global ||
|
||||
!!(goog.global['document'] && document.documentElement &&
|
||||
'ontouchstart' in document.documentElement) ||
|
||||
// IE10 uses non-standard touch events, so it has a different check.
|
||||
!!(goog.global['navigator'] &&
|
||||
goog.global['navigator']['msMaxTouchPoints'])),
|
||||
|
||||
/**
|
||||
* Whether addEventListener supports {passive: true}.
|
||||
* https://developers.google.com/web/updates/2016/06/passive-event-listeners
|
||||
*/
|
||||
PASSIVE_EVENTS: purify(function() {
|
||||
// If we're in a web worker or other custom environment, we can't tell.
|
||||
if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8
|
||||
return false;
|
||||
}
|
||||
|
||||
var passive = false;
|
||||
var options = Object.defineProperty({}, 'passive', {
|
||||
get: function() {
|
||||
passive = true;
|
||||
}
|
||||
});
|
||||
goog.global.addEventListener('test', goog.nullFunction, options);
|
||||
goog.global.removeEventListener('test', goog.nullFunction, options);
|
||||
|
||||
return passive;
|
||||
})
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Tricks Closure Compiler into believing that a function is pure. The compiler
|
||||
* assumes that any `valueOf` function is pure, without analyzing its contents.
|
||||
*
|
||||
* @param {function(): T} fn
|
||||
* @return {T}
|
||||
* @template T
|
||||
*/
|
||||
function purify(fn) {
|
||||
return ({valueOf: fn}).valueOf();
|
||||
}
|
||||
}); // goog.scope
|
||||
@@ -0,0 +1,143 @@
|
||||
// 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 base class for event objects.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.events.Event');
|
||||
goog.provide('goog.events.EventLike');
|
||||
|
||||
/**
|
||||
* goog.events.Event no longer depends on goog.Disposable. Keep requiring
|
||||
* goog.Disposable here to not break projects which assume this dependency.
|
||||
* @suppress {extraRequire}
|
||||
*/
|
||||
goog.require('goog.Disposable');
|
||||
goog.require('goog.events.EventId');
|
||||
|
||||
|
||||
/**
|
||||
* A typedef for event like objects that are dispatchable via the
|
||||
* goog.events.dispatchEvent function. strings are treated as the type for a
|
||||
* goog.events.Event. Objects are treated as an extension of a new
|
||||
* goog.events.Event with the type property of the object being used as the type
|
||||
* of the Event.
|
||||
* @typedef {string|Object|goog.events.Event|goog.events.EventId}
|
||||
*/
|
||||
goog.events.EventLike;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A base class for event objects, so that they can support preventDefault and
|
||||
* stopPropagation.
|
||||
*
|
||||
* @suppress {underscore} Several properties on this class are technically
|
||||
* public, but referencing these properties outside this package is strongly
|
||||
* discouraged.
|
||||
*
|
||||
* @param {string|!goog.events.EventId} type Event Type.
|
||||
* @param {Object=} opt_target Reference to the object that is the target of
|
||||
* this event. It has to implement the {@code EventTarget} interface
|
||||
* declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.
|
||||
* @constructor
|
||||
*/
|
||||
goog.events.Event = function(type, opt_target) {
|
||||
/**
|
||||
* Event type.
|
||||
* @type {string}
|
||||
*/
|
||||
this.type = type instanceof goog.events.EventId ? String(type) : type;
|
||||
|
||||
/**
|
||||
* TODO(tbreisacher): The type should probably be
|
||||
* EventTarget|goog.events.EventTarget.
|
||||
*
|
||||
* Target of the event.
|
||||
* @type {Object|undefined}
|
||||
*/
|
||||
this.target = opt_target;
|
||||
|
||||
/**
|
||||
* Object that had the listener attached.
|
||||
* @type {Object|undefined}
|
||||
*/
|
||||
this.currentTarget = this.target;
|
||||
|
||||
/**
|
||||
* Whether to cancel the event in internal capture/bubble processing for IE.
|
||||
* @type {boolean}
|
||||
* @public
|
||||
*/
|
||||
this.propagationStopped_ = false;
|
||||
|
||||
/**
|
||||
* Whether the default action has been prevented.
|
||||
* This is a property to match the W3C specification at
|
||||
* {@link http://www.w3.org/TR/DOM-Level-3-Events/
|
||||
* #events-event-type-defaultPrevented}.
|
||||
* Must be treated as read-only outside the class.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.defaultPrevented = false;
|
||||
|
||||
/**
|
||||
* Return value for in internal capture/bubble processing for IE.
|
||||
* @type {boolean}
|
||||
* @public
|
||||
*/
|
||||
this.returnValue_ = true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Stops event propagation.
|
||||
*/
|
||||
goog.events.Event.prototype.stopPropagation = function() {
|
||||
this.propagationStopped_ = true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Prevents the default action, for example a link redirecting to a url.
|
||||
*/
|
||||
goog.events.Event.prototype.preventDefault = function() {
|
||||
this.defaultPrevented = true;
|
||||
this.returnValue_ = false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Stops the propagation of the event. It is equivalent to
|
||||
* {@code e.stopPropagation()}, but can be used as the callback argument of
|
||||
* {@link goog.events.listen} without declaring another function.
|
||||
* @param {!goog.events.Event} e An event.
|
||||
*/
|
||||
goog.events.Event.stopPropagation = function(e) {
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Prevents the default action. It is equivalent to
|
||||
* {@code e.preventDefault()}, but can be used as the callback argument of
|
||||
* {@link goog.events.listen} without declaring another function.
|
||||
* @param {!goog.events.Event} e An event.
|
||||
*/
|
||||
goog.events.Event.preventDefault = function(e) {
|
||||
e.preventDefault();
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2013 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.events.EventId');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A templated class that is used when registering for events. Typical usage:
|
||||
*
|
||||
* /** @type {goog.events.EventId<MyEventObj>} *\
|
||||
* var myEventId = new goog.events.EventId(
|
||||
* goog.events.getUniqueId(('someEvent'));
|
||||
*
|
||||
* // No need to cast or declare here since the compiler knows the
|
||||
* // correct type of 'evt' (MyEventObj).
|
||||
* something.listen(myEventId, function(evt) {});
|
||||
*
|
||||
* @param {string} eventId
|
||||
* @template T
|
||||
* @constructor
|
||||
* @struct
|
||||
* @final
|
||||
*/
|
||||
goog.events.EventId = function(eventId) {
|
||||
/** @const */ this.id = eventId;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @override
|
||||
*/
|
||||
goog.events.EventId.prototype.toString = function() {
|
||||
return this.id;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,394 @@
|
||||
// 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 disposable implementation of a custom
|
||||
* listenable/event target. See also: documentation for
|
||||
* {@code goog.events.Listenable}.
|
||||
*
|
||||
* @author arv@google.com (Erik Arvidsson) [Original implementation]
|
||||
* @see ../demos/eventtarget.html
|
||||
* @see goog.events.Listenable
|
||||
*/
|
||||
|
||||
goog.provide('goog.events.EventTarget');
|
||||
|
||||
goog.require('goog.Disposable');
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.events');
|
||||
goog.require('goog.events.Event');
|
||||
goog.require('goog.events.Listenable');
|
||||
goog.require('goog.events.ListenerMap');
|
||||
goog.require('goog.object');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An implementation of {@code goog.events.Listenable} with full W3C
|
||||
* EventTarget-like support (capture/bubble mechanism, stopping event
|
||||
* propagation, preventing default actions).
|
||||
*
|
||||
* You may subclass this class to turn your class into a Listenable.
|
||||
*
|
||||
* Unless propagation is stopped, an event dispatched by an
|
||||
* EventTarget will bubble to the parent returned by
|
||||
* {@code getParentEventTarget}. To set the parent, call
|
||||
* {@code setParentEventTarget}. Subclasses that don't support
|
||||
* changing the parent can override the setter to throw an error.
|
||||
*
|
||||
* Example usage:
|
||||
* <pre>
|
||||
* var source = new goog.events.EventTarget();
|
||||
* function handleEvent(e) {
|
||||
* alert('Type: ' + e.type + '; Target: ' + e.target);
|
||||
* }
|
||||
* source.listen('foo', handleEvent);
|
||||
* // Or: goog.events.listen(source, 'foo', handleEvent);
|
||||
* ...
|
||||
* source.dispatchEvent('foo'); // will call handleEvent
|
||||
* ...
|
||||
* source.unlisten('foo', handleEvent);
|
||||
* // Or: goog.events.unlisten(source, 'foo', handleEvent);
|
||||
* </pre>
|
||||
*
|
||||
* @constructor
|
||||
* @extends {goog.Disposable}
|
||||
* @implements {goog.events.Listenable}
|
||||
*/
|
||||
goog.events.EventTarget = function() {
|
||||
goog.Disposable.call(this);
|
||||
|
||||
/**
|
||||
* Maps of event type to an array of listeners.
|
||||
* @private {!goog.events.ListenerMap}
|
||||
*/
|
||||
this.eventTargetListeners_ = new goog.events.ListenerMap(this);
|
||||
|
||||
/**
|
||||
* The object to use for event.target. Useful when mixing in an
|
||||
* EventTarget to another object.
|
||||
* @private {!Object}
|
||||
*/
|
||||
this.actualEventTarget_ = this;
|
||||
|
||||
/**
|
||||
* Parent event target, used during event bubbling.
|
||||
*
|
||||
* TODO(chrishenry): Change this to goog.events.Listenable. This
|
||||
* currently breaks people who expect getParentEventTarget to return
|
||||
* goog.events.EventTarget.
|
||||
*
|
||||
* @private {goog.events.EventTarget}
|
||||
*/
|
||||
this.parentEventTarget_ = null;
|
||||
};
|
||||
goog.inherits(goog.events.EventTarget, goog.Disposable);
|
||||
goog.events.Listenable.addImplementation(goog.events.EventTarget);
|
||||
|
||||
|
||||
/**
|
||||
* An artificial cap on the number of ancestors you can have. This is mainly
|
||||
* for loop detection.
|
||||
* @const {number}
|
||||
* @private
|
||||
*/
|
||||
goog.events.EventTarget.MAX_ANCESTORS_ = 1000;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the parent of this event target to use for bubbling.
|
||||
*
|
||||
* @return {goog.events.EventTarget} The parent EventTarget or null if
|
||||
* there is no parent.
|
||||
* @override
|
||||
*/
|
||||
goog.events.EventTarget.prototype.getParentEventTarget = function() {
|
||||
return this.parentEventTarget_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets the parent of this event target to use for capture/bubble
|
||||
* mechanism.
|
||||
* @param {goog.events.EventTarget} parent Parent listenable (null if none).
|
||||
*/
|
||||
goog.events.EventTarget.prototype.setParentEventTarget = function(parent) {
|
||||
this.parentEventTarget_ = parent;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds an event listener to the event target. The same handler can only be
|
||||
* added once per the type. Even if you add the same handler multiple times
|
||||
* using the same type then it will only be called once when the event is
|
||||
* dispatched.
|
||||
*
|
||||
* @param {string|!goog.events.EventId} type The type of the event to listen for
|
||||
* @param {function(?):?|{handleEvent:function(?):?}|null} handler The function
|
||||
* to handle the event. The handler can also be an object that implements
|
||||
* the handleEvent method which takes the event object as argument.
|
||||
* @param {boolean=} opt_capture In DOM-compliant browsers, this determines
|
||||
* whether the listener is fired during the capture or bubble phase
|
||||
* of the event.
|
||||
* @param {Object=} opt_handlerScope Object in whose scope to call
|
||||
* the listener.
|
||||
* @deprecated Use {@code #listen} instead, when possible. Otherwise, use
|
||||
* {@code goog.events.listen} if you are passing Object
|
||||
* (instead of Function) as handler.
|
||||
*/
|
||||
goog.events.EventTarget.prototype.addEventListener = function(
|
||||
type, handler, opt_capture, opt_handlerScope) {
|
||||
goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes an event listener from the event target. The handler must be the
|
||||
* same object as the one added. If the handler has not been added then
|
||||
* nothing is done.
|
||||
*
|
||||
* @param {string} type The type of the event to listen for.
|
||||
* @param {function(?):?|{handleEvent:function(?):?}|null} handler The function
|
||||
* to handle the event. The handler can also be an object that implements
|
||||
* the handleEvent method which takes the event object as argument.
|
||||
* @param {boolean=} opt_capture In DOM-compliant browsers, this determines
|
||||
* whether the listener is fired during the capture or bubble phase
|
||||
* of the event.
|
||||
* @param {Object=} opt_handlerScope Object in whose scope to call
|
||||
* the listener.
|
||||
* @deprecated Use {@code #unlisten} instead, when possible. Otherwise, use
|
||||
* {@code goog.events.unlisten} if you are passing Object
|
||||
* (instead of Function) as handler.
|
||||
*/
|
||||
goog.events.EventTarget.prototype.removeEventListener = function(
|
||||
type, handler, opt_capture, opt_handlerScope) {
|
||||
goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.dispatchEvent = function(e) {
|
||||
this.assertInitialized_();
|
||||
|
||||
var ancestorsTree, ancestor = this.getParentEventTarget();
|
||||
if (ancestor) {
|
||||
ancestorsTree = [];
|
||||
var ancestorCount = 1;
|
||||
for (; ancestor; ancestor = ancestor.getParentEventTarget()) {
|
||||
ancestorsTree.push(ancestor);
|
||||
goog.asserts.assert(
|
||||
(++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),
|
||||
'infinite loop');
|
||||
}
|
||||
}
|
||||
|
||||
return goog.events.EventTarget.dispatchEventInternal_(
|
||||
this.actualEventTarget_, e, ancestorsTree);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes listeners from this object. Classes that extend EventTarget may
|
||||
* need to override this method in order to remove references to DOM Elements
|
||||
* and additional listeners.
|
||||
* @override
|
||||
*/
|
||||
goog.events.EventTarget.prototype.disposeInternal = function() {
|
||||
goog.events.EventTarget.superClass_.disposeInternal.call(this);
|
||||
|
||||
this.removeAllListeners();
|
||||
this.parentEventTarget_ = null;
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.listen = function(
|
||||
type, listener, opt_useCapture, opt_listenerScope) {
|
||||
this.assertInitialized_();
|
||||
return this.eventTargetListeners_.add(
|
||||
String(type), listener, false /* callOnce */, opt_useCapture,
|
||||
opt_listenerScope);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.listenOnce = function(
|
||||
type, listener, opt_useCapture, opt_listenerScope) {
|
||||
return this.eventTargetListeners_.add(
|
||||
String(type), listener, true /* callOnce */, opt_useCapture,
|
||||
opt_listenerScope);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.unlisten = function(
|
||||
type, listener, opt_useCapture, opt_listenerScope) {
|
||||
return this.eventTargetListeners_.remove(
|
||||
String(type), listener, opt_useCapture, opt_listenerScope);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.unlistenByKey = function(key) {
|
||||
return this.eventTargetListeners_.removeByKey(key);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {
|
||||
// TODO(chrishenry): Previously, removeAllListeners can be called on
|
||||
// uninitialized EventTarget, so we preserve that behavior. We
|
||||
// should remove this when usages that rely on that fact are purged.
|
||||
if (!this.eventTargetListeners_) {
|
||||
return 0;
|
||||
}
|
||||
return this.eventTargetListeners_.removeAll(opt_type);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.fireListeners = function(
|
||||
type, capture, eventObject) {
|
||||
// TODO(chrishenry): Original code avoids array creation when there
|
||||
// is no listener, so we do the same. If this optimization turns
|
||||
// out to be not required, we can replace this with
|
||||
// getListeners(type, capture) instead, which is simpler.
|
||||
var listenerArray = this.eventTargetListeners_.listeners[String(type)];
|
||||
if (!listenerArray) {
|
||||
return true;
|
||||
}
|
||||
listenerArray = listenerArray.concat();
|
||||
|
||||
var rv = true;
|
||||
for (var i = 0; i < listenerArray.length; ++i) {
|
||||
var listener = listenerArray[i];
|
||||
// We might not have a listener if the listener was removed.
|
||||
if (listener && !listener.removed && listener.capture == capture) {
|
||||
var listenerFn = listener.listener;
|
||||
var listenerHandler = listener.handler || listener.src;
|
||||
|
||||
if (listener.callOnce) {
|
||||
this.unlistenByKey(listener);
|
||||
}
|
||||
rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;
|
||||
}
|
||||
}
|
||||
|
||||
return rv && eventObject.returnValue_ != false;
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.getListeners = function(type, capture) {
|
||||
return this.eventTargetListeners_.getListeners(String(type), capture);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.getListener = function(
|
||||
type, listener, capture, opt_listenerScope) {
|
||||
return this.eventTargetListeners_.getListener(
|
||||
String(type), listener, capture, opt_listenerScope);
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.events.EventTarget.prototype.hasListener = function(
|
||||
opt_type, opt_capture) {
|
||||
var id = goog.isDef(opt_type) ? String(opt_type) : undefined;
|
||||
return this.eventTargetListeners_.hasListener(id, opt_capture);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets the target to be used for {@code event.target} when firing
|
||||
* event. Mainly used for testing. For example, see
|
||||
* {@code goog.testing.events.mixinListenable}.
|
||||
* @param {!Object} target The target.
|
||||
*/
|
||||
goog.events.EventTarget.prototype.setTargetForTesting = function(target) {
|
||||
this.actualEventTarget_ = target;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Asserts that the event target instance is initialized properly.
|
||||
* @private
|
||||
*/
|
||||
goog.events.EventTarget.prototype.assertInitialized_ = function() {
|
||||
goog.asserts.assert(
|
||||
this.eventTargetListeners_,
|
||||
'Event target is not initialized. Did you call the superclass ' +
|
||||
'(goog.events.EventTarget) constructor?');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Dispatches the given event on the ancestorsTree.
|
||||
*
|
||||
* @param {!Object} target The target to dispatch on.
|
||||
* @param {goog.events.Event|Object|string} e The event object.
|
||||
* @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors
|
||||
* tree of the target, in reverse order from the closest ancestor
|
||||
* to the root event target. May be null if the target has no ancestor.
|
||||
* @return {boolean} If anyone called preventDefault on the event object (or
|
||||
* if any of the listeners returns false) this will also return false.
|
||||
* @private
|
||||
*/
|
||||
goog.events.EventTarget.dispatchEventInternal_ = function(
|
||||
target, e, opt_ancestorsTree) {
|
||||
var type = e.type || /** @type {string} */ (e);
|
||||
|
||||
// If accepting a string or object, create a custom event object so that
|
||||
// preventDefault and stopPropagation work with the event.
|
||||
if (goog.isString(e)) {
|
||||
e = new goog.events.Event(e, target);
|
||||
} else if (!(e instanceof goog.events.Event)) {
|
||||
var oldEvent = e;
|
||||
e = new goog.events.Event(type, target);
|
||||
goog.object.extend(e, oldEvent);
|
||||
} else {
|
||||
e.target = e.target || target;
|
||||
}
|
||||
|
||||
var rv = true, currentTarget;
|
||||
|
||||
// Executes all capture listeners on the ancestors, if any.
|
||||
if (opt_ancestorsTree) {
|
||||
for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;
|
||||
i--) {
|
||||
currentTarget = e.currentTarget = opt_ancestorsTree[i];
|
||||
rv = currentTarget.fireListeners(type, true, e) && rv;
|
||||
}
|
||||
}
|
||||
|
||||
// Executes capture and bubble listeners on the target.
|
||||
if (!e.propagationStopped_) {
|
||||
currentTarget = /** @type {?} */ (e.currentTarget = target);
|
||||
rv = currentTarget.fireListeners(type, true, e) && rv;
|
||||
if (!e.propagationStopped_) {
|
||||
rv = currentTarget.fireListeners(type, false, e) && rv;
|
||||
}
|
||||
}
|
||||
|
||||
// Executes all bubble listeners on the ancestors, if any.
|
||||
if (opt_ancestorsTree) {
|
||||
for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {
|
||||
currentTarget = e.currentTarget = opt_ancestorsTree[i];
|
||||
rv = currentTarget.fireListeners(type, false, e) && rv;
|
||||
}
|
||||
}
|
||||
|
||||
return rv;
|
||||
};
|
||||
@@ -0,0 +1,295 @@
|
||||
// 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 Event Types.
|
||||
*
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.events.EventType');
|
||||
|
||||
goog.require('goog.userAgent');
|
||||
|
||||
|
||||
/**
|
||||
* Returns a prefixed event name for the current browser.
|
||||
* @param {string} eventName The name of the event.
|
||||
* @return {string} The prefixed event name.
|
||||
* @suppress {missingRequire|missingProvide}
|
||||
* @private
|
||||
*/
|
||||
goog.events.getVendorPrefixedName_ = function(eventName) {
|
||||
return goog.userAgent.WEBKIT ?
|
||||
'webkit' + eventName :
|
||||
(goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
|
||||
eventName.toLowerCase());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Constants for event names.
|
||||
* @enum {string}
|
||||
*/
|
||||
goog.events.EventType = {
|
||||
// Mouse events
|
||||
CLICK: 'click',
|
||||
RIGHTCLICK: 'rightclick',
|
||||
DBLCLICK: 'dblclick',
|
||||
MOUSEDOWN: 'mousedown',
|
||||
MOUSEUP: 'mouseup',
|
||||
MOUSEOVER: 'mouseover',
|
||||
MOUSEOUT: 'mouseout',
|
||||
MOUSEMOVE: 'mousemove',
|
||||
MOUSEENTER: 'mouseenter',
|
||||
MOUSELEAVE: 'mouseleave',
|
||||
|
||||
// Selection events.
|
||||
// https://www.w3.org/TR/selection-api/
|
||||
SELECTIONCHANGE: 'selectionchange',
|
||||
SELECTSTART: 'selectstart', // IE, Safari, Chrome
|
||||
|
||||
// Wheel events
|
||||
// http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
|
||||
WHEEL: 'wheel',
|
||||
|
||||
// Key events
|
||||
KEYPRESS: 'keypress',
|
||||
KEYDOWN: 'keydown',
|
||||
KEYUP: 'keyup',
|
||||
|
||||
// Focus
|
||||
BLUR: 'blur',
|
||||
FOCUS: 'focus',
|
||||
DEACTIVATE: 'deactivate', // IE only
|
||||
// NOTE: The following two events are not stable in cross-browser usage.
|
||||
// WebKit and Opera implement DOMFocusIn/Out.
|
||||
// IE implements focusin/out.
|
||||
// Gecko implements neither see bug at
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
|
||||
// The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
|
||||
// http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
|
||||
// You can use FOCUS in Capture phase until implementations converge.
|
||||
FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
|
||||
FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',
|
||||
|
||||
// Forms
|
||||
CHANGE: 'change',
|
||||
RESET: 'reset',
|
||||
SELECT: 'select',
|
||||
SUBMIT: 'submit',
|
||||
INPUT: 'input',
|
||||
PROPERTYCHANGE: 'propertychange', // IE only
|
||||
|
||||
// Drag and drop
|
||||
DRAGSTART: 'dragstart',
|
||||
DRAG: 'drag',
|
||||
DRAGENTER: 'dragenter',
|
||||
DRAGOVER: 'dragover',
|
||||
DRAGLEAVE: 'dragleave',
|
||||
DROP: 'drop',
|
||||
DRAGEND: 'dragend',
|
||||
|
||||
// Touch events
|
||||
// Note that other touch events exist, but we should follow the W3C list here.
|
||||
// http://www.w3.org/TR/touch-events/#list-of-touchevent-types
|
||||
TOUCHSTART: 'touchstart',
|
||||
TOUCHMOVE: 'touchmove',
|
||||
TOUCHEND: 'touchend',
|
||||
TOUCHCANCEL: 'touchcancel',
|
||||
|
||||
// Misc
|
||||
BEFOREUNLOAD: 'beforeunload',
|
||||
CONSOLEMESSAGE: 'consolemessage',
|
||||
CONTEXTMENU: 'contextmenu',
|
||||
DEVICEMOTION: 'devicemotion',
|
||||
DEVICEORIENTATION: 'deviceorientation',
|
||||
DOMCONTENTLOADED: 'DOMContentLoaded',
|
||||
ERROR: 'error',
|
||||
HELP: 'help',
|
||||
LOAD: 'load',
|
||||
LOSECAPTURE: 'losecapture',
|
||||
ORIENTATIONCHANGE: 'orientationchange',
|
||||
READYSTATECHANGE: 'readystatechange',
|
||||
RESIZE: 'resize',
|
||||
SCROLL: 'scroll',
|
||||
UNLOAD: 'unload',
|
||||
|
||||
// Media events
|
||||
CANPLAY: 'canplay',
|
||||
CANPLAYTHROUGH: 'canplaythrough',
|
||||
DURATIONCHANGE: 'durationchange',
|
||||
EMPTIED: 'emptied',
|
||||
ENDED: 'ended',
|
||||
LOADEDDATA: 'loadeddata',
|
||||
LOADEDMETADATA: 'loadedmetadata',
|
||||
PAUSE: 'pause',
|
||||
PLAY: 'play',
|
||||
PLAYING: 'playing',
|
||||
RATECHANGE: 'ratechange',
|
||||
SEEKED: 'seeked',
|
||||
SEEKING: 'seeking',
|
||||
STALLED: 'stalled',
|
||||
SUSPEND: 'suspend',
|
||||
TIMEUPDATE: 'timeupdate',
|
||||
VOLUMECHANGE: 'volumechange',
|
||||
WAITING: 'waiting',
|
||||
|
||||
// Media Source Extensions events
|
||||
// https://www.w3.org/TR/media-source/#mediasource-events
|
||||
SOURCEOPEN: 'sourceopen',
|
||||
SOURCEENDED: 'sourceended',
|
||||
SOURCECLOSED: 'sourceclosed',
|
||||
// https://www.w3.org/TR/media-source/#sourcebuffer-events
|
||||
ABORT: 'abort',
|
||||
UPDATE: 'update',
|
||||
UPDATESTART: 'updatestart',
|
||||
UPDATEEND: 'updateend',
|
||||
|
||||
// HTML 5 History events
|
||||
// See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
|
||||
HASHCHANGE: 'hashchange',
|
||||
PAGEHIDE: 'pagehide',
|
||||
PAGESHOW: 'pageshow',
|
||||
POPSTATE: 'popstate',
|
||||
|
||||
// Copy and Paste
|
||||
// Support is limited. Make sure it works on your favorite browser
|
||||
// before using.
|
||||
// http://www.quirksmode.org/dom/events/cutcopypaste.html
|
||||
COPY: 'copy',
|
||||
PASTE: 'paste',
|
||||
CUT: 'cut',
|
||||
BEFORECOPY: 'beforecopy',
|
||||
BEFORECUT: 'beforecut',
|
||||
BEFOREPASTE: 'beforepaste',
|
||||
|
||||
// HTML5 online/offline events.
|
||||
// http://www.w3.org/TR/offline-webapps/#related
|
||||
ONLINE: 'online',
|
||||
OFFLINE: 'offline',
|
||||
|
||||
// HTML 5 worker events
|
||||
MESSAGE: 'message',
|
||||
CONNECT: 'connect',
|
||||
|
||||
// Service Worker Events - ServiceWorkerGlobalScope context
|
||||
// See https://w3c.github.io/ServiceWorker/#execution-context-events
|
||||
// Note: message event defined in worker events section
|
||||
INSTALL: 'install',
|
||||
ACTIVATE: 'activate',
|
||||
FETCH: 'fetch',
|
||||
FOREIGNFETCH: 'foreignfetch',
|
||||
MESSAGEERROR: 'messageerror',
|
||||
|
||||
// Service Worker Events - Document context
|
||||
// See https://w3c.github.io/ServiceWorker/#document-context-events
|
||||
STATECHANGE: 'statechange',
|
||||
UPDATEFOUND: 'updatefound',
|
||||
CONTROLLERCHANGE: 'controllerchange',
|
||||
|
||||
// CSS animation events.
|
||||
/** @suppress {missingRequire} */
|
||||
ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
|
||||
/** @suppress {missingRequire} */
|
||||
ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
|
||||
/** @suppress {missingRequire} */
|
||||
ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),
|
||||
|
||||
// CSS transition events. Based on the browser support described at:
|
||||
// https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
|
||||
/** @suppress {missingRequire} */
|
||||
TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),
|
||||
|
||||
// W3C Pointer Events
|
||||
// http://www.w3.org/TR/pointerevents/
|
||||
POINTERDOWN: 'pointerdown',
|
||||
POINTERUP: 'pointerup',
|
||||
POINTERCANCEL: 'pointercancel',
|
||||
POINTERMOVE: 'pointermove',
|
||||
POINTEROVER: 'pointerover',
|
||||
POINTEROUT: 'pointerout',
|
||||
POINTERENTER: 'pointerenter',
|
||||
POINTERLEAVE: 'pointerleave',
|
||||
GOTPOINTERCAPTURE: 'gotpointercapture',
|
||||
LOSTPOINTERCAPTURE: 'lostpointercapture',
|
||||
|
||||
// IE specific events.
|
||||
// See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
|
||||
// Note: these events will be supplanted in IE11.
|
||||
MSGESTURECHANGE: 'MSGestureChange',
|
||||
MSGESTUREEND: 'MSGestureEnd',
|
||||
MSGESTUREHOLD: 'MSGestureHold',
|
||||
MSGESTURESTART: 'MSGestureStart',
|
||||
MSGESTURETAP: 'MSGestureTap',
|
||||
MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
|
||||
MSINERTIASTART: 'MSInertiaStart',
|
||||
MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
|
||||
MSPOINTERCANCEL: 'MSPointerCancel',
|
||||
MSPOINTERDOWN: 'MSPointerDown',
|
||||
MSPOINTERENTER: 'MSPointerEnter',
|
||||
MSPOINTERHOVER: 'MSPointerHover',
|
||||
MSPOINTERLEAVE: 'MSPointerLeave',
|
||||
MSPOINTERMOVE: 'MSPointerMove',
|
||||
MSPOINTEROUT: 'MSPointerOut',
|
||||
MSPOINTEROVER: 'MSPointerOver',
|
||||
MSPOINTERUP: 'MSPointerUp',
|
||||
|
||||
// Native IMEs/input tools events.
|
||||
TEXT: 'text',
|
||||
// The textInput event is supported in IE9+, but only in lower case. All other
|
||||
// browsers use the camel-case event name.
|
||||
TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',
|
||||
COMPOSITIONSTART: 'compositionstart',
|
||||
COMPOSITIONUPDATE: 'compositionupdate',
|
||||
COMPOSITIONEND: 'compositionend',
|
||||
|
||||
// The beforeinput event is initially only supported in Safari. See
|
||||
// https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome
|
||||
// implementation tracking.
|
||||
BEFOREINPUT: 'beforeinput',
|
||||
|
||||
// Webview tag events
|
||||
// See http://developer.chrome.com/dev/apps/webview_tag.html
|
||||
EXIT: 'exit',
|
||||
LOADABORT: 'loadabort',
|
||||
LOADCOMMIT: 'loadcommit',
|
||||
LOADREDIRECT: 'loadredirect',
|
||||
LOADSTART: 'loadstart',
|
||||
LOADSTOP: 'loadstop',
|
||||
RESPONSIVE: 'responsive',
|
||||
SIZECHANGED: 'sizechanged',
|
||||
UNRESPONSIVE: 'unresponsive',
|
||||
|
||||
// HTML5 Page Visibility API. See details at
|
||||
// {@code goog.labs.dom.PageVisibilityMonitor}.
|
||||
VISIBILITYCHANGE: 'visibilitychange',
|
||||
|
||||
// LocalStorage event.
|
||||
STORAGE: 'storage',
|
||||
|
||||
// DOM Level 2 mutation events (deprecated).
|
||||
DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
|
||||
DOMNODEINSERTED: 'DOMNodeInserted',
|
||||
DOMNODEREMOVED: 'DOMNodeRemoved',
|
||||
DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
|
||||
DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
|
||||
DOMATTRMODIFIED: 'DOMAttrModified',
|
||||
DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',
|
||||
|
||||
// Print events.
|
||||
BEFOREPRINT: 'beforeprint',
|
||||
AFTERPRINT: 'afterprint'
|
||||
};
|
||||
@@ -0,0 +1,338 @@
|
||||
// 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 a listenable JavaScript object.
|
||||
* @author chrishenry@google.com (Chris Henry)
|
||||
*/
|
||||
|
||||
goog.provide('goog.events.Listenable');
|
||||
goog.provide('goog.events.ListenableKey');
|
||||
|
||||
/** @suppress {extraRequire} */
|
||||
goog.require('goog.events.EventId');
|
||||
|
||||
goog.forwardDeclare('goog.events.EventLike');
|
||||
goog.forwardDeclare('goog.events.EventTarget');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A listenable interface. A listenable is an object with the ability
|
||||
* to dispatch/broadcast events to "event listeners" registered via
|
||||
* listen/listenOnce.
|
||||
*
|
||||
* The interface allows for an event propagation mechanism similar
|
||||
* to one offered by native browser event targets, such as
|
||||
* capture/bubble mechanism, stopping propagation, and preventing
|
||||
* default actions. Capture/bubble mechanism depends on the ancestor
|
||||
* tree constructed via {@code #getParentEventTarget}; this tree
|
||||
* must be directed acyclic graph. The meaning of default action(s)
|
||||
* in preventDefault is specific to a particular use case.
|
||||
*
|
||||
* Implementations that do not support capture/bubble or can not have
|
||||
* a parent listenable can simply not implement any ability to set the
|
||||
* parent listenable (and have {@code #getParentEventTarget} return
|
||||
* null).
|
||||
*
|
||||
* Implementation of this class can be used with or independently from
|
||||
* goog.events.
|
||||
*
|
||||
* Implementation must call {@code #addImplementation(implClass)}.
|
||||
*
|
||||
* @interface
|
||||
* @see goog.events
|
||||
* @see http://www.w3.org/TR/DOM-Level-2-Events/events.html
|
||||
*/
|
||||
goog.events.Listenable = function() {};
|
||||
|
||||
|
||||
/**
|
||||
* An expando property to indicate that an object implements
|
||||
* goog.events.Listenable.
|
||||
*
|
||||
* See addImplementation/isImplementedBy.
|
||||
*
|
||||
* @type {string}
|
||||
* @const
|
||||
*/
|
||||
goog.events.Listenable.IMPLEMENTED_BY_PROP =
|
||||
'closure_listenable_' + ((Math.random() * 1e6) | 0);
|
||||
|
||||
|
||||
/**
|
||||
* Marks a given class (constructor) as an implementation of
|
||||
* Listenable, do that we can query that fact at runtime. The class
|
||||
* must have already implemented the interface.
|
||||
* @param {!function(new:goog.events.Listenable,...)} cls The class constructor.
|
||||
* The corresponding class must have already implemented the interface.
|
||||
*/
|
||||
goog.events.Listenable.addImplementation = function(cls) {
|
||||
cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {Object} obj The object to check.
|
||||
* @return {boolean} Whether a given instance implements Listenable. The
|
||||
* class/superclass of the instance must call addImplementation.
|
||||
*/
|
||||
goog.events.Listenable.isImplementedBy = function(obj) {
|
||||
return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds an event listener. A listener can only be added once to an
|
||||
* object and if it is added again the key for the listener is
|
||||
* returned. Note that if the existing listener is a one-off listener
|
||||
* (registered via listenOnce), it will no longer be a one-off
|
||||
* listener after a call to listen().
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
|
||||
* @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
|
||||
* method.
|
||||
* @param {boolean=} opt_useCapture Whether to fire in capture phase
|
||||
* (defaults to false).
|
||||
* @param {SCOPE=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {!goog.events.ListenableKey} Unique key for the listener.
|
||||
* @template SCOPE,EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.listen;
|
||||
|
||||
|
||||
/**
|
||||
* Adds an event listener that is removed automatically after the
|
||||
* listener fired once.
|
||||
*
|
||||
* If an existing listener already exists, listenOnce will do
|
||||
* nothing. In particular, if the listener was previously registered
|
||||
* via listen(), listenOnce() will not turn the listener into a
|
||||
* one-off listener. Similarly, if there is already an existing
|
||||
* one-off listener, listenOnce does not modify the listeners (it is
|
||||
* still a once listener).
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
|
||||
* @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
|
||||
* method.
|
||||
* @param {boolean=} opt_useCapture Whether to fire in capture phase
|
||||
* (defaults to false).
|
||||
* @param {SCOPE=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {!goog.events.ListenableKey} Unique key for the listener.
|
||||
* @template SCOPE,EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.listenOnce;
|
||||
|
||||
|
||||
/**
|
||||
* Removes an event listener which was added with listen() or listenOnce().
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.
|
||||
* @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback
|
||||
* method.
|
||||
* @param {boolean=} opt_useCapture Whether to fire in capture phase
|
||||
* (defaults to false).
|
||||
* @param {SCOPE=} opt_listenerScope Object in whose scope to call
|
||||
* the listener.
|
||||
* @return {boolean} Whether any listener was removed.
|
||||
* @template SCOPE,EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.unlisten;
|
||||
|
||||
|
||||
/**
|
||||
* Removes an event listener which was added with listen() by the key
|
||||
* returned by listen().
|
||||
*
|
||||
* @param {!goog.events.ListenableKey} key The key returned by
|
||||
* listen() or listenOnce().
|
||||
* @return {boolean} Whether any listener was removed.
|
||||
*/
|
||||
goog.events.Listenable.prototype.unlistenByKey;
|
||||
|
||||
|
||||
/**
|
||||
* Dispatches an event (or event like object) and calls all listeners
|
||||
* listening for events of this type. The type of the event is decided by the
|
||||
* type property on the event object.
|
||||
*
|
||||
* If any of the listeners returns false OR calls preventDefault then this
|
||||
* function will return false. If one of the capture listeners calls
|
||||
* stopPropagation, then the bubble listeners won't fire.
|
||||
*
|
||||
* @param {goog.events.EventLike} e Event object.
|
||||
* @return {boolean} If anyone called preventDefault on the event object (or
|
||||
* if any of the listeners returns false) this will also return false.
|
||||
*/
|
||||
goog.events.Listenable.prototype.dispatchEvent;
|
||||
|
||||
|
||||
/**
|
||||
* Removes all listeners from this listenable. If type is specified,
|
||||
* it will only remove listeners of the particular type. otherwise all
|
||||
* registered listeners will be removed.
|
||||
*
|
||||
* @param {string=} opt_type Type of event to remove, default is to
|
||||
* remove all types.
|
||||
* @return {number} Number of listeners removed.
|
||||
*/
|
||||
goog.events.Listenable.prototype.removeAllListeners;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the parent of this event target to use for capture/bubble
|
||||
* mechanism.
|
||||
*
|
||||
* NOTE(chrishenry): The name reflects the original implementation of
|
||||
* custom event target ({@code goog.events.EventTarget}). We decided
|
||||
* that changing the name is not worth it.
|
||||
*
|
||||
* @return {goog.events.Listenable} The parent EventTarget or null if
|
||||
* there is no parent.
|
||||
*/
|
||||
goog.events.Listenable.prototype.getParentEventTarget;
|
||||
|
||||
|
||||
/**
|
||||
* Fires all registered listeners in this listenable for the given
|
||||
* type and capture mode, passing them the given eventObject. This
|
||||
* does not perform actual capture/bubble. Only implementors of the
|
||||
* interface should be using this.
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the
|
||||
* listeners to fire.
|
||||
* @param {boolean} capture The capture mode of the listeners to fire.
|
||||
* @param {EVENTOBJ} eventObject The event object to fire.
|
||||
* @return {boolean} Whether all listeners succeeded without
|
||||
* attempting to prevent default behavior. If any listener returns
|
||||
* false or called goog.events.Event#preventDefault, this returns
|
||||
* false.
|
||||
* @template EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.fireListeners;
|
||||
|
||||
|
||||
/**
|
||||
* Gets all listeners in this listenable for the given type and
|
||||
* capture mode.
|
||||
*
|
||||
* @param {string|!goog.events.EventId} type The type of the listeners to fire.
|
||||
* @param {boolean} capture The capture mode of the listeners to fire.
|
||||
* @return {!Array<!goog.events.ListenableKey>} An array of registered
|
||||
* listeners.
|
||||
* @template EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.getListeners;
|
||||
|
||||
|
||||
/**
|
||||
* Gets the goog.events.ListenableKey for the event or null if no such
|
||||
* listener is in use.
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event
|
||||
* without the 'on' prefix.
|
||||
* @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The
|
||||
* listener function to get.
|
||||
* @param {boolean} capture Whether the listener is a capturing listener.
|
||||
* @param {SCOPE=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {goog.events.ListenableKey} the found listener or null if not found.
|
||||
* @template SCOPE,EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.getListener;
|
||||
|
||||
|
||||
/**
|
||||
* Whether there is any active listeners matching the specified
|
||||
* signature. If either the type or capture parameters are
|
||||
* unspecified, the function will match on the remaining criteria.
|
||||
*
|
||||
* @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.
|
||||
* @param {boolean=} opt_capture Whether to check for capture or bubble
|
||||
* listeners.
|
||||
* @return {boolean} Whether there is any active listeners matching
|
||||
* the requested type and/or capture phase.
|
||||
* @template EVENTOBJ
|
||||
*/
|
||||
goog.events.Listenable.prototype.hasListener;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An interface that describes a single registered listener.
|
||||
* @interface
|
||||
*/
|
||||
goog.events.ListenableKey = function() {};
|
||||
|
||||
|
||||
/**
|
||||
* Counter used to create a unique key
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.events.ListenableKey.counter_ = 0;
|
||||
|
||||
|
||||
/**
|
||||
* Reserves a key to be used for ListenableKey#key field.
|
||||
* @return {number} A number to be used to fill ListenableKey#key
|
||||
* field.
|
||||
*/
|
||||
goog.events.ListenableKey.reserveKey = function() {
|
||||
return ++goog.events.ListenableKey.counter_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The source event target.
|
||||
* @type {Object|goog.events.Listenable|goog.events.EventTarget}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.src;
|
||||
|
||||
|
||||
/**
|
||||
* The event type the listener is listening to.
|
||||
* @type {string}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.type;
|
||||
|
||||
|
||||
/**
|
||||
* The listener function.
|
||||
* @type {function(?):?|{handleEvent:function(?):?}|null}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.listener;
|
||||
|
||||
|
||||
/**
|
||||
* Whether the listener works on capture phase.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.capture;
|
||||
|
||||
|
||||
/**
|
||||
* The 'this' object for the listener function's scope.
|
||||
* @type {Object|undefined}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.handler;
|
||||
|
||||
|
||||
/**
|
||||
* A globally unique number to identify the key.
|
||||
* @type {number}
|
||||
*/
|
||||
goog.events.ListenableKey.prototype.key;
|
||||
@@ -0,0 +1,128 @@
|
||||
// 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 Listener object.
|
||||
* @see ../demos/events.html
|
||||
*/
|
||||
|
||||
goog.provide('goog.events.Listener');
|
||||
|
||||
goog.require('goog.events.ListenableKey');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Simple class that stores information about a listener
|
||||
* @param {function(?):?} listener Callback function.
|
||||
* @param {Function} proxy Wrapper for the listener that patches the event.
|
||||
* @param {EventTarget|goog.events.Listenable} src Source object for
|
||||
* the event.
|
||||
* @param {string} type Event type.
|
||||
* @param {boolean} capture Whether in capture or bubble phase.
|
||||
* @param {Object=} opt_handler Object in whose context to execute the callback.
|
||||
* @implements {goog.events.ListenableKey}
|
||||
* @constructor
|
||||
*/
|
||||
goog.events.Listener = function(
|
||||
listener, proxy, src, type, capture, opt_handler) {
|
||||
if (goog.events.Listener.ENABLE_MONITORING) {
|
||||
this.creationStack = new Error().stack;
|
||||
}
|
||||
|
||||
/** @override */
|
||||
this.listener = listener;
|
||||
|
||||
/**
|
||||
* A wrapper over the original listener. This is used solely to
|
||||
* handle native browser events (it is used to simulate the capture
|
||||
* phase and to patch the event object).
|
||||
* @type {Function}
|
||||
*/
|
||||
this.proxy = proxy;
|
||||
|
||||
/**
|
||||
* Object or node that callback is listening to
|
||||
* @type {EventTarget|goog.events.Listenable}
|
||||
*/
|
||||
this.src = src;
|
||||
|
||||
/**
|
||||
* The event type.
|
||||
* @const {string}
|
||||
*/
|
||||
this.type = type;
|
||||
|
||||
/**
|
||||
* Whether the listener is being called in the capture or bubble phase
|
||||
* @const {boolean}
|
||||
*/
|
||||
this.capture = !!capture;
|
||||
|
||||
/**
|
||||
* Optional object whose context to execute the listener in
|
||||
* @type {Object|undefined}
|
||||
*/
|
||||
this.handler = opt_handler;
|
||||
|
||||
/**
|
||||
* The key of the listener.
|
||||
* @const {number}
|
||||
* @override
|
||||
*/
|
||||
this.key = goog.events.ListenableKey.reserveKey();
|
||||
|
||||
/**
|
||||
* Whether to remove the listener after it has been called.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.callOnce = false;
|
||||
|
||||
/**
|
||||
* Whether the listener has been removed.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.removed = false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether to enable the monitoring of the
|
||||
* goog.events.Listener instances. 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.define('goog.events.Listener.ENABLE_MONITORING', false);
|
||||
|
||||
|
||||
/**
|
||||
* If monitoring the goog.events.Listener instances is enabled, stores the
|
||||
* creation stack trace of the Disposable instance.
|
||||
* @type {string}
|
||||
*/
|
||||
goog.events.Listener.prototype.creationStack;
|
||||
|
||||
|
||||
/**
|
||||
* Marks this listener as removed. This also remove references held by
|
||||
* this listener object (such as listener and event source).
|
||||
*/
|
||||
goog.events.Listener.prototype.markAsRemoved = function() {
|
||||
this.removed = true;
|
||||
this.listener = null;
|
||||
this.proxy = null;
|
||||
this.src = null;
|
||||
this.handler = null;
|
||||
};
|
||||
@@ -0,0 +1,307 @@
|
||||
// Copyright 2013 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 map of listeners that provides utility functions to
|
||||
* deal with listeners on an event target. Used by
|
||||
* {@code goog.events.EventTarget}.
|
||||
*
|
||||
* WARNING: Do not use this class from outside goog.events package.
|
||||
*
|
||||
* @visibility {//closure/goog/bin/sizetests:__pkg__}
|
||||
* @visibility {//closure/goog:__pkg__}
|
||||
* @visibility {//closure/goog/events:__pkg__}
|
||||
* @visibility {//closure/goog/labs/events:__pkg__}
|
||||
*/
|
||||
|
||||
goog.provide('goog.events.ListenerMap');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.events.Listener');
|
||||
goog.require('goog.object');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new listener map.
|
||||
* @param {EventTarget|goog.events.Listenable} src The src object.
|
||||
* @constructor
|
||||
* @final
|
||||
*/
|
||||
goog.events.ListenerMap = function(src) {
|
||||
/** @type {EventTarget|goog.events.Listenable} */
|
||||
this.src = src;
|
||||
|
||||
/**
|
||||
* Maps of event type to an array of listeners.
|
||||
* @type {!Object<string, !Array<!goog.events.Listener>>}
|
||||
*/
|
||||
this.listeners = {};
|
||||
|
||||
/**
|
||||
* The count of types in this map that have registered listeners.
|
||||
* @private {number}
|
||||
*/
|
||||
this.typeCount_ = 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number} The count of event types in this map that actually
|
||||
* have registered listeners.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.getTypeCount = function() {
|
||||
return this.typeCount_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number} Total number of registered listeners.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.getListenerCount = function() {
|
||||
var count = 0;
|
||||
for (var type in this.listeners) {
|
||||
count += this.listeners[type].length;
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds an event listener. A listener can only be added once to an
|
||||
* object and if it is added again the key for the listener is
|
||||
* returned.
|
||||
*
|
||||
* Note that a one-off listener will not change an existing listener,
|
||||
* if any. On the other hand a normal listener will change existing
|
||||
* one-off listener to become a normal listener.
|
||||
*
|
||||
* @param {string|!goog.events.EventId} type The listener event type.
|
||||
* @param {!Function} listener This listener callback method.
|
||||
* @param {boolean} callOnce Whether the listener is a one-off
|
||||
* listener.
|
||||
* @param {boolean=} opt_useCapture The capture mode of the listener.
|
||||
* @param {Object=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {!goog.events.ListenableKey} Unique key for the listener.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.add = function(
|
||||
type, listener, callOnce, opt_useCapture, opt_listenerScope) {
|
||||
var typeStr = type.toString();
|
||||
var listenerArray = this.listeners[typeStr];
|
||||
if (!listenerArray) {
|
||||
listenerArray = this.listeners[typeStr] = [];
|
||||
this.typeCount_++;
|
||||
}
|
||||
|
||||
var listenerObj;
|
||||
var index = goog.events.ListenerMap.findListenerIndex_(
|
||||
listenerArray, listener, opt_useCapture, opt_listenerScope);
|
||||
if (index > -1) {
|
||||
listenerObj = listenerArray[index];
|
||||
if (!callOnce) {
|
||||
// Ensure that, if there is an existing callOnce listener, it is no
|
||||
// longer a callOnce listener.
|
||||
listenerObj.callOnce = false;
|
||||
}
|
||||
} else {
|
||||
listenerObj = new goog.events.Listener(
|
||||
listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);
|
||||
listenerObj.callOnce = callOnce;
|
||||
listenerArray.push(listenerObj);
|
||||
}
|
||||
return listenerObj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes a matching listener.
|
||||
* @param {string|!goog.events.EventId} type The listener event type.
|
||||
* @param {!Function} listener This listener callback method.
|
||||
* @param {boolean=} opt_useCapture The capture mode of the listener.
|
||||
* @param {Object=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {boolean} Whether any listener was removed.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.remove = function(
|
||||
type, listener, opt_useCapture, opt_listenerScope) {
|
||||
var typeStr = type.toString();
|
||||
if (!(typeStr in this.listeners)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var listenerArray = this.listeners[typeStr];
|
||||
var index = goog.events.ListenerMap.findListenerIndex_(
|
||||
listenerArray, listener, opt_useCapture, opt_listenerScope);
|
||||
if (index > -1) {
|
||||
var listenerObj = listenerArray[index];
|
||||
listenerObj.markAsRemoved();
|
||||
goog.array.removeAt(listenerArray, index);
|
||||
if (listenerArray.length == 0) {
|
||||
delete this.listeners[typeStr];
|
||||
this.typeCount_--;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes the given listener object.
|
||||
* @param {!goog.events.ListenableKey} listener The listener to remove.
|
||||
* @return {boolean} Whether the listener is removed.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.removeByKey = function(listener) {
|
||||
var type = listener.type;
|
||||
if (!(type in this.listeners)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var removed = goog.array.remove(this.listeners[type], listener);
|
||||
if (removed) {
|
||||
/** @type {!goog.events.Listener} */ (listener).markAsRemoved();
|
||||
if (this.listeners[type].length == 0) {
|
||||
delete this.listeners[type];
|
||||
this.typeCount_--;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes all listeners from this map. If opt_type is provided, only
|
||||
* listeners that match the given type are removed.
|
||||
* @param {string|!goog.events.EventId=} opt_type Type of event to remove.
|
||||
* @return {number} Number of listeners removed.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.removeAll = function(opt_type) {
|
||||
var typeStr = opt_type && opt_type.toString();
|
||||
var count = 0;
|
||||
for (var type in this.listeners) {
|
||||
if (!typeStr || type == typeStr) {
|
||||
var listenerArray = this.listeners[type];
|
||||
for (var i = 0; i < listenerArray.length; i++) {
|
||||
++count;
|
||||
listenerArray[i].markAsRemoved();
|
||||
}
|
||||
delete this.listeners[type];
|
||||
this.typeCount_--;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets all listeners that match the given type and capture mode. The
|
||||
* returned array is a copy (but the listener objects are not).
|
||||
* @param {string|!goog.events.EventId} type The type of the listeners
|
||||
* to retrieve.
|
||||
* @param {boolean} capture The capture mode of the listeners to retrieve.
|
||||
* @return {!Array<!goog.events.ListenableKey>} An array of matching
|
||||
* listeners.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.getListeners = function(type, capture) {
|
||||
var listenerArray = this.listeners[type.toString()];
|
||||
var rv = [];
|
||||
if (listenerArray) {
|
||||
for (var i = 0; i < listenerArray.length; ++i) {
|
||||
var listenerObj = listenerArray[i];
|
||||
if (listenerObj.capture == capture) {
|
||||
rv.push(listenerObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets the goog.events.ListenableKey for the event or null if no such
|
||||
* listener is in use.
|
||||
*
|
||||
* @param {string|!goog.events.EventId} type The type of the listener
|
||||
* to retrieve.
|
||||
* @param {!Function} listener The listener function to get.
|
||||
* @param {boolean} capture Whether the listener is a capturing listener.
|
||||
* @param {Object=} opt_listenerScope Object in whose scope to call the
|
||||
* listener.
|
||||
* @return {goog.events.ListenableKey} the found listener or null if not found.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.getListener = function(
|
||||
type, listener, capture, opt_listenerScope) {
|
||||
var listenerArray = this.listeners[type.toString()];
|
||||
var i = -1;
|
||||
if (listenerArray) {
|
||||
i = goog.events.ListenerMap.findListenerIndex_(
|
||||
listenerArray, listener, capture, opt_listenerScope);
|
||||
}
|
||||
return i > -1 ? listenerArray[i] : null;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether there is a matching listener. If either the type or capture
|
||||
* parameters are unspecified, the function will match on the
|
||||
* remaining criteria.
|
||||
*
|
||||
* @param {string|!goog.events.EventId=} opt_type The type of the listener.
|
||||
* @param {boolean=} opt_capture The capture mode of the listener.
|
||||
* @return {boolean} Whether there is an active listener matching
|
||||
* the requested type and/or capture phase.
|
||||
*/
|
||||
goog.events.ListenerMap.prototype.hasListener = function(
|
||||
opt_type, opt_capture) {
|
||||
var hasType = goog.isDef(opt_type);
|
||||
var typeStr = hasType ? opt_type.toString() : '';
|
||||
var hasCapture = goog.isDef(opt_capture);
|
||||
|
||||
return goog.object.some(this.listeners, function(listenerArray, type) {
|
||||
for (var i = 0; i < listenerArray.length; ++i) {
|
||||
if ((!hasType || listenerArray[i].type == typeStr) &&
|
||||
(!hasCapture || listenerArray[i].capture == opt_capture)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Finds the index of a matching goog.events.Listener in the given
|
||||
* listenerArray.
|
||||
* @param {!Array<!goog.events.Listener>} listenerArray Array of listener.
|
||||
* @param {!Function} listener The listener function.
|
||||
* @param {boolean=} opt_useCapture The capture flag for the listener.
|
||||
* @param {Object=} opt_listenerScope The listener scope.
|
||||
* @return {number} The index of the matching listener within the
|
||||
* listenerArray.
|
||||
* @private
|
||||
*/
|
||||
goog.events.ListenerMap.findListenerIndex_ = function(
|
||||
listenerArray, listener, opt_useCapture, opt_listenerScope) {
|
||||
for (var i = 0; i < listenerArray.length; ++i) {
|
||||
var listenerObj = listenerArray[i];
|
||||
if (!listenerObj.removed && listenerObj.listener == listener &&
|
||||
listenerObj.capture == !!opt_useCapture &&
|
||||
listenerObj.handler == opt_listenerScope) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
@@ -0,0 +1,483 @@
|
||||
// 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 functions. Loosely inspired by the
|
||||
* java classes: http://goo.gl/GM0Hmu and http://goo.gl/6k7nI8.
|
||||
*
|
||||
* @author nicksantos@google.com (Nick Santos)
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.functions');
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that always returns the same value.
|
||||
* @param {T} retValue The value to return.
|
||||
* @return {function():T} The new function.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.constant = function(retValue) {
|
||||
return function() { return retValue; };
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Always returns false.
|
||||
* @type {function(...): boolean}
|
||||
*/
|
||||
goog.functions.FALSE = goog.functions.constant(false);
|
||||
|
||||
|
||||
/**
|
||||
* Always returns true.
|
||||
* @type {function(...): boolean}
|
||||
*/
|
||||
goog.functions.TRUE = goog.functions.constant(true);
|
||||
|
||||
|
||||
/**
|
||||
* Always returns NULL.
|
||||
* @type {function(...): null}
|
||||
*/
|
||||
goog.functions.NULL = goog.functions.constant(null);
|
||||
|
||||
|
||||
/**
|
||||
* A simple function that returns the first argument of whatever is passed
|
||||
* into it.
|
||||
* @param {T=} opt_returnValue The single value that will be returned.
|
||||
* @param {...*} var_args Optional trailing arguments. These are ignored.
|
||||
* @return {T} The first argument passed in, or undefined if nothing was passed.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.identity = function(opt_returnValue, var_args) {
|
||||
return opt_returnValue;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that always throws an error with the given message.
|
||||
* @param {string} message The error message.
|
||||
* @return {!Function} The error-throwing function.
|
||||
*/
|
||||
goog.functions.error = function(message) {
|
||||
return function() { throw Error(message); };
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that throws the given object.
|
||||
* @param {*} err An object to be thrown.
|
||||
* @return {!Function} The error-throwing function.
|
||||
*/
|
||||
goog.functions.fail = function(err) {
|
||||
return function() { throw err; };
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Given a function, create a function that keeps opt_numArgs arguments and
|
||||
* silently discards all additional arguments.
|
||||
* @param {Function} f The original function.
|
||||
* @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.
|
||||
* @return {!Function} A version of f that only keeps the first opt_numArgs
|
||||
* arguments.
|
||||
*/
|
||||
goog.functions.lock = function(f, opt_numArgs) {
|
||||
opt_numArgs = opt_numArgs || 0;
|
||||
return function() {
|
||||
return f.apply(this, Array.prototype.slice.call(arguments, 0, opt_numArgs));
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that returns its nth argument.
|
||||
* @param {number} n The position of the return argument.
|
||||
* @return {!Function} A new function.
|
||||
*/
|
||||
goog.functions.nth = function(n) {
|
||||
return function() { return arguments[n]; };
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Like goog.partial(), except that arguments are added after arguments to the
|
||||
* returned function.
|
||||
*
|
||||
* Usage:
|
||||
* function f(arg1, arg2, arg3, arg4) { ... }
|
||||
* var g = goog.functions.partialRight(f, arg3, arg4);
|
||||
* g(arg1, arg2);
|
||||
*
|
||||
* @param {!Function} fn A function to partially apply.
|
||||
* @param {...*} var_args Additional arguments that are partially applied to fn
|
||||
* at the end.
|
||||
* @return {!Function} A partially-applied form of the function goog.partial()
|
||||
* was invoked as a method of.
|
||||
*/
|
||||
goog.functions.partialRight = function(fn, var_args) {
|
||||
var rightArgs = Array.prototype.slice.call(arguments, 1);
|
||||
return function() {
|
||||
var newArgs = Array.prototype.slice.call(arguments);
|
||||
newArgs.push.apply(newArgs, rightArgs);
|
||||
return fn.apply(this, newArgs);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Given a function, create a new function that swallows its return value
|
||||
* and replaces it with a new one.
|
||||
* @param {Function} f A function.
|
||||
* @param {T} retValue A new return value.
|
||||
* @return {function(...?):T} A new function.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.withReturnValue = function(f, retValue) {
|
||||
return goog.functions.sequence(f, goog.functions.constant(retValue));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that returns whether its argument equals the given value.
|
||||
*
|
||||
* Example:
|
||||
* var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));
|
||||
*
|
||||
* @param {*} value The value to compare to.
|
||||
* @param {boolean=} opt_useLooseComparison Whether to use a loose (==)
|
||||
* comparison rather than a strict (===) one. Defaults to false.
|
||||
* @return {function(*):boolean} The new function.
|
||||
*/
|
||||
goog.functions.equalTo = function(value, opt_useLooseComparison) {
|
||||
return function(other) {
|
||||
return opt_useLooseComparison ? (value == other) : (value === other);
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates the composition of the functions passed in.
|
||||
* For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).
|
||||
* @param {function(...?):T} fn The final function.
|
||||
* @param {...Function} var_args A list of functions.
|
||||
* @return {function(...?):T} The composition of all inputs.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.compose = function(fn, var_args) {
|
||||
var functions = arguments;
|
||||
var length = functions.length;
|
||||
return function() {
|
||||
var result;
|
||||
if (length) {
|
||||
result = functions[length - 1].apply(this, arguments);
|
||||
}
|
||||
|
||||
for (var i = length - 2; i >= 0; i--) {
|
||||
result = functions[i].call(this, result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that calls the functions passed in in sequence, and
|
||||
* returns the value of the last function. For example,
|
||||
* (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).
|
||||
* @param {...Function} var_args A list of functions.
|
||||
* @return {!Function} A function that calls all inputs in sequence.
|
||||
*/
|
||||
goog.functions.sequence = function(var_args) {
|
||||
var functions = arguments;
|
||||
var length = functions.length;
|
||||
return function() {
|
||||
var result;
|
||||
for (var i = 0; i < length; i++) {
|
||||
result = functions[i].apply(this, arguments);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that returns true if each of its components evaluates
|
||||
* to true. The components are evaluated in order, and the evaluation will be
|
||||
* short-circuited as soon as a function returns false.
|
||||
* For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).
|
||||
* @param {...Function} var_args A list of functions.
|
||||
* @return {function(...?):boolean} A function that ANDs its component
|
||||
* functions.
|
||||
*/
|
||||
goog.functions.and = function(var_args) {
|
||||
var functions = arguments;
|
||||
var length = functions.length;
|
||||
return function() {
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (!functions[i].apply(this, arguments)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that returns true if any of its components evaluates
|
||||
* to true. The components are evaluated in order, and the evaluation will be
|
||||
* short-circuited as soon as a function returns true.
|
||||
* For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).
|
||||
* @param {...Function} var_args A list of functions.
|
||||
* @return {function(...?):boolean} A function that ORs its component
|
||||
* functions.
|
||||
*/
|
||||
goog.functions.or = function(var_args) {
|
||||
var functions = arguments;
|
||||
var length = functions.length;
|
||||
return function() {
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (functions[i].apply(this, arguments)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a function that returns the Boolean opposite of a provided function.
|
||||
* For example, (goog.functions.not(f))(x) is equivalent to !f(x).
|
||||
* @param {!Function} f The original function.
|
||||
* @return {function(...?):boolean} A function that delegates to f and returns
|
||||
* opposite.
|
||||
*/
|
||||
goog.functions.not = function(f) {
|
||||
return function() { return !f.apply(this, arguments); };
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Generic factory function to construct an object given the constructor
|
||||
* and the arguments. Intended to be bound to create object factories.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* var factory = goog.partial(goog.functions.create, Class);
|
||||
*
|
||||
* @param {function(new:T, ...)} constructor The constructor for the Object.
|
||||
* @param {...*} var_args The arguments to be passed to the constructor.
|
||||
* @return {T} A new instance of the class given in {@code constructor}.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.create = function(constructor, var_args) {
|
||||
/**
|
||||
* @constructor
|
||||
* @final
|
||||
*/
|
||||
var temp = function() {};
|
||||
temp.prototype = constructor.prototype;
|
||||
|
||||
// obj will have constructor's prototype in its chain and
|
||||
// 'obj instanceof constructor' will be true.
|
||||
var obj = new temp();
|
||||
|
||||
// obj is initialized by constructor.
|
||||
// arguments is only array-like so lacks shift(), but can be used with
|
||||
// the Array prototype function.
|
||||
constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
|
||||
return obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the return value cache should be used.
|
||||
* This should only be used to disable caches when testing.
|
||||
*/
|
||||
goog.define('goog.functions.CACHE_RETURN_VALUE', true);
|
||||
|
||||
|
||||
/**
|
||||
* Gives a wrapper function that caches the return value of a parameterless
|
||||
* function when first called.
|
||||
*
|
||||
* When called for the first time, the given function is called and its
|
||||
* return value is cached (thus this is only appropriate for idempotent
|
||||
* functions). Subsequent calls will return the cached return value. This
|
||||
* allows the evaluation of expensive functions to be delayed until first used.
|
||||
*
|
||||
* To cache the return values of functions with parameters, see goog.memoize.
|
||||
*
|
||||
* @param {function():T} fn A function to lazily evaluate.
|
||||
* @return {function():T} A wrapped version the function.
|
||||
* @template T
|
||||
*/
|
||||
goog.functions.cacheReturnValue = function(fn) {
|
||||
var called = false;
|
||||
var value;
|
||||
|
||||
return function() {
|
||||
if (!goog.functions.CACHE_RETURN_VALUE) {
|
||||
return fn();
|
||||
}
|
||||
|
||||
if (!called) {
|
||||
value = fn();
|
||||
called = true;
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Wraps a function to allow it to be called, at most, once. All
|
||||
* additional calls are no-ops.
|
||||
*
|
||||
* This is particularly useful for initialization functions
|
||||
* that should be called, at most, once.
|
||||
*
|
||||
* @param {function():*} f Function to call.
|
||||
* @return {function():undefined} Wrapped function.
|
||||
*/
|
||||
goog.functions.once = function(f) {
|
||||
// Keep a reference to the function that we null out when we're done with
|
||||
// it -- that way, the function can be GC'd when we're done with it.
|
||||
var inner = f;
|
||||
return function() {
|
||||
if (inner) {
|
||||
var tmp = inner;
|
||||
inner = null;
|
||||
tmp();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Wraps a function to allow it to be called, at most, once per interval
|
||||
* (specified in milliseconds). If the wrapper function is called N times within
|
||||
* that interval, only the Nth call will go through.
|
||||
*
|
||||
* This is particularly useful for batching up repeated actions where the
|
||||
* last action should win. This can be used, for example, for refreshing an
|
||||
* autocomplete pop-up every so often rather than updating with every keystroke,
|
||||
* since the final text typed by the user is the one that should produce the
|
||||
* final autocomplete results. For more stateful debouncing with support for
|
||||
* pausing, resuming, and canceling debounced actions, use {@code
|
||||
* goog.async.Debouncer}.
|
||||
*
|
||||
* @param {function(this:SCOPE, ...?)} f Function to call.
|
||||
* @param {number} interval Interval over which to debounce. The function will
|
||||
* only be called after the full interval has elapsed since the last call.
|
||||
* @param {SCOPE=} opt_scope Object in whose scope to call the function.
|
||||
* @return {function(...?): undefined} Wrapped function.
|
||||
* @template SCOPE
|
||||
*/
|
||||
goog.functions.debounce = function(f, interval, opt_scope) {
|
||||
var timeout = 0;
|
||||
return /** @type {function(...?)} */ (function(var_args) {
|
||||
goog.global.clearTimeout(timeout);
|
||||
var args = arguments;
|
||||
timeout = goog.global.setTimeout(function() {
|
||||
f.apply(opt_scope, args);
|
||||
}, interval);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Wraps a function to allow it to be called, at most, once per interval
|
||||
* (specified in milliseconds). If the wrapper function is called N times in
|
||||
* that interval, both the 1st and the Nth calls will go through.
|
||||
*
|
||||
* This is particularly useful for limiting repeated user requests where the
|
||||
* the last action should win, but you also don't want to wait until the end of
|
||||
* the interval before sending a request out, as it leads to a perception of
|
||||
* slowness for the user.
|
||||
*
|
||||
* @param {function(this:SCOPE, ...?)} f Function to call.
|
||||
* @param {number} interval Interval over which to throttle. The function can
|
||||
* only be called once per interval.
|
||||
* @param {SCOPE=} opt_scope Object in whose scope to call the function.
|
||||
* @return {function(...?): undefined} Wrapped function.
|
||||
* @template SCOPE
|
||||
*/
|
||||
goog.functions.throttle = function(f, interval, opt_scope) {
|
||||
var timeout = 0;
|
||||
var shouldFire = false;
|
||||
var args = [];
|
||||
|
||||
var handleTimeout = function() {
|
||||
timeout = 0;
|
||||
if (shouldFire) {
|
||||
shouldFire = false;
|
||||
fire();
|
||||
}
|
||||
};
|
||||
|
||||
var fire = function() {
|
||||
timeout = goog.global.setTimeout(handleTimeout, interval);
|
||||
f.apply(opt_scope, args);
|
||||
};
|
||||
|
||||
return /** @type {function(...?)} */ (function(var_args) {
|
||||
args = arguments;
|
||||
if (!timeout) {
|
||||
fire();
|
||||
} else {
|
||||
shouldFire = true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Wraps a function to allow it to be called, at most, once per interval
|
||||
* (specified in milliseconds). If the wrapper function is called N times within
|
||||
* that interval, only the 1st call will go through.
|
||||
*
|
||||
* This is particularly useful for limiting repeated user requests where the
|
||||
* first request is guaranteed to have all the data required to perform the
|
||||
* final action, so there's no need to wait until the end of the interval before
|
||||
* sending the request out.
|
||||
*
|
||||
* @param {function(this:SCOPE, ...?)} f Function to call.
|
||||
* @param {number} interval Interval over which to rate-limit. The function will
|
||||
* only be called once per interval, and ignored for the remainer of the
|
||||
* interval.
|
||||
* @param {SCOPE=} opt_scope Object in whose scope to call the function.
|
||||
* @return {function(...?): undefined} Wrapped function.
|
||||
* @template SCOPE
|
||||
*/
|
||||
goog.functions.rateLimit = function(f, interval, opt_scope) {
|
||||
var timeout = 0;
|
||||
|
||||
var handleTimeout = function() {
|
||||
timeout = 0;
|
||||
};
|
||||
|
||||
return /** @type {function(...?)} */ (function(var_args) {
|
||||
if (!timeout) {
|
||||
timeout = goog.global.setTimeout(handleTimeout, interval);
|
||||
f.apply(opt_scope, arguments);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
// 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 The event object dispatched when the history changes.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.history.Event');
|
||||
|
||||
goog.require('goog.events.Event');
|
||||
goog.require('goog.history.EventType');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Event object dispatched after the history state has changed.
|
||||
* @param {string} token The string identifying the new history state.
|
||||
* @param {boolean} isNavigation True if the event was triggered by a browser
|
||||
* action, such as forward or back, clicking on a link, editing the URL, or
|
||||
* calling {@code window.history.(go|back|forward)}.
|
||||
* False if the token has been changed by a {@code setToken} or
|
||||
* {@code replaceToken} call.
|
||||
* @constructor
|
||||
* @extends {goog.events.Event}
|
||||
* @final
|
||||
*/
|
||||
goog.history.Event = function(token, isNavigation) {
|
||||
goog.events.Event.call(this, goog.history.EventType.NAVIGATE);
|
||||
|
||||
/**
|
||||
* The current history state.
|
||||
* @type {string}
|
||||
*/
|
||||
this.token = token;
|
||||
|
||||
/**
|
||||
* Whether the event was triggered by browser navigation.
|
||||
* @type {boolean}
|
||||
*/
|
||||
this.isNavigation = isNavigation;
|
||||
};
|
||||
goog.inherits(goog.history.Event, goog.events.Event);
|
||||
@@ -0,0 +1,30 @@
|
||||
// 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 Event types for goog.history.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.history.EventType');
|
||||
|
||||
|
||||
/**
|
||||
* Event types for goog.history.
|
||||
* @enum {string}
|
||||
*/
|
||||
goog.history.EventType = {
|
||||
NAVIGATE: 'navigate'
|
||||
};
|
||||
@@ -0,0 +1,342 @@
|
||||
// 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 HTML5 based history implementation, compatible with
|
||||
* goog.History.
|
||||
*
|
||||
* TODO(user): There should really be a history interface and multiple
|
||||
* implementations.
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.history.Html5History');
|
||||
goog.provide('goog.history.Html5History.TokenTransformer');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.events');
|
||||
goog.require('goog.events.EventTarget');
|
||||
goog.require('goog.events.EventType');
|
||||
goog.require('goog.history.Event');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* An implementation compatible with goog.History that uses the HTML5
|
||||
* history APIs.
|
||||
*
|
||||
* @param {Window=} opt_win The window to listen/dispatch history events on.
|
||||
* @param {goog.history.Html5History.TokenTransformer=} opt_transformer
|
||||
* The token transformer that is used to create URL from the token
|
||||
* when storing token without using hash fragment.
|
||||
* @constructor
|
||||
* @extends {goog.events.EventTarget}
|
||||
* @final
|
||||
*/
|
||||
goog.history.Html5History = function(opt_win, opt_transformer) {
|
||||
goog.events.EventTarget.call(this);
|
||||
goog.asserts.assert(
|
||||
goog.history.Html5History.isSupported(opt_win),
|
||||
'HTML5 history is not supported.');
|
||||
|
||||
/**
|
||||
* The window object to use for history tokens. Typically the top window.
|
||||
* @type {Window}
|
||||
* @private
|
||||
*/
|
||||
this.window_ = opt_win || window;
|
||||
|
||||
/**
|
||||
* The token transformer that is used to create URL from the token
|
||||
* when storing token without using hash fragment.
|
||||
* @type {goog.history.Html5History.TokenTransformer}
|
||||
* @private
|
||||
*/
|
||||
this.transformer_ = opt_transformer || null;
|
||||
|
||||
/**
|
||||
* The fragment of the last navigation. Used to eliminate duplicate/redundant
|
||||
* NAVIGATE events when a POPSTATE and HASHCHANGE event are triggered for the
|
||||
* same navigation (e.g., back button click).
|
||||
* @private {?string}
|
||||
*/
|
||||
this.lastFragment_ = null;
|
||||
|
||||
goog.events.listen(
|
||||
this.window_, goog.events.EventType.POPSTATE, this.onHistoryEvent_, false,
|
||||
this);
|
||||
goog.events.listen(
|
||||
this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_,
|
||||
false, this);
|
||||
};
|
||||
goog.inherits(goog.history.Html5History, goog.events.EventTarget);
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether Html5History is supported.
|
||||
* @param {Window=} opt_win Optional window to check.
|
||||
* @return {boolean} Whether html5 history is supported.
|
||||
*/
|
||||
goog.history.Html5History.isSupported = function(opt_win) {
|
||||
var win = opt_win || window;
|
||||
return !!(win.history && win.history.pushState);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Status of when the object is active and dispatching events.
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.enabled_ = false;
|
||||
|
||||
|
||||
/**
|
||||
* Whether to use the fragment to store the token, defaults to true.
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.useFragment_ = true;
|
||||
|
||||
|
||||
/**
|
||||
* If useFragment is false the path will be used, the path prefix will be
|
||||
* prepended to all tokens. Defaults to '/'.
|
||||
* @type {string}
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.pathPrefix_ = '/';
|
||||
|
||||
|
||||
/**
|
||||
* Starts or stops the History. When enabled, the History object
|
||||
* will immediately fire an event for the current location. The caller can set
|
||||
* up event listeners between the call to the constructor and the call to
|
||||
* setEnabled.
|
||||
*
|
||||
* @param {boolean} enable Whether to enable history.
|
||||
*/
|
||||
goog.history.Html5History.prototype.setEnabled = function(enable) {
|
||||
if (enable == this.enabled_) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.enabled_ = enable;
|
||||
|
||||
if (enable) {
|
||||
this.dispatchEvent(new goog.history.Event(this.getToken(), false));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the current token.
|
||||
* @return {string} The current token.
|
||||
*/
|
||||
goog.history.Html5History.prototype.getToken = function() {
|
||||
if (this.useFragment_) {
|
||||
return goog.asserts.assertString(this.getFragment_());
|
||||
} else {
|
||||
return this.transformer_ ?
|
||||
this.transformer_.retrieveToken(
|
||||
this.pathPrefix_, this.window_.location) :
|
||||
this.window_.location.pathname.substr(this.pathPrefix_.length);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets the history state.
|
||||
* @param {string} token The history state identifier.
|
||||
* @param {string=} opt_title Optional title to associate with history entry.
|
||||
*/
|
||||
goog.history.Html5History.prototype.setToken = function(token, opt_title) {
|
||||
if (token == this.getToken()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Per externs/gecko_dom.js document.title can be null.
|
||||
this.window_.history.pushState(
|
||||
null, opt_title || this.window_.document.title || '',
|
||||
this.getUrl_(token));
|
||||
this.dispatchEvent(new goog.history.Event(token, false));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Replaces the current history state without affecting the rest of the history
|
||||
* stack.
|
||||
* @param {string} token The history state identifier.
|
||||
* @param {string=} opt_title Optional title to associate with history entry.
|
||||
*/
|
||||
goog.history.Html5History.prototype.replaceToken = function(token, opt_title) {
|
||||
// Per externs/gecko_dom.js document.title can be null.
|
||||
this.window_.history.replaceState(
|
||||
null, opt_title || this.window_.document.title || '',
|
||||
this.getUrl_(token));
|
||||
this.dispatchEvent(new goog.history.Event(token, false));
|
||||
};
|
||||
|
||||
|
||||
/** @override */
|
||||
goog.history.Html5History.prototype.disposeInternal = function() {
|
||||
goog.events.unlisten(
|
||||
this.window_, goog.events.EventType.POPSTATE, this.onHistoryEvent_, false,
|
||||
this);
|
||||
if (this.useFragment_) {
|
||||
goog.events.unlisten(
|
||||
this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_,
|
||||
false, this);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets whether to use the fragment to store tokens.
|
||||
* @param {boolean} useFragment Whether to use the fragment.
|
||||
*/
|
||||
goog.history.Html5History.prototype.setUseFragment = function(useFragment) {
|
||||
if (this.useFragment_ != useFragment) {
|
||||
if (useFragment) {
|
||||
goog.events.listen(
|
||||
this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_,
|
||||
false, this);
|
||||
} else {
|
||||
goog.events.unlisten(
|
||||
this.window_, goog.events.EventType.HASHCHANGE, this.onHistoryEvent_,
|
||||
false, this);
|
||||
}
|
||||
this.useFragment_ = useFragment;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets the path prefix to use if storing tokens in the path. The path
|
||||
* prefix should start and end with slash.
|
||||
* @param {string} pathPrefix Sets the path prefix.
|
||||
*/
|
||||
goog.history.Html5History.prototype.setPathPrefix = function(pathPrefix) {
|
||||
this.pathPrefix_ = pathPrefix;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets the path prefix.
|
||||
* @return {string} The path prefix.
|
||||
*/
|
||||
goog.history.Html5History.prototype.getPathPrefix = function() {
|
||||
return this.pathPrefix_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets the current hash fragment, if useFragment_ is enabled.
|
||||
* @return {?string} The hash fragment.
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.getFragment_ = function() {
|
||||
if (this.useFragment_) {
|
||||
var loc = this.window_.location.href;
|
||||
var index = loc.indexOf('#');
|
||||
return index < 0 ? '' : loc.substring(index + 1);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Gets the URL to set when calling history.pushState
|
||||
* @param {string} token The history token.
|
||||
* @return {string} The URL.
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.getUrl_ = function(token) {
|
||||
if (this.useFragment_) {
|
||||
return '#' + token;
|
||||
} else {
|
||||
return this.transformer_ ?
|
||||
this.transformer_.createUrl(
|
||||
token, this.pathPrefix_, this.window_.location) :
|
||||
this.pathPrefix_ + token + this.window_.location.search;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Handles history events dispatched by the browser.
|
||||
* @param {goog.events.BrowserEvent} e The browser event object.
|
||||
* @private
|
||||
*/
|
||||
goog.history.Html5History.prototype.onHistoryEvent_ = function(e) {
|
||||
if (this.enabled_) {
|
||||
var fragment = this.getFragment_();
|
||||
// Only fire NAVIGATE event if it's POPSTATE or if the fragment has changed
|
||||
// without a POPSTATE event. The latter is an indication the browser doesn't
|
||||
// support POPSTATE, and the event is a HASHCHANGE instead.
|
||||
if (e.type == goog.events.EventType.POPSTATE ||
|
||||
fragment != this.lastFragment_) {
|
||||
this.lastFragment_ = fragment;
|
||||
this.dispatchEvent(new goog.history.Event(this.getToken(), true));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* A token transformer that can create a URL from a history
|
||||
* token. This is used by {@code goog.history.Html5History} to create
|
||||
* URL when storing token without the hash fragment.
|
||||
*
|
||||
* Given a {@code window.location} object containing the location
|
||||
* created by {@code createUrl}, the token transformer allows
|
||||
* retrieval of the token back via {@code retrieveToken}.
|
||||
*
|
||||
* @interface
|
||||
*/
|
||||
goog.history.Html5History.TokenTransformer = function() {};
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves a history token given the path prefix and
|
||||
* {@code window.location} object.
|
||||
*
|
||||
* @param {string} pathPrefix The path prefix to use when storing token
|
||||
* in a path; always begin with a slash.
|
||||
* @param {Location} location The {@code window.location} object.
|
||||
* Treat this object as read-only.
|
||||
* @return {string} token The history token.
|
||||
*/
|
||||
goog.history.Html5History.TokenTransformer.prototype.retrieveToken = function(
|
||||
pathPrefix, location) {};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a URL to be pushed into HTML5 history stack when storing
|
||||
* token without using hash fragment.
|
||||
*
|
||||
* @param {string} token The history token.
|
||||
* @param {string} pathPrefix The path prefix to use when storing token
|
||||
* in a path; always begin with a slash.
|
||||
* @param {Location} location The {@code window.location} object.
|
||||
* Treat this object as read-only.
|
||||
* @return {string} url The complete URL string from path onwards
|
||||
* (without {@code protocol://host:port} part); must begin with a
|
||||
* slash.
|
||||
*/
|
||||
goog.history.Html5History.TokenTransformer.prototype.createUrl = function(
|
||||
token, pathPrefix, location) {};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,338 @@
|
||||
// Copyright 2013 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 Closure user agent detection (Browser).
|
||||
* @see <a href="http://www.useragentstring.com/">User agent strings</a>
|
||||
* For more information on rendering engine, platform, or device see the other
|
||||
* sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,
|
||||
* goog.labs.userAgent.device respectively.)
|
||||
*
|
||||
* @author martone@google.com (Andy Martone)
|
||||
*/
|
||||
|
||||
goog.provide('goog.labs.userAgent.browser');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.labs.userAgent.util');
|
||||
goog.require('goog.object');
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
// TODO(nnaze): Refactor to remove excessive exclusion logic in matching
|
||||
// functions.
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Opera. Note: Chromium
|
||||
* based Opera (Opera 15+) is detected as Chrome to avoid unnecessary
|
||||
* special casing.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchOpera_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Opera');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is IE.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchIE_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Trident') ||
|
||||
goog.labs.userAgent.util.matchUserAgent('MSIE');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Edge.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchEdge_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Edge');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Firefox.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchFirefox_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Firefox');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Safari.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchSafari_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Safari') &&
|
||||
!(goog.labs.userAgent.browser.matchChrome_() ||
|
||||
goog.labs.userAgent.browser.matchCoast_() ||
|
||||
goog.labs.userAgent.browser.matchOpera_() ||
|
||||
goog.labs.userAgent.browser.matchEdge_() ||
|
||||
goog.labs.userAgent.browser.isSilk() ||
|
||||
goog.labs.userAgent.util.matchUserAgent('Android'));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based
|
||||
* iOS browser).
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchCoast_ = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Coast');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is iOS Webview.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchIosWebview_ = function() {
|
||||
// iOS Webview does not show up as Chrome or Safari. Also check for Opera's
|
||||
// WebKit-based iOS browser, Coast.
|
||||
return (goog.labs.userAgent.util.matchUserAgent('iPad') ||
|
||||
goog.labs.userAgent.util.matchUserAgent('iPhone')) &&
|
||||
!goog.labs.userAgent.browser.matchSafari_() &&
|
||||
!goog.labs.userAgent.browser.matchChrome_() &&
|
||||
!goog.labs.userAgent.browser.matchCoast_() &&
|
||||
goog.labs.userAgent.util.matchUserAgent('AppleWebKit');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Chrome.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchChrome_ = function() {
|
||||
return (goog.labs.userAgent.util.matchUserAgent('Chrome') ||
|
||||
goog.labs.userAgent.util.matchUserAgent('CriOS')) &&
|
||||
!goog.labs.userAgent.browser.matchEdge_();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is the Android browser.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.matchAndroidBrowser_ = function() {
|
||||
// Android can appear in the user agent string for Chrome on Android.
|
||||
// This is not the Android standalone browser if it does.
|
||||
return goog.labs.userAgent.util.matchUserAgent('Android') &&
|
||||
!(goog.labs.userAgent.browser.isChrome() ||
|
||||
goog.labs.userAgent.browser.isFirefox() ||
|
||||
goog.labs.userAgent.browser.isOpera() ||
|
||||
goog.labs.userAgent.browser.isSilk());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Opera.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is IE.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Edge.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdge_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Firefox.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isFirefox =
|
||||
goog.labs.userAgent.browser.matchFirefox_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Safari.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based
|
||||
* iOS browser).
|
||||
*/
|
||||
goog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is iOS Webview.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isIosWebview =
|
||||
goog.labs.userAgent.browser.matchIosWebview_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is Chrome.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_;
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user's browser is the Android browser.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isAndroidBrowser =
|
||||
goog.labs.userAgent.browser.matchAndroidBrowser_;
|
||||
|
||||
|
||||
/**
|
||||
* For more information, see:
|
||||
* http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html
|
||||
* @return {boolean} Whether the user's browser is Silk.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isSilk = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Silk');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {string} The browser version or empty string if version cannot be
|
||||
* determined. Note that for Internet Explorer, this returns the version of
|
||||
* the browser, not the version of the rendering engine. (IE 8 in
|
||||
* compatibility mode will return 8.0 rather than 7.0. To determine the
|
||||
* rendering engine version, look at document.documentMode instead. See
|
||||
* http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more
|
||||
* details.)
|
||||
*/
|
||||
goog.labs.userAgent.browser.getVersion = function() {
|
||||
var userAgentString = goog.labs.userAgent.util.getUserAgent();
|
||||
// Special case IE since IE's version is inside the parenthesis and
|
||||
// without the '/'.
|
||||
if (goog.labs.userAgent.browser.isIE()) {
|
||||
return goog.labs.userAgent.browser.getIEVersion_(userAgentString);
|
||||
}
|
||||
|
||||
var versionTuples =
|
||||
goog.labs.userAgent.util.extractVersionTuples(userAgentString);
|
||||
|
||||
// Construct a map for easy lookup.
|
||||
var versionMap = {};
|
||||
goog.array.forEach(versionTuples, function(tuple) {
|
||||
// Note that the tuple is of length three, but we only care about the
|
||||
// first two.
|
||||
var key = tuple[0];
|
||||
var value = tuple[1];
|
||||
versionMap[key] = value;
|
||||
});
|
||||
|
||||
var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap);
|
||||
|
||||
// Gives the value with the first key it finds, otherwise empty string.
|
||||
function lookUpValueWithKeys(keys) {
|
||||
var key = goog.array.find(keys, versionMapHasKey);
|
||||
return versionMap[key] || '';
|
||||
}
|
||||
|
||||
// Check Opera before Chrome since Opera 15+ has "Chrome" in the string.
|
||||
// See
|
||||
// http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond
|
||||
if (goog.labs.userAgent.browser.isOpera()) {
|
||||
// Opera 10 has Version/10.0 but Opera/9.8, so look for "Version" first.
|
||||
// Opera uses 'OPR' for more recent UAs.
|
||||
return lookUpValueWithKeys(['Version', 'Opera']);
|
||||
}
|
||||
|
||||
// Check Edge before Chrome since it has Chrome in the string.
|
||||
if (goog.labs.userAgent.browser.isEdge()) {
|
||||
return lookUpValueWithKeys(['Edge']);
|
||||
}
|
||||
|
||||
if (goog.labs.userAgent.browser.isChrome()) {
|
||||
return lookUpValueWithKeys(['Chrome', 'CriOS']);
|
||||
}
|
||||
|
||||
// Usually products browser versions are in the third tuple after "Mozilla"
|
||||
// and the engine.
|
||||
var tuple = versionTuples[2];
|
||||
return tuple && tuple[1] || '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string|number} version The version to check.
|
||||
* @return {boolean} Whether the browser version is higher or the same as the
|
||||
* given version.
|
||||
*/
|
||||
goog.labs.userAgent.browser.isVersionOrHigher = function(version) {
|
||||
return goog.string.compareVersions(
|
||||
goog.labs.userAgent.browser.getVersion(), version) >= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Determines IE version. More information:
|
||||
* http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString
|
||||
* http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
|
||||
* http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx
|
||||
* http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx
|
||||
*
|
||||
* @param {string} userAgent the User-Agent.
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.browser.getIEVersion_ = function(userAgent) {
|
||||
// IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade
|
||||
// bug. Example UA:
|
||||
// Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)
|
||||
// like Gecko.
|
||||
// See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.
|
||||
var rv = /rv: *([\d\.]*)/.exec(userAgent);
|
||||
if (rv && rv[1]) {
|
||||
return rv[1];
|
||||
}
|
||||
|
||||
var version = '';
|
||||
var msie = /MSIE +([\d\.]+)/.exec(userAgent);
|
||||
if (msie && msie[1]) {
|
||||
// IE in compatibility mode usually identifies itself as MSIE 7.0; in this
|
||||
// case, use the Trident version to determine the version of IE. For more
|
||||
// details, see the links above.
|
||||
var tridentVersion = /Trident\/(\d.\d)/.exec(userAgent);
|
||||
if (msie[1] == '7.0') {
|
||||
if (tridentVersion && tridentVersion[1]) {
|
||||
switch (tridentVersion[1]) {
|
||||
case '4.0':
|
||||
version = '8.0';
|
||||
break;
|
||||
case '5.0':
|
||||
version = '9.0';
|
||||
break;
|
||||
case '6.0':
|
||||
version = '10.0';
|
||||
break;
|
||||
case '7.0':
|
||||
version = '11.0';
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
version = '7.0';
|
||||
}
|
||||
} else {
|
||||
version = msie[1];
|
||||
}
|
||||
}
|
||||
return version;
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
// Copyright 2013 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 Closure user agent detection.
|
||||
* @see http://en.wikipedia.org/wiki/User_agent
|
||||
* For more information on browser brand, platform, or device see the other
|
||||
* sub-namespaces in goog.labs.userAgent (browser, platform, and device).
|
||||
*
|
||||
*/
|
||||
|
||||
goog.provide('goog.labs.userAgent.engine');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.labs.userAgent.util');
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the rendering engine is Presto.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isPresto = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Presto');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the rendering engine is Trident.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isTrident = function() {
|
||||
// IE only started including the Trident token in IE8.
|
||||
return goog.labs.userAgent.util.matchUserAgent('Trident') ||
|
||||
goog.labs.userAgent.util.matchUserAgent('MSIE');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the rendering engine is Edge.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isEdge = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Edge');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the rendering engine is WebKit.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isWebKit = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&
|
||||
!goog.labs.userAgent.engine.isEdge();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the rendering engine is Gecko.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isGecko = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Gecko') &&
|
||||
!goog.labs.userAgent.engine.isWebKit() &&
|
||||
!goog.labs.userAgent.engine.isTrident() &&
|
||||
!goog.labs.userAgent.engine.isEdge();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {string} The rendering engine's version or empty string if version
|
||||
* can't be determined.
|
||||
*/
|
||||
goog.labs.userAgent.engine.getVersion = function() {
|
||||
var userAgentString = goog.labs.userAgent.util.getUserAgent();
|
||||
if (userAgentString) {
|
||||
var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString);
|
||||
|
||||
var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);
|
||||
if (engineTuple) {
|
||||
// In Gecko, the version string is either in the browser info or the
|
||||
// Firefox version. See Gecko user agent string reference:
|
||||
// http://goo.gl/mULqa
|
||||
if (engineTuple[0] == 'Gecko') {
|
||||
return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox');
|
||||
}
|
||||
|
||||
return engineTuple[1];
|
||||
}
|
||||
|
||||
// MSIE has only one version identifier, and the Trident version is
|
||||
// specified in the parenthetical. IE Edge is covered in the engine tuple
|
||||
// detection.
|
||||
var browserTuple = tuples[0];
|
||||
var info;
|
||||
if (browserTuple && (info = browserTuple[2])) {
|
||||
var match = /Trident\/([^\s;]+)/.exec(info);
|
||||
if (match) {
|
||||
return match[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {!Array<!Array<string>>} tuples Extracted version tuples.
|
||||
* @return {!Array<string>|undefined} The engine tuple or undefined if not
|
||||
* found.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {
|
||||
if (!goog.labs.userAgent.engine.isEdge()) {
|
||||
return tuples[1];
|
||||
}
|
||||
for (var i = 0; i < tuples.length; i++) {
|
||||
var tuple = tuples[i];
|
||||
if (tuple[0] == 'Edge') {
|
||||
return tuple;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string|number} version The version to check.
|
||||
* @return {boolean} Whether the rendering engine version is higher or the same
|
||||
* as the given version.
|
||||
*/
|
||||
goog.labs.userAgent.engine.isVersionOrHigher = function(version) {
|
||||
return goog.string.compareVersions(
|
||||
goog.labs.userAgent.engine.getVersion(), version) >= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {!Array<!Array<string>>} tuples Version tuples.
|
||||
* @param {string} key The key to look for.
|
||||
* @return {string} The version string of the given key, if present.
|
||||
* Otherwise, the empty string.
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {
|
||||
// TODO(nnaze): Move to util if useful elsewhere.
|
||||
|
||||
var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; });
|
||||
|
||||
return pair && pair[1] || '';
|
||||
};
|
||||
@@ -0,0 +1,160 @@
|
||||
// Copyright 2013 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 Closure user agent platform detection.
|
||||
* @see <a href="http://www.useragentstring.com/">User agent strings</a>
|
||||
* For more information on browser brand, rendering engine, or device see the
|
||||
* other sub-namespaces in goog.labs.userAgent (browser, engine, and device
|
||||
* respectively).
|
||||
*
|
||||
*/
|
||||
|
||||
goog.provide('goog.labs.userAgent.platform');
|
||||
|
||||
goog.require('goog.labs.userAgent.util');
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is Android.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isAndroid = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Android');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is iPod.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isIpod = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('iPod');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is iPhone.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isIphone = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('iPhone') &&
|
||||
!goog.labs.userAgent.util.matchUserAgent('iPod') &&
|
||||
!goog.labs.userAgent.util.matchUserAgent('iPad');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is iPad.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isIpad = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('iPad');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is iOS.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isIos = function() {
|
||||
return goog.labs.userAgent.platform.isIphone() ||
|
||||
goog.labs.userAgent.platform.isIpad() ||
|
||||
goog.labs.userAgent.platform.isIpod();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is Mac.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isMacintosh = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Macintosh');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Note: ChromeOS is not considered to be Linux as it does not report itself
|
||||
* as Linux in the user agent string.
|
||||
* @return {boolean} Whether the platform is Linux.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isLinux = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Linux');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is Windows.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isWindows = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('Windows');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the platform is ChromeOS.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isChromeOS = function() {
|
||||
return goog.labs.userAgent.util.matchUserAgent('CrOS');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The version of the platform. We only determine the version for Windows,
|
||||
* Mac, and Chrome OS. It doesn't make much sense on Linux. For Windows, we only
|
||||
* look at the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given
|
||||
* version 0.0.
|
||||
*
|
||||
* @return {string} The platform version or empty string if version cannot be
|
||||
* determined.
|
||||
*/
|
||||
goog.labs.userAgent.platform.getVersion = function() {
|
||||
var userAgentString = goog.labs.userAgent.util.getUserAgent();
|
||||
var version = '', re;
|
||||
if (goog.labs.userAgent.platform.isWindows()) {
|
||||
re = /Windows (?:NT|Phone) ([0-9.]+)/;
|
||||
var match = re.exec(userAgentString);
|
||||
if (match) {
|
||||
version = match[1];
|
||||
} else {
|
||||
version = '0.0';
|
||||
}
|
||||
} else if (goog.labs.userAgent.platform.isIos()) {
|
||||
re = /(?:iPhone|iPod|iPad|CPU)\s+OS\s+(\S+)/;
|
||||
var match = re.exec(userAgentString);
|
||||
// Report the version as x.y.z and not x_y_z
|
||||
version = match && match[1].replace(/_/g, '.');
|
||||
} else if (goog.labs.userAgent.platform.isMacintosh()) {
|
||||
re = /Mac OS X ([0-9_.]+)/;
|
||||
var match = re.exec(userAgentString);
|
||||
// Note: some old versions of Camino do not report an OSX version.
|
||||
// Default to 10.
|
||||
version = match ? match[1].replace(/_/g, '.') : '10';
|
||||
} else if (goog.labs.userAgent.platform.isAndroid()) {
|
||||
re = /Android\s+([^\);]+)(\)|;)/;
|
||||
var match = re.exec(userAgentString);
|
||||
version = match && match[1];
|
||||
} else if (goog.labs.userAgent.platform.isChromeOS()) {
|
||||
re = /(?:CrOS\s+(?:i686|x86_64)\s+([0-9.]+))/;
|
||||
var match = re.exec(userAgentString);
|
||||
version = match && match[1];
|
||||
}
|
||||
return version || '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string|number} version The version to check.
|
||||
* @return {boolean} Whether the browser version is higher or the same as the
|
||||
* given version.
|
||||
*/
|
||||
goog.labs.userAgent.platform.isVersionOrHigher = function(version) {
|
||||
return goog.string.compareVersions(
|
||||
goog.labs.userAgent.platform.getVersion(), version) >= 0;
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
// Copyright 2013 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 used by goog.labs.userAgent tools. These functions
|
||||
* should not be used outside of goog.labs.userAgent.*.
|
||||
*
|
||||
*
|
||||
* @author nnaze@google.com (Nathan Naze)
|
||||
*/
|
||||
|
||||
goog.provide('goog.labs.userAgent.util');
|
||||
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* Gets the native userAgent string from navigator if it exists.
|
||||
* If navigator or navigator.userAgent string is missing, returns an empty
|
||||
* string.
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.util.getNativeUserAgentString_ = function() {
|
||||
var navigator = goog.labs.userAgent.util.getNavigator_();
|
||||
if (navigator) {
|
||||
var userAgent = navigator.userAgent;
|
||||
if (userAgent) {
|
||||
return userAgent;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Getter for the native navigator.
|
||||
* This is a separate function so it can be stubbed out in testing.
|
||||
* @return {Navigator}
|
||||
* @private
|
||||
*/
|
||||
goog.labs.userAgent.util.getNavigator_ = function() {
|
||||
return goog.global.navigator;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A possible override for applications which wish to not check
|
||||
* navigator.userAgent but use a specified value for detection instead.
|
||||
* @private {string}
|
||||
*/
|
||||
goog.labs.userAgent.util.userAgent_ =
|
||||
goog.labs.userAgent.util.getNativeUserAgentString_();
|
||||
|
||||
|
||||
/**
|
||||
* Applications may override browser detection on the built in
|
||||
* navigator.userAgent object by setting this string. Set to null to use the
|
||||
* browser object instead.
|
||||
* @param {?string=} opt_userAgent The User-Agent override.
|
||||
*/
|
||||
goog.labs.userAgent.util.setUserAgent = function(opt_userAgent) {
|
||||
goog.labs.userAgent.util.userAgent_ =
|
||||
opt_userAgent || goog.labs.userAgent.util.getNativeUserAgentString_();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {string} The user agent string.
|
||||
*/
|
||||
goog.labs.userAgent.util.getUserAgent = function() {
|
||||
return goog.labs.userAgent.util.userAgent_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string} str
|
||||
* @return {boolean} Whether the user agent contains the given string.
|
||||
*/
|
||||
goog.labs.userAgent.util.matchUserAgent = function(str) {
|
||||
var userAgent = goog.labs.userAgent.util.getUserAgent();
|
||||
return goog.string.contains(userAgent, str);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {string} str
|
||||
* @return {boolean} Whether the user agent contains the given string, ignoring
|
||||
* case.
|
||||
*/
|
||||
goog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) {
|
||||
var userAgent = goog.labs.userAgent.util.getUserAgent();
|
||||
return goog.string.caseInsensitiveContains(userAgent, str);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Parses the user agent into tuples for each section.
|
||||
* @param {string} userAgent
|
||||
* @return {!Array<!Array<string>>} Tuples of key, version, and the contents
|
||||
* of the parenthetical.
|
||||
*/
|
||||
goog.labs.userAgent.util.extractVersionTuples = function(userAgent) {
|
||||
// Matches each section of a user agent string.
|
||||
// Example UA:
|
||||
// Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)
|
||||
// AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405
|
||||
// This has three version tuples: Mozilla, AppleWebKit, and Mobile.
|
||||
|
||||
var versionRegExp = new RegExp(
|
||||
// Key. Note that a key may have a space.
|
||||
// (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')
|
||||
'(\\w[\\w ]+)' +
|
||||
|
||||
'/' + // slash
|
||||
'([^\\s]+)' + // version (i.e. '5.0b')
|
||||
'\\s*' + // whitespace
|
||||
'(?:\\((.*?)\\))?', // parenthetical info. parentheses not matched.
|
||||
'g');
|
||||
|
||||
var data = [];
|
||||
var match;
|
||||
|
||||
// Iterate and collect the version tuples. Each iteration will be the
|
||||
// next regex match.
|
||||
while (match = versionRegExp.exec(userAgent)) {
|
||||
data.push([
|
||||
match[1], // key
|
||||
match[2], // value
|
||||
// || undefined as this is not undefined in IE7 and IE8
|
||||
match[3] || undefined // info
|
||||
]);
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
@@ -0,0 +1,808 @@
|
||||
// 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 an Integer class for representing (potentially)
|
||||
* infinite length two's-complement integer values.
|
||||
*
|
||||
* For the specific case of 64-bit integers, use goog.math.Long, which is more
|
||||
* efficient.
|
||||
*
|
||||
*/
|
||||
|
||||
goog.provide('goog.math.Integer');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a two's-complement integer an array containing bits of the
|
||||
* integer in 32-bit (signed) pieces, given in little-endian order (i.e.,
|
||||
* lowest-order bits in the first piece), and the sign of -1 or 0.
|
||||
*
|
||||
* See the from* functions below for other convenient ways of constructing
|
||||
* Integers.
|
||||
*
|
||||
* The internal representation of an integer is an array of 32-bit signed
|
||||
* pieces, along with a sign (0 or -1) that indicates the contents of all the
|
||||
* other 32-bit pieces out to infinity. We use 32-bit pieces because these are
|
||||
* the size of integers on which Javascript performs bit-operations. For
|
||||
* operations like addition and multiplication, we split each number into 16-bit
|
||||
* pieces, which can easily be multiplied within Javascript's floating-point
|
||||
* representation without overflow or change in sign.
|
||||
*
|
||||
* @struct
|
||||
* @constructor
|
||||
* @param {Array<number>} bits Array containing the bits of the number.
|
||||
* @param {number} sign The sign of the number: -1 for negative and 0 positive.
|
||||
* @final
|
||||
*/
|
||||
goog.math.Integer = function(bits, sign) {
|
||||
/**
|
||||
* @type {!Array<number>}
|
||||
* @private
|
||||
*/
|
||||
this.bits_ = [];
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
this.sign_ = sign;
|
||||
|
||||
// Copy the 32-bit signed integer values passed in. We prune out those at the
|
||||
// top that equal the sign since they are redundant.
|
||||
var top = true;
|
||||
for (var i = bits.length - 1; i >= 0; i--) {
|
||||
var val = bits[i] | 0;
|
||||
if (!top || val != sign) {
|
||||
this.bits_[i] = val;
|
||||
top = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
|
||||
/**
|
||||
* A cache of the Integer representations of small integer values.
|
||||
* @type {!Object}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Integer.IntCache_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an Integer representing the given (32-bit) integer value.
|
||||
* @param {number} value A 32-bit integer value.
|
||||
* @return {!goog.math.Integer} The corresponding Integer value.
|
||||
*/
|
||||
goog.math.Integer.fromInt = function(value) {
|
||||
if (-128 <= value && value < 128) {
|
||||
var cachedObj = goog.math.Integer.IntCache_[value];
|
||||
if (cachedObj) {
|
||||
return cachedObj;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new goog.math.Integer([value | 0], value < 0 ? -1 : 0);
|
||||
if (-128 <= value && value < 128) {
|
||||
goog.math.Integer.IntCache_[value] = obj;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an Integer representing the given value, provided that it is a finite
|
||||
* number. Otherwise, zero is returned.
|
||||
* @param {number} value The value in question.
|
||||
* @return {!goog.math.Integer} The corresponding Integer value.
|
||||
*/
|
||||
goog.math.Integer.fromNumber = function(value) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return goog.math.Integer.ZERO;
|
||||
} else if (value < 0) {
|
||||
return goog.math.Integer.fromNumber(-value).negate();
|
||||
} else {
|
||||
var bits = [];
|
||||
var pow = 1;
|
||||
for (var i = 0; value >= pow; i++) {
|
||||
bits[i] = (value / pow) | 0;
|
||||
pow *= goog.math.Integer.TWO_PWR_32_DBL_;
|
||||
}
|
||||
return new goog.math.Integer(bits, 0);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a Integer representing the value that comes by concatenating the
|
||||
* given entries, each is assumed to be 32 signed bits, given in little-endian
|
||||
* order (lowest order bits in the lowest index), and sign-extending the highest
|
||||
* order 32-bit value.
|
||||
* @param {Array<number>} bits The bits of the number, in 32-bit signed pieces,
|
||||
* in little-endian order.
|
||||
* @return {!goog.math.Integer} The corresponding Integer value.
|
||||
*/
|
||||
goog.math.Integer.fromBits = function(bits) {
|
||||
var high = bits[bits.length - 1];
|
||||
return new goog.math.Integer(bits, high & (1 << 31) ? -1 : 0);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an Integer representation of the given string, written using the
|
||||
* given radix.
|
||||
* @param {string} str The textual representation of the Integer.
|
||||
* @param {number=} opt_radix The radix in which the text is written.
|
||||
* @return {!goog.math.Integer} The corresponding Integer value.
|
||||
*/
|
||||
goog.math.Integer.fromString = function(str, opt_radix) {
|
||||
if (str.length == 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) == '-') {
|
||||
return goog.math.Integer.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character');
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = goog.math.Integer.ZERO;
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = goog.math.Integer.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(goog.math.Integer.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(goog.math.Integer.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A number used repeatedly in calculations. This must appear before the first
|
||||
* call to the from* functions below.
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16);
|
||||
|
||||
|
||||
/** @type {!goog.math.Integer} */
|
||||
goog.math.Integer.ZERO = goog.math.Integer.fromInt(0);
|
||||
|
||||
|
||||
/** @type {!goog.math.Integer} */
|
||||
goog.math.Integer.ONE = goog.math.Integer.fromInt(1);
|
||||
|
||||
|
||||
/**
|
||||
* @type {!goog.math.Integer}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Integer.TWO_PWR_24_ = goog.math.Integer.fromInt(1 << 24);
|
||||
|
||||
|
||||
/**
|
||||
* Returns the value, assuming it is a 32-bit integer.
|
||||
* @return {number} The corresponding int value.
|
||||
*/
|
||||
goog.math.Integer.prototype.toInt = function() {
|
||||
return this.bits_.length > 0 ? this.bits_[0] : this.sign_;
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The closest floating-point representation to this value. */
|
||||
goog.math.Integer.prototype.toNumber = function() {
|
||||
if (this.isNegative()) {
|
||||
return -this.negate().toNumber();
|
||||
} else {
|
||||
var val = 0;
|
||||
var pow = 1;
|
||||
for (var i = 0; i < this.bits_.length; i++) {
|
||||
val += this.getBitsUnsigned(i) * pow;
|
||||
pow *= goog.math.Integer.TWO_PWR_32_DBL_;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {number=} opt_radix The radix in which the text should be written.
|
||||
* @return {string} The textual representation of this value.
|
||||
* @override
|
||||
*/
|
||||
goog.math.Integer.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
} else if (this.isNegative()) {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = goog.math.Integer.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
var rem = this;
|
||||
var result = '';
|
||||
while (true) {
|
||||
var remDiv = rem.divide(radixToPower);
|
||||
// The right shifting fixes negative values in the case when
|
||||
// intval >= 2^31; for more details see
|
||||
// https://github.com/google/closure-library/pull/498
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the index-th 32-bit (signed) piece of the Integer according to
|
||||
* little-endian order (i.e., index 0 contains the smallest bits).
|
||||
* @param {number} index The index in question.
|
||||
* @return {number} The requested 32-bits as a signed number.
|
||||
*/
|
||||
goog.math.Integer.prototype.getBits = function(index) {
|
||||
if (index < 0) {
|
||||
return 0; // Allowing this simplifies bit shifting operations below...
|
||||
} else if (index < this.bits_.length) {
|
||||
return this.bits_[index];
|
||||
} else {
|
||||
return this.sign_;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the index-th 32-bit piece as an unsigned number.
|
||||
* @param {number} index The index in question.
|
||||
* @return {number} The requested 32-bits as an unsigned number.
|
||||
*/
|
||||
goog.math.Integer.prototype.getBitsUnsigned = function(index) {
|
||||
var val = this.getBits(index);
|
||||
return val >= 0 ? val : goog.math.Integer.TWO_PWR_32_DBL_ + val;
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The sign bit of this number, -1 or 0. */
|
||||
goog.math.Integer.prototype.getSign = function() {
|
||||
return this.sign_;
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is zero. */
|
||||
goog.math.Integer.prototype.isZero = function() {
|
||||
if (this.sign_ != 0) {
|
||||
return false;
|
||||
}
|
||||
for (var i = 0; i < this.bits_.length; i++) {
|
||||
if (this.bits_[i] != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is negative. */
|
||||
goog.math.Integer.prototype.isNegative = function() {
|
||||
return this.sign_ == -1;
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is odd. */
|
||||
goog.math.Integer.prototype.isOdd = function() {
|
||||
return (this.bits_.length == 0) && (this.sign_ == -1) ||
|
||||
(this.bits_.length > 0) && ((this.bits_[0] & 1) != 0);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer equals the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.equals = function(other) {
|
||||
if (this.sign_ != other.sign_) {
|
||||
return false;
|
||||
}
|
||||
var len = Math.max(this.bits_.length, other.bits_.length);
|
||||
for (var i = 0; i < len; i++) {
|
||||
if (this.getBits(i) != other.getBits(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer does not equal the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.notEquals = function(other) {
|
||||
return !this.equals(other);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer is greater than the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer is greater than or equal to the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer is less than the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {boolean} Whether this Integer is less than or equal to the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Compares this Integer with the given one.
|
||||
* @param {goog.math.Integer} other Integer to compare against.
|
||||
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
|
||||
* if the given one is greater.
|
||||
*/
|
||||
goog.math.Integer.prototype.compare = function(other) {
|
||||
var diff = this.subtract(other);
|
||||
if (diff.isNegative()) {
|
||||
return -1;
|
||||
} else if (diff.isZero()) {
|
||||
return 0;
|
||||
} else {
|
||||
return +1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an integer with only the first numBits bits of this value, sign
|
||||
* extended from the final bit.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Integer} The shorted integer value.
|
||||
*/
|
||||
goog.math.Integer.prototype.shorten = function(numBits) {
|
||||
var arr_index = (numBits - 1) >> 5;
|
||||
var bit_index = (numBits - 1) % 32;
|
||||
var bits = [];
|
||||
for (var i = 0; i < arr_index; i++) {
|
||||
bits[i] = this.getBits(i);
|
||||
}
|
||||
var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1;
|
||||
var val = this.getBits(arr_index) & sigBits;
|
||||
if (val & (1 << bit_index)) {
|
||||
val |= 0xFFFFFFFF - sigBits;
|
||||
bits[arr_index] = val;
|
||||
return new goog.math.Integer(bits, -1);
|
||||
} else {
|
||||
bits[arr_index] = val;
|
||||
return new goog.math.Integer(bits, 0);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** @return {!goog.math.Integer} The negation of this value. */
|
||||
goog.math.Integer.prototype.negate = function() {
|
||||
return this.not().add(goog.math.Integer.ONE);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Integer.
|
||||
* @param {goog.math.Integer} other The Integer to add to this.
|
||||
* @return {!goog.math.Integer} The Integer result.
|
||||
*/
|
||||
goog.math.Integer.prototype.add = function(other) {
|
||||
var len = Math.max(this.bits_.length, other.bits_.length);
|
||||
var arr = [];
|
||||
var carry = 0;
|
||||
|
||||
for (var i = 0; i <= len; i++) {
|
||||
var a1 = this.getBits(i) >>> 16;
|
||||
var a0 = this.getBits(i) & 0xFFFF;
|
||||
|
||||
var b1 = other.getBits(i) >>> 16;
|
||||
var b0 = other.getBits(i) & 0xFFFF;
|
||||
|
||||
var c0 = carry + a0 + b0;
|
||||
var c1 = (c0 >>> 16) + a1 + b1;
|
||||
carry = c1 >>> 16;
|
||||
c0 &= 0xFFFF;
|
||||
c1 &= 0xFFFF;
|
||||
arr[i] = (c1 << 16) | c0;
|
||||
}
|
||||
return goog.math.Integer.fromBits(arr);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Integer.
|
||||
* @param {goog.math.Integer} other The Integer to subtract from this.
|
||||
* @return {!goog.math.Integer} The Integer result.
|
||||
*/
|
||||
goog.math.Integer.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given Integer.
|
||||
* @param {goog.math.Integer} other The Integer to multiply against this.
|
||||
* @return {!goog.math.Integer} The product of this and the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return goog.math.Integer.ZERO;
|
||||
} else if (other.isZero()) {
|
||||
return goog.math.Integer.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate().multiply(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both numbers are small, use float multiplication
|
||||
if (this.lessThan(goog.math.Integer.TWO_PWR_24_) &&
|
||||
other.lessThan(goog.math.Integer.TWO_PWR_24_)) {
|
||||
return goog.math.Integer.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Fill in an array of 16-bit products.
|
||||
var len = this.bits_.length + other.bits_.length;
|
||||
var arr = [];
|
||||
for (var i = 0; i < 2 * len; i++) {
|
||||
arr[i] = 0;
|
||||
}
|
||||
for (var i = 0; i < this.bits_.length; i++) {
|
||||
for (var j = 0; j < other.bits_.length; j++) {
|
||||
var a1 = this.getBits(i) >>> 16;
|
||||
var a0 = this.getBits(i) & 0xFFFF;
|
||||
|
||||
var b1 = other.getBits(j) >>> 16;
|
||||
var b0 = other.getBits(j) & 0xFFFF;
|
||||
|
||||
arr[2 * i + 2 * j] += a0 * b0;
|
||||
goog.math.Integer.carry16_(arr, 2 * i + 2 * j);
|
||||
arr[2 * i + 2 * j + 1] += a1 * b0;
|
||||
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);
|
||||
arr[2 * i + 2 * j + 1] += a0 * b1;
|
||||
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 1);
|
||||
arr[2 * i + 2 * j + 2] += a1 * b1;
|
||||
goog.math.Integer.carry16_(arr, 2 * i + 2 * j + 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Combine the 16-bit values into 32-bit values.
|
||||
for (var i = 0; i < len; i++) {
|
||||
arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i];
|
||||
}
|
||||
for (var i = len; i < 2 * len; i++) {
|
||||
arr[i] = 0;
|
||||
}
|
||||
return new goog.math.Integer(arr, 0);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Carries any overflow from the given index into later entries.
|
||||
* @param {Array<number>} bits Array of 16-bit values in little-endian order.
|
||||
* @param {number} index The index in question.
|
||||
* @private
|
||||
*/
|
||||
goog.math.Integer.carry16_ = function(bits, index) {
|
||||
while ((bits[index] & 0xFFFF) != bits[index]) {
|
||||
bits[index + 1] += bits[index] >>> 16;
|
||||
bits[index] &= 0xFFFF;
|
||||
index++;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns "this" Integer divided by the given one. Both "this" and the given
|
||||
* Integer MUST be positive.
|
||||
*
|
||||
* This method is only needed for very large numbers (>10^308),
|
||||
* for which the original division algorithm gets into an infinite
|
||||
* loop (see https://github.com/google/closure-library/issues/500).
|
||||
*
|
||||
* The algorithm has some possible performance enhancements (or
|
||||
* could be rewritten entirely), it's just an initial solution for
|
||||
* the issue linked above.
|
||||
*
|
||||
* @param {!goog.math.Integer} other The Integer to divide "this" by.
|
||||
* @return {!goog.math.Integer} "this" value divided by the given one.
|
||||
* @private
|
||||
*/
|
||||
goog.math.Integer.prototype.slowDivide_ = function(other) {
|
||||
if (this.isNegative() || other.isNegative()) {
|
||||
throw Error('slowDivide_ only works with positive integers.');
|
||||
}
|
||||
|
||||
var twoPower = goog.math.Integer.ONE;
|
||||
var multiple = other;
|
||||
|
||||
// First we have to figure out what the highest bit of the result
|
||||
// is, so we increase "twoPower" and "multiple" until "multiple"
|
||||
// exceeds "this".
|
||||
while (multiple.lessThanOrEqual(this)) {
|
||||
twoPower = twoPower.shiftLeft(1);
|
||||
multiple = multiple.shiftLeft(1);
|
||||
}
|
||||
|
||||
// Rewind by one power of two, giving us the highest bit of the
|
||||
// result.
|
||||
var res = twoPower.shiftRight(1);
|
||||
var total = multiple.shiftRight(1);
|
||||
|
||||
// Now we starting decreasing "multiple" and "twoPower" to find the
|
||||
// rest of the bits of the result.
|
||||
var total2;
|
||||
multiple = multiple.shiftRight(2);
|
||||
twoPower = twoPower.shiftRight(2);
|
||||
while (!multiple.isZero()) {
|
||||
// whenever we can add "multiple" to the total and not exceed
|
||||
// "this", that means we've found a 1 bit. Else we've found a 0
|
||||
// and don't need to add to the result.
|
||||
total2 = total.add(multiple);
|
||||
if (total2.lessThanOrEqual(this)) {
|
||||
res = res.add(twoPower);
|
||||
total = total2;
|
||||
}
|
||||
multiple = multiple.shiftRight(1);
|
||||
twoPower = twoPower.shiftRight(1);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Integer divided by the given one.
|
||||
* @param {!goog.math.Integer} other The Integer to divide this by.
|
||||
* @return {!goog.math.Integer} This value divided by the given one.
|
||||
*/
|
||||
goog.math.Integer.prototype.divide = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return goog.math.Integer.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().divide(other.negate());
|
||||
} else {
|
||||
return this.negate().divide(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.divide(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Have to degrade to slowDivide for Very Large Numbers, because
|
||||
// they're out of range for the floating-point approximation
|
||||
// technique used below.
|
||||
if (this.bits_.length > 30) {
|
||||
return this.slowDivide_(other);
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = goog.math.Integer.ZERO;
|
||||
var rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = goog.math.Integer.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = goog.math.Integer.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = goog.math.Integer.ONE;
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Integer modulo the given one.
|
||||
* @param {!goog.math.Integer} other The Integer by which to mod.
|
||||
* @return {!goog.math.Integer} This value modulo the given one.
|
||||
*/
|
||||
goog.math.Integer.prototype.modulo = function(other) {
|
||||
return this.subtract(this.divide(other).multiply(other));
|
||||
};
|
||||
|
||||
|
||||
/** @return {!goog.math.Integer} The bitwise-NOT of this value. */
|
||||
goog.math.Integer.prototype.not = function() {
|
||||
var len = this.bits_.length;
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
arr[i] = ~this.bits_[i];
|
||||
}
|
||||
return new goog.math.Integer(arr, ~this.sign_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Integer and the given one.
|
||||
* @param {goog.math.Integer} other The Integer to AND with this.
|
||||
* @return {!goog.math.Integer} The bitwise-AND of this and the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.and = function(other) {
|
||||
var len = Math.max(this.bits_.length, other.bits_.length);
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
arr[i] = this.getBits(i) & other.getBits(i);
|
||||
}
|
||||
return new goog.math.Integer(arr, this.sign_ & other.sign_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Integer and the given one.
|
||||
* @param {goog.math.Integer} other The Integer to OR with this.
|
||||
* @return {!goog.math.Integer} The bitwise-OR of this and the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.or = function(other) {
|
||||
var len = Math.max(this.bits_.length, other.bits_.length);
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
arr[i] = this.getBits(i) | other.getBits(i);
|
||||
}
|
||||
return new goog.math.Integer(arr, this.sign_ | other.sign_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Integer and the given one.
|
||||
* @param {goog.math.Integer} other The Integer to XOR with this.
|
||||
* @return {!goog.math.Integer} The bitwise-XOR of this and the other.
|
||||
*/
|
||||
goog.math.Integer.prototype.xor = function(other) {
|
||||
var len = Math.max(this.bits_.length, other.bits_.length);
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
arr[i] = this.getBits(i) ^ other.getBits(i);
|
||||
}
|
||||
return new goog.math.Integer(arr, this.sign_ ^ other.sign_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this value with bits shifted to the left by the given amount.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Integer} This shifted to the left by the given amount.
|
||||
*/
|
||||
goog.math.Integer.prototype.shiftLeft = function(numBits) {
|
||||
var arr_delta = numBits >> 5;
|
||||
var bit_delta = numBits % 32;
|
||||
var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0);
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
if (bit_delta > 0) {
|
||||
arr[i] = (this.getBits(i - arr_delta) << bit_delta) |
|
||||
(this.getBits(i - arr_delta - 1) >>> (32 - bit_delta));
|
||||
} else {
|
||||
arr[i] = this.getBits(i - arr_delta);
|
||||
}
|
||||
}
|
||||
return new goog.math.Integer(arr, this.sign_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this value with bits shifted to the right by the given amount.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Integer} This shifted to the right by the given amount.
|
||||
*/
|
||||
goog.math.Integer.prototype.shiftRight = function(numBits) {
|
||||
var arr_delta = numBits >> 5;
|
||||
var bit_delta = numBits % 32;
|
||||
var len = this.bits_.length - arr_delta;
|
||||
var arr = [];
|
||||
for (var i = 0; i < len; i++) {
|
||||
if (bit_delta > 0) {
|
||||
arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) |
|
||||
(this.getBits(i + arr_delta + 1) << (32 - bit_delta));
|
||||
} else {
|
||||
arr[i] = this.getBits(i + arr_delta);
|
||||
}
|
||||
}
|
||||
return new goog.math.Integer(arr, this.sign_);
|
||||
};
|
||||
@@ -0,0 +1,965 @@
|
||||
// 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 a Long class for representing a 64-bit two's-complement
|
||||
* integer value, which faithfully simulates the behavior of a Java "long". This
|
||||
* implementation is derived from LongLib in GWT.
|
||||
*
|
||||
*/
|
||||
|
||||
goog.provide('goog.math.Long');
|
||||
|
||||
goog.require('goog.asserts');
|
||||
goog.require('goog.reflect');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
|
||||
* values as *signed* integers. See the from* functions below for more
|
||||
* convenient ways of constructing Longs.
|
||||
*
|
||||
* The internal representation of a long is the two given signed, 32-bit values.
|
||||
* We use 32-bit pieces because these are the size of integers on which
|
||||
* Javascript performs bit-operations. For operations like addition and
|
||||
* multiplication, we split each number into 16-bit pieces, which can easily be
|
||||
* multiplied within Javascript's floating-point representation without overflow
|
||||
* or change in sign.
|
||||
*
|
||||
* In the algorithms below, we frequently reduce the negative case to the
|
||||
* positive case by negating the input(s) and then post-processing the result.
|
||||
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
||||
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
||||
* a positive number, it overflows back into a negative). Not handling this
|
||||
* case would often result in infinite recursion.
|
||||
*
|
||||
* @param {number} low The low (signed) 32 bits of the long.
|
||||
* @param {number} high The high (signed) 32 bits of the long.
|
||||
* @struct
|
||||
* @constructor
|
||||
* @final
|
||||
*/
|
||||
goog.math.Long = function(low, high) {
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
this.high_ = high | 0; // force into 32 signed bits.
|
||||
};
|
||||
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
|
||||
/**
|
||||
* A cache of the Long representations of small integer values.
|
||||
* @type {!Object<number, !goog.math.Long>}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.IntCache_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* A cache of the Long representations of common values.
|
||||
* @type {!Object<goog.math.Long.ValueCacheId_, !goog.math.Long>}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.valueCache_ = {};
|
||||
|
||||
/**
|
||||
* Returns a cached long number representing the given (32-bit) integer value.
|
||||
* @param {number} value The 32-bit integer in question.
|
||||
* @return {!goog.math.Long} The corresponding Long value.
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.getCachedIntValue_ = function(value) {
|
||||
return goog.reflect.cache(goog.math.Long.IntCache_, value, function(val) {
|
||||
return new goog.math.Long(val, val < 0 ? -1 : 0);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* The array of maximum values of a Long in string representation for a given
|
||||
* radix between 2 and 36, inclusive.
|
||||
* @private @const {!Array<string>}
|
||||
*/
|
||||
goog.math.Long.MAX_VALUE_FOR_RADIX_ = [
|
||||
'', '', // unused
|
||||
'111111111111111111111111111111111111111111111111111111111111111',
|
||||
// base 2
|
||||
'2021110011022210012102010021220101220221', // base 3
|
||||
'13333333333333333333333333333333', // base 4
|
||||
'1104332401304422434310311212', // base 5
|
||||
'1540241003031030222122211', // base 6
|
||||
'22341010611245052052300', // base 7
|
||||
'777777777777777777777', // base 8
|
||||
'67404283172107811827', // base 9
|
||||
'9223372036854775807', // base 10
|
||||
'1728002635214590697', // base 11
|
||||
'41a792678515120367', // base 12
|
||||
'10b269549075433c37', // base 13
|
||||
'4340724c6c71dc7a7', // base 14
|
||||
'160e2ad3246366807', // base 15
|
||||
'7fffffffffffffff', // base 16
|
||||
'33d3d8307b214008', // base 17
|
||||
'16agh595df825fa7', // base 18
|
||||
'ba643dci0ffeehh', // base 19
|
||||
'5cbfjia3fh26ja7', // base 20
|
||||
'2heiciiie82dh97', // base 21
|
||||
'1adaibb21dckfa7', // base 22
|
||||
'i6k448cf4192c2', // base 23
|
||||
'acd772jnc9l0l7', // base 24
|
||||
'64ie1focnn5g77', // base 25
|
||||
'3igoecjbmca687', // base 26
|
||||
'27c48l5b37oaop', // base 27
|
||||
'1bk39f3ah3dmq7', // base 28
|
||||
'q1se8f0m04isb', // base 29
|
||||
'hajppbc1fc207', // base 30
|
||||
'bm03i95hia437', // base 31
|
||||
'7vvvvvvvvvvvv', // base 32
|
||||
'5hg4ck9jd4u37', // base 33
|
||||
'3tdtk1v8j6tpp', // base 34
|
||||
'2pijmikexrxp7', // base 35
|
||||
'1y2p0ij32e8e7' // base 36
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* The array of minimum values of a Long in string representation for a given
|
||||
* radix between 2 and 36, inclusive.
|
||||
* @private @const {!Array<string>}
|
||||
*/
|
||||
goog.math.Long.MIN_VALUE_FOR_RADIX_ = [
|
||||
'', '', // unused
|
||||
'-1000000000000000000000000000000000000000000000000000000000000000',
|
||||
// base 2
|
||||
'-2021110011022210012102010021220101220222', // base 3
|
||||
'-20000000000000000000000000000000', // base 4
|
||||
'-1104332401304422434310311213', // base 5
|
||||
'-1540241003031030222122212', // base 6
|
||||
'-22341010611245052052301', // base 7
|
||||
'-1000000000000000000000', // base 8
|
||||
'-67404283172107811828', // base 9
|
||||
'-9223372036854775808', // base 10
|
||||
'-1728002635214590698', // base 11
|
||||
'-41a792678515120368', // base 12
|
||||
'-10b269549075433c38', // base 13
|
||||
'-4340724c6c71dc7a8', // base 14
|
||||
'-160e2ad3246366808', // base 15
|
||||
'-8000000000000000', // base 16
|
||||
'-33d3d8307b214009', // base 17
|
||||
'-16agh595df825fa8', // base 18
|
||||
'-ba643dci0ffeehi', // base 19
|
||||
'-5cbfjia3fh26ja8', // base 20
|
||||
'-2heiciiie82dh98', // base 21
|
||||
'-1adaibb21dckfa8', // base 22
|
||||
'-i6k448cf4192c3', // base 23
|
||||
'-acd772jnc9l0l8', // base 24
|
||||
'-64ie1focnn5g78', // base 25
|
||||
'-3igoecjbmca688', // base 26
|
||||
'-27c48l5b37oaoq', // base 27
|
||||
'-1bk39f3ah3dmq8', // base 28
|
||||
'-q1se8f0m04isc', // base 29
|
||||
'-hajppbc1fc208', // base 30
|
||||
'-bm03i95hia438', // base 31
|
||||
'-8000000000000', // base 32
|
||||
'-5hg4ck9jd4u38', // base 33
|
||||
'-3tdtk1v8j6tpq', // base 34
|
||||
'-2pijmikexrxp8', // base 35
|
||||
'-1y2p0ij32e8e8' // base 36
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given (32-bit) integer value.
|
||||
* @param {number} value The 32-bit integer in question.
|
||||
* @return {!goog.math.Long} The corresponding Long value.
|
||||
*/
|
||||
goog.math.Long.fromInt = function(value) {
|
||||
var intValue = value | 0;
|
||||
goog.asserts.assert(value === intValue, 'value should be a 32-bit integer');
|
||||
|
||||
if (-128 <= intValue && intValue < 128) {
|
||||
return goog.math.Long.getCachedIntValue_(intValue);
|
||||
} else {
|
||||
return new goog.math.Long(intValue, intValue < 0 ? -1 : 0);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given value.
|
||||
* NaN will be returned as zero. Infinity is converted to max value and
|
||||
* -Infinity to min value.
|
||||
* @param {number} value The number in question.
|
||||
* @return {!goog.math.Long} The corresponding Long value.
|
||||
*/
|
||||
goog.math.Long.fromNumber = function(value) {
|
||||
if (isNaN(value)) {
|
||||
return goog.math.Long.getZero();
|
||||
} else if (value <= -goog.math.Long.TWO_PWR_63_DBL_) {
|
||||
return goog.math.Long.getMinValue();
|
||||
} else if (value + 1 >= goog.math.Long.TWO_PWR_63_DBL_) {
|
||||
return goog.math.Long.getMaxValue();
|
||||
} else if (value < 0) {
|
||||
return goog.math.Long.fromNumber(-value).negate();
|
||||
} else {
|
||||
return new goog.math.Long(
|
||||
(value % goog.math.Long.TWO_PWR_32_DBL_) | 0,
|
||||
(value / goog.math.Long.TWO_PWR_32_DBL_) | 0);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a Long representing the 64-bit integer that comes by concatenating
|
||||
* the given high and low bits. Each is assumed to use 32 bits.
|
||||
* @param {number} lowBits The low 32-bits.
|
||||
* @param {number} highBits The high 32-bits.
|
||||
* @return {!goog.math.Long} The corresponding Long value.
|
||||
*/
|
||||
goog.math.Long.fromBits = function(lowBits, highBits) {
|
||||
return new goog.math.Long(lowBits, highBits);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a Long representation of the given string, written using the given
|
||||
* radix.
|
||||
* @param {string} str The textual representation of the Long.
|
||||
* @param {number=} opt_radix The radix in which the text is written.
|
||||
* @return {!goog.math.Long} The corresponding Long value.
|
||||
*/
|
||||
goog.math.Long.fromString = function(str, opt_radix) {
|
||||
if (str.length == 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) == '-') {
|
||||
return goog.math.Long.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character: ' + str);
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = goog.math.Long.getZero();
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = goog.math.Long.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(goog.math.Long.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(goog.math.Long.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the boolean value of whether the input string is within a Long's
|
||||
* range. Assumes an input string containing only numeric characters with an
|
||||
* optional preceding '-'.
|
||||
* @param {string} str The textual representation of the Long.
|
||||
* @param {number=} opt_radix The radix in which the text is written.
|
||||
* @return {boolean} Whether the string is within the range of a Long.
|
||||
*/
|
||||
goog.math.Long.isStringInRange = function(str, opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
var extremeValue = (str.charAt(0) == '-') ?
|
||||
goog.math.Long.MIN_VALUE_FOR_RADIX_[radix] :
|
||||
goog.math.Long.MAX_VALUE_FOR_RADIX_[radix];
|
||||
|
||||
if (str.length < extremeValue.length) {
|
||||
return true;
|
||||
} else if (str.length == extremeValue.length && str <= extremeValue) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// NOTE: the compiler should inline these constant values below and then remove
|
||||
// these variables, so there should be no runtime penalty for these.
|
||||
|
||||
|
||||
/**
|
||||
* Number used repeated below in calculations. This must appear before the
|
||||
* first call to any from* function below.
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.TWO_PWR_16_DBL_ = 1 << 16;
|
||||
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.TWO_PWR_32_DBL_ =
|
||||
goog.math.Long.TWO_PWR_16_DBL_ * goog.math.Long.TWO_PWR_16_DBL_;
|
||||
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.TWO_PWR_64_DBL_ =
|
||||
goog.math.Long.TWO_PWR_32_DBL_ * goog.math.Long.TWO_PWR_32_DBL_;
|
||||
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.TWO_PWR_63_DBL_ = goog.math.Long.TWO_PWR_64_DBL_ / 2;
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getZero = function() {
|
||||
return goog.math.Long.getCachedIntValue_(0);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getOne = function() {
|
||||
return goog.math.Long.getCachedIntValue_(1);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getNegOne = function() {
|
||||
return goog.math.Long.getCachedIntValue_(-1);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getMaxValue = function() {
|
||||
return goog.reflect.cache(
|
||||
goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.MAX_VALUE,
|
||||
function() {
|
||||
return goog.math.Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getMinValue = function() {
|
||||
return goog.reflect.cache(
|
||||
goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.MIN_VALUE,
|
||||
function() { return goog.math.Long.fromBits(0, 0x80000000 | 0); });
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!goog.math.Long}
|
||||
* @public
|
||||
*/
|
||||
goog.math.Long.getTwoPwr24 = function() {
|
||||
return goog.reflect.cache(
|
||||
goog.math.Long.valueCache_, goog.math.Long.ValueCacheId_.TWO_PWR_24,
|
||||
function() { return goog.math.Long.fromInt(1 << 24); });
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The value, assuming it is a 32-bit integer. */
|
||||
goog.math.Long.prototype.toInt = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The closest floating-point representation to this value. */
|
||||
goog.math.Long.prototype.toNumber = function() {
|
||||
return this.high_ * goog.math.Long.TWO_PWR_32_DBL_ +
|
||||
this.getLowBitsUnsigned();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {number=} opt_radix The radix in which the text should be written.
|
||||
* @return {string} The textual representation of this value.
|
||||
* @override
|
||||
*/
|
||||
goog.math.Long.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(goog.math.Long.getMinValue())) {
|
||||
// We need to change the Long value before it can be negated, so we remove
|
||||
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
var radixLong = goog.math.Long.fromNumber(radix);
|
||||
var div = this.div(radixLong);
|
||||
var rem = div.multiply(radixLong).subtract(this);
|
||||
return div.toString(radix) + rem.toInt().toString(radix);
|
||||
} else {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = goog.math.Long.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
var rem = this;
|
||||
var result = '';
|
||||
while (true) {
|
||||
var remDiv = rem.div(radixToPower);
|
||||
// The right shifting fixes negative values in the case when
|
||||
// intval >= 2^31; for more details see
|
||||
// https://github.com/google/closure-library/pull/498
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0;
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The high 32-bits as a signed value. */
|
||||
goog.math.Long.prototype.getHighBits = function() {
|
||||
return this.high_;
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The low 32-bits as a signed value. */
|
||||
goog.math.Long.prototype.getLowBits = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
|
||||
/** @return {number} The low 32-bits as an unsigned value. */
|
||||
goog.math.Long.prototype.getLowBitsUnsigned = function() {
|
||||
return (this.low_ >= 0) ? this.low_ :
|
||||
goog.math.Long.TWO_PWR_32_DBL_ + this.low_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number} Returns the number of bits needed to represent the absolute
|
||||
* value of this Long.
|
||||
*/
|
||||
goog.math.Long.prototype.getNumBitsAbs = function() {
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(goog.math.Long.getMinValue())) {
|
||||
return 64;
|
||||
} else {
|
||||
return this.negate().getNumBitsAbs();
|
||||
}
|
||||
} else {
|
||||
var val = this.high_ != 0 ? this.high_ : this.low_;
|
||||
for (var bit = 31; bit > 0; bit--) {
|
||||
if ((val & (1 << bit)) != 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this.high_ != 0 ? bit + 33 : bit + 1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is zero. */
|
||||
goog.math.Long.prototype.isZero = function() {
|
||||
return this.high_ == 0 && this.low_ == 0;
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is negative. */
|
||||
goog.math.Long.prototype.isNegative = function() {
|
||||
return this.high_ < 0;
|
||||
};
|
||||
|
||||
|
||||
/** @return {boolean} Whether this value is odd. */
|
||||
goog.math.Long.prototype.isOdd = function() {
|
||||
return (this.low_ & 1) == 1;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long equals the other.
|
||||
*/
|
||||
goog.math.Long.prototype.equals = function(other) {
|
||||
return (this.high_ == other.high_) && (this.low_ == other.low_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long does not equal the other.
|
||||
*/
|
||||
goog.math.Long.prototype.notEquals = function(other) {
|
||||
return (this.high_ != other.high_) || (this.low_ != other.low_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long is less than the other.
|
||||
*/
|
||||
goog.math.Long.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long is less than or equal to the other.
|
||||
*/
|
||||
goog.math.Long.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long is greater than the other.
|
||||
*/
|
||||
goog.math.Long.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {boolean} Whether this Long is greater than or equal to the other.
|
||||
*/
|
||||
goog.math.Long.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Compares this Long with the given one.
|
||||
* @param {goog.math.Long} other Long to compare against.
|
||||
* @return {number} 0 if they are the same, 1 if the this is greater, and -1
|
||||
* if the given one is greater.
|
||||
*/
|
||||
goog.math.Long.prototype.compare = function(other) {
|
||||
if (this.equals(other)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var thisNeg = this.isNegative();
|
||||
var otherNeg = other.isNegative();
|
||||
if (thisNeg && !otherNeg) {
|
||||
return -1;
|
||||
}
|
||||
if (!thisNeg && otherNeg) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// at this point, the signs are the same, so subtraction will not overflow
|
||||
if (this.subtract(other).isNegative()) {
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** @return {!goog.math.Long} The negation of this value. */
|
||||
goog.math.Long.prototype.negate = function() {
|
||||
if (this.equals(goog.math.Long.getMinValue())) {
|
||||
return goog.math.Long.getMinValue();
|
||||
} else {
|
||||
return this.not().add(goog.math.Long.getOne());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Long.
|
||||
* @param {goog.math.Long} other Long to add to this one.
|
||||
* @return {!goog.math.Long} The sum of this and the given Long.
|
||||
*/
|
||||
goog.math.Long.prototype.add = function(other) {
|
||||
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 + b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 + b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 + b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 + b48;
|
||||
c48 &= 0xFFFF;
|
||||
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Long.
|
||||
* @param {goog.math.Long} other Long to subtract from this.
|
||||
* @return {!goog.math.Long} The difference of this and the given Long.
|
||||
*/
|
||||
goog.math.Long.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given long.
|
||||
* @param {goog.math.Long} other Long to multiply with this.
|
||||
* @return {!goog.math.Long} The product of this and the other.
|
||||
*/
|
||||
goog.math.Long.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return goog.math.Long.getZero();
|
||||
} else if (other.isZero()) {
|
||||
return goog.math.Long.getZero();
|
||||
}
|
||||
|
||||
if (this.equals(goog.math.Long.getMinValue())) {
|
||||
return other.isOdd() ? goog.math.Long.getMinValue() :
|
||||
goog.math.Long.getZero();
|
||||
} else if (other.equals(goog.math.Long.getMinValue())) {
|
||||
return this.isOdd() ? goog.math.Long.getMinValue() :
|
||||
goog.math.Long.getZero();
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate().multiply(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both longs are small, use float multiplication
|
||||
if (this.lessThan(goog.math.Long.getTwoPwr24()) &&
|
||||
other.lessThan(goog.math.Long.getTwoPwr24())) {
|
||||
return goog.math.Long.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
// We can skip products that would overflow.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 * b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 * b00;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c16 += a00 * b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 * b00;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a16 * b16;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a00 * b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
||||
c48 &= 0xFFFF;
|
||||
return goog.math.Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Long divided by the given one.
|
||||
* @param {goog.math.Long} other Long by which to divide.
|
||||
* @return {!goog.math.Long} This Long divided by the given one.
|
||||
*/
|
||||
goog.math.Long.prototype.div = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return goog.math.Long.getZero();
|
||||
}
|
||||
|
||||
if (this.equals(goog.math.Long.getMinValue())) {
|
||||
if (other.equals(goog.math.Long.getOne()) ||
|
||||
other.equals(goog.math.Long.getNegOne())) {
|
||||
return goog.math.Long.getMinValue(); // recall -MIN_VALUE == MIN_VALUE
|
||||
} else if (other.equals(goog.math.Long.getMinValue())) {
|
||||
return goog.math.Long.getOne();
|
||||
} else {
|
||||
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
var halfThis = this.shiftRight(1);
|
||||
var approx = halfThis.div(other).shiftLeft(1);
|
||||
if (approx.equals(goog.math.Long.getZero())) {
|
||||
return other.isNegative() ? goog.math.Long.getOne() :
|
||||
goog.math.Long.getNegOne();
|
||||
} else {
|
||||
var rem = this.subtract(other.multiply(approx));
|
||||
var result = approx.add(rem.div(other));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (other.equals(goog.math.Long.getMinValue())) {
|
||||
return goog.math.Long.getZero();
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().div(other.negate());
|
||||
} else {
|
||||
return this.negate().div(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.div(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = goog.math.Long.getZero();
|
||||
var rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = goog.math.Long.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = goog.math.Long.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = goog.math.Long.getOne();
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Long modulo the given one.
|
||||
* @param {goog.math.Long} other Long by which to mod.
|
||||
* @return {!goog.math.Long} This Long modulo the given one.
|
||||
*/
|
||||
goog.math.Long.prototype.modulo = function(other) {
|
||||
return this.subtract(this.div(other).multiply(other));
|
||||
};
|
||||
|
||||
|
||||
/** @return {!goog.math.Long} The bitwise-NOT of this value. */
|
||||
goog.math.Long.prototype.not = function() {
|
||||
return goog.math.Long.fromBits(~this.low_, ~this.high_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Long and the given one.
|
||||
* @param {goog.math.Long} other The Long with which to AND.
|
||||
* @return {!goog.math.Long} The bitwise-AND of this and the other.
|
||||
*/
|
||||
goog.math.Long.prototype.and = function(other) {
|
||||
return goog.math.Long.fromBits(
|
||||
this.low_ & other.low_, this.high_ & other.high_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Long and the given one.
|
||||
* @param {goog.math.Long} other The Long with which to OR.
|
||||
* @return {!goog.math.Long} The bitwise-OR of this and the other.
|
||||
*/
|
||||
goog.math.Long.prototype.or = function(other) {
|
||||
return goog.math.Long.fromBits(
|
||||
this.low_ | other.low_, this.high_ | other.high_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Long and the given one.
|
||||
* @param {goog.math.Long} other The Long with which to XOR.
|
||||
* @return {!goog.math.Long} The bitwise-XOR of this and the other.
|
||||
*/
|
||||
goog.math.Long.prototype.xor = function(other) {
|
||||
return goog.math.Long.fromBits(
|
||||
this.low_ ^ other.low_, this.high_ ^ other.high_);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the left by the given amount.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Long} This shifted to the left by the given amount.
|
||||
*/
|
||||
goog.math.Long.prototype.shiftLeft = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var low = this.low_;
|
||||
if (numBits < 32) {
|
||||
var high = this.high_;
|
||||
return goog.math.Long.fromBits(
|
||||
low << numBits, (high << numBits) | (low >>> (32 - numBits)));
|
||||
} else {
|
||||
return goog.math.Long.fromBits(0, low << (numBits - 32));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount.
|
||||
* The new leading bits match the current sign bit.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Long} This shifted to the right by the given amount.
|
||||
*/
|
||||
goog.math.Long.prototype.shiftRight = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return goog.math.Long.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)), high >> numBits);
|
||||
} else {
|
||||
return goog.math.Long.fromBits(
|
||||
high >> (numBits - 32), high >= 0 ? 0 : -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount, with
|
||||
* zeros placed into the new leading bits.
|
||||
* @param {number} numBits The number of bits by which to shift.
|
||||
* @return {!goog.math.Long} This shifted to the right by the given amount, with
|
||||
* zeros placed into the new leading bits.
|
||||
*/
|
||||
goog.math.Long.prototype.shiftRightUnsigned = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return goog.math.Long.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)), high >>> numBits);
|
||||
} else if (numBits == 32) {
|
||||
return goog.math.Long.fromBits(high, 0);
|
||||
} else {
|
||||
return goog.math.Long.fromBits(high >>> (numBits - 32), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @enum {number} Ids of commonly requested Long instances.
|
||||
* @private
|
||||
*/
|
||||
goog.math.Long.ValueCacheId_ = {
|
||||
MAX_VALUE: 1,
|
||||
MIN_VALUE: 2,
|
||||
TWO_PWR_24: 6
|
||||
};
|
||||
@@ -0,0 +1,448 @@
|
||||
// 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 Additional mathematical functions.
|
||||
*/
|
||||
|
||||
goog.provide('goog.math');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.asserts');
|
||||
|
||||
|
||||
/**
|
||||
* Returns a random integer greater than or equal to 0 and less than {@code a}.
|
||||
* @param {number} a The upper bound for the random integer (exclusive).
|
||||
* @return {number} A random integer N such that 0 <= N < a.
|
||||
*/
|
||||
goog.math.randomInt = function(a) {
|
||||
return Math.floor(Math.random() * a);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a random number greater than or equal to {@code a} and less than
|
||||
* {@code b}.
|
||||
* @param {number} a The lower bound for the random number (inclusive).
|
||||
* @param {number} b The upper bound for the random number (exclusive).
|
||||
* @return {number} A random number N such that a <= N < b.
|
||||
*/
|
||||
goog.math.uniformRandom = function(a, b) {
|
||||
return a + Math.random() * (b - a);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Takes a number and clamps it to within the provided bounds.
|
||||
* @param {number} value The input number.
|
||||
* @param {number} min The minimum value to return.
|
||||
* @param {number} max The maximum value to return.
|
||||
* @return {number} The input number if it is within bounds, or the nearest
|
||||
* number within the bounds.
|
||||
*/
|
||||
goog.math.clamp = function(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The % operator in JavaScript returns the remainder of a / b, but differs from
|
||||
* some other languages in that the result will have the same sign as the
|
||||
* dividend. For example, -1 % 8 == -1, whereas in some other languages
|
||||
* (such as Python) the result would be 7. This function emulates the more
|
||||
* correct modulo behavior, which is useful for certain applications such as
|
||||
* calculating an offset index in a circular list.
|
||||
*
|
||||
* @param {number} a The dividend.
|
||||
* @param {number} b The divisor.
|
||||
* @return {number} a % b where the result is between 0 and b (either 0 <= x < b
|
||||
* or b < x <= 0, depending on the sign of b).
|
||||
*/
|
||||
goog.math.modulo = function(a, b) {
|
||||
var r = a % b;
|
||||
// If r and b differ in sign, add b to wrap the result to the correct sign.
|
||||
return (r * b < 0) ? r + b : r;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Performs linear interpolation between values a and b. Returns the value
|
||||
* between a and b proportional to x (when x is between 0 and 1. When x is
|
||||
* outside this range, the return value is a linear extrapolation).
|
||||
* @param {number} a A number.
|
||||
* @param {number} b A number.
|
||||
* @param {number} x The proportion between a and b.
|
||||
* @return {number} The interpolated value between a and b.
|
||||
*/
|
||||
goog.math.lerp = function(a, b, x) {
|
||||
return a + x * (b - a);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Tests whether the two values are equal to each other, within a certain
|
||||
* tolerance to adjust for floating point errors.
|
||||
* @param {number} a A number.
|
||||
* @param {number} b A number.
|
||||
* @param {number=} opt_tolerance Optional tolerance range. Defaults
|
||||
* to 0.000001. If specified, should be greater than 0.
|
||||
* @return {boolean} Whether {@code a} and {@code b} are nearly equal.
|
||||
*/
|
||||
goog.math.nearlyEquals = function(a, b, opt_tolerance) {
|
||||
return Math.abs(a - b) <= (opt_tolerance || 0.000001);
|
||||
};
|
||||
|
||||
|
||||
// TODO(user): Rename to normalizeAngle, retaining old name as deprecated
|
||||
// alias.
|
||||
/**
|
||||
* Normalizes an angle to be in range [0-360). Angles outside this range will
|
||||
* be normalized to be the equivalent angle with that range.
|
||||
* @param {number} angle Angle in degrees.
|
||||
* @return {number} Standardized angle.
|
||||
*/
|
||||
goog.math.standardAngle = function(angle) {
|
||||
return goog.math.modulo(angle, 360);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Normalizes an angle to be in range [0-2*PI). Angles outside this range will
|
||||
* be normalized to be the equivalent angle with that range.
|
||||
* @param {number} angle Angle in radians.
|
||||
* @return {number} Standardized angle.
|
||||
*/
|
||||
goog.math.standardAngleInRadians = function(angle) {
|
||||
return goog.math.modulo(angle, 2 * Math.PI);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Converts degrees to radians.
|
||||
* @param {number} angleDegrees Angle in degrees.
|
||||
* @return {number} Angle in radians.
|
||||
*/
|
||||
goog.math.toRadians = function(angleDegrees) {
|
||||
return angleDegrees * Math.PI / 180;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Converts radians to degrees.
|
||||
* @param {number} angleRadians Angle in radians.
|
||||
* @return {number} Angle in degrees.
|
||||
*/
|
||||
goog.math.toDegrees = function(angleRadians) {
|
||||
return angleRadians * 180 / Math.PI;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* For a given angle and radius, finds the X portion of the offset.
|
||||
* @param {number} degrees Angle in degrees (zero points in +X direction).
|
||||
* @param {number} radius Radius.
|
||||
* @return {number} The x-distance for the angle and radius.
|
||||
*/
|
||||
goog.math.angleDx = function(degrees, radius) {
|
||||
return radius * Math.cos(goog.math.toRadians(degrees));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* For a given angle and radius, finds the Y portion of the offset.
|
||||
* @param {number} degrees Angle in degrees (zero points in +X direction).
|
||||
* @param {number} radius Radius.
|
||||
* @return {number} The y-distance for the angle and radius.
|
||||
*/
|
||||
goog.math.angleDy = function(degrees, radius) {
|
||||
return radius * Math.sin(goog.math.toRadians(degrees));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Computes the angle between two points (x1,y1) and (x2,y2).
|
||||
* Angle zero points in the +X direction, 90 degrees points in the +Y
|
||||
* direction (down) and from there we grow clockwise towards 360 degrees.
|
||||
* @param {number} x1 x of first point.
|
||||
* @param {number} y1 y of first point.
|
||||
* @param {number} x2 x of second point.
|
||||
* @param {number} y2 y of second point.
|
||||
* @return {number} Standardized angle in degrees of the vector from
|
||||
* x1,y1 to x2,y2.
|
||||
*/
|
||||
goog.math.angle = function(x1, y1, x2, y2) {
|
||||
return goog.math.standardAngle(
|
||||
goog.math.toDegrees(Math.atan2(y2 - y1, x2 - x1)));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Computes the difference between startAngle and endAngle (angles in degrees).
|
||||
* @param {number} startAngle Start angle in degrees.
|
||||
* @param {number} endAngle End angle in degrees.
|
||||
* @return {number} The number of degrees that when added to
|
||||
* startAngle will result in endAngle. Positive numbers mean that the
|
||||
* direction is clockwise. Negative numbers indicate a counter-clockwise
|
||||
* direction.
|
||||
* The shortest route (clockwise vs counter-clockwise) between the angles
|
||||
* is used.
|
||||
* When the difference is 180 degrees, the function returns 180 (not -180)
|
||||
* angleDifference(30, 40) is 10, and angleDifference(40, 30) is -10.
|
||||
* angleDifference(350, 10) is 20, and angleDifference(10, 350) is -20.
|
||||
*/
|
||||
goog.math.angleDifference = function(startAngle, endAngle) {
|
||||
var d =
|
||||
goog.math.standardAngle(endAngle) - goog.math.standardAngle(startAngle);
|
||||
if (d > 180) {
|
||||
d = d - 360;
|
||||
} else if (d <= -180) {
|
||||
d = 360 + d;
|
||||
}
|
||||
return d;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the sign of a number as per the "sign" or "signum" function.
|
||||
* @param {number} x The number to take the sign of.
|
||||
* @return {number} -1 when negative, 1 when positive, 0 when 0. Preserves
|
||||
* signed zeros and NaN.
|
||||
*/
|
||||
goog.math.sign = function(x) {
|
||||
if (x > 0) {
|
||||
return 1;
|
||||
}
|
||||
if (x < 0) {
|
||||
return -1;
|
||||
}
|
||||
return x; // Preserves signed zeros and NaN.
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* JavaScript implementation of Longest Common Subsequence problem.
|
||||
* http://en.wikipedia.org/wiki/Longest_common_subsequence
|
||||
*
|
||||
* Returns the longest possible array that is subarray of both of given arrays.
|
||||
*
|
||||
* @param {IArrayLike<S>} array1 First array of objects.
|
||||
* @param {IArrayLike<T>} array2 Second array of objects.
|
||||
* @param {Function=} opt_compareFn Function that acts as a custom comparator
|
||||
* for the array ojects. Function should return true if objects are equal,
|
||||
* otherwise false.
|
||||
* @param {Function=} opt_collectorFn Function used to decide what to return
|
||||
* as a result subsequence. It accepts 2 arguments: index of common element
|
||||
* in the first array and index in the second. The default function returns
|
||||
* element from the first array.
|
||||
* @return {!Array<S|T>} A list of objects that are common to both arrays
|
||||
* such that there is no common subsequence with size greater than the
|
||||
* length of the list.
|
||||
* @template S,T
|
||||
*/
|
||||
goog.math.longestCommonSubsequence = function(
|
||||
array1, array2, opt_compareFn, opt_collectorFn) {
|
||||
|
||||
var compare = opt_compareFn || function(a, b) { return a == b; };
|
||||
|
||||
var collect = opt_collectorFn || function(i1, i2) { return array1[i1]; };
|
||||
|
||||
var length1 = array1.length;
|
||||
var length2 = array2.length;
|
||||
|
||||
var arr = [];
|
||||
for (var i = 0; i < length1 + 1; i++) {
|
||||
arr[i] = [];
|
||||
arr[i][0] = 0;
|
||||
}
|
||||
|
||||
for (var j = 0; j < length2 + 1; j++) {
|
||||
arr[0][j] = 0;
|
||||
}
|
||||
|
||||
for (i = 1; i <= length1; i++) {
|
||||
for (j = 1; j <= length2; j++) {
|
||||
if (compare(array1[i - 1], array2[j - 1])) {
|
||||
arr[i][j] = arr[i - 1][j - 1] + 1;
|
||||
} else {
|
||||
arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Backtracking
|
||||
var result = [];
|
||||
var i = length1, j = length2;
|
||||
while (i > 0 && j > 0) {
|
||||
if (compare(array1[i - 1], array2[j - 1])) {
|
||||
result.unshift(collect(i - 1, j - 1));
|
||||
i--;
|
||||
j--;
|
||||
} else {
|
||||
if (arr[i - 1][j] > arr[i][j - 1]) {
|
||||
i--;
|
||||
} else {
|
||||
j--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the sum of the arguments.
|
||||
* @param {...number} var_args Numbers to add.
|
||||
* @return {number} The sum of the arguments (0 if no arguments were provided,
|
||||
* {@code NaN} if any of the arguments is not a valid number).
|
||||
*/
|
||||
goog.math.sum = function(var_args) {
|
||||
return /** @type {number} */ (
|
||||
goog.array.reduce(
|
||||
arguments, function(sum, value) { return sum + value; }, 0));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the arithmetic mean of the arguments.
|
||||
* @param {...number} var_args Numbers to average.
|
||||
* @return {number} The average of the arguments ({@code NaN} if no arguments
|
||||
* were provided or any of the arguments is not a valid number).
|
||||
*/
|
||||
goog.math.average = function(var_args) {
|
||||
return goog.math.sum.apply(null, arguments) / arguments.length;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the unbiased sample variance of the arguments. For a definition,
|
||||
* see e.g. http://en.wikipedia.org/wiki/Variance
|
||||
* @param {...number} var_args Number samples to analyze.
|
||||
* @return {number} The unbiased sample variance of the arguments (0 if fewer
|
||||
* than two samples were provided, or {@code NaN} if any of the samples is
|
||||
* not a valid number).
|
||||
*/
|
||||
goog.math.sampleVariance = function(var_args) {
|
||||
var sampleSize = arguments.length;
|
||||
if (sampleSize < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var mean = goog.math.average.apply(null, arguments);
|
||||
var variance =
|
||||
goog.math.sum.apply(null, goog.array.map(arguments, function(val) {
|
||||
return Math.pow(val - mean, 2);
|
||||
})) / (sampleSize - 1);
|
||||
|
||||
return variance;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the sample standard deviation of the arguments. For a definition of
|
||||
* sample standard deviation, see e.g.
|
||||
* http://en.wikipedia.org/wiki/Standard_deviation
|
||||
* @param {...number} var_args Number samples to analyze.
|
||||
* @return {number} The sample standard deviation of the arguments (0 if fewer
|
||||
* than two samples were provided, or {@code NaN} if any of the samples is
|
||||
* not a valid number).
|
||||
*/
|
||||
goog.math.standardDeviation = function(var_args) {
|
||||
return Math.sqrt(goog.math.sampleVariance.apply(null, arguments));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether the supplied number represents an integer, i.e. that is has
|
||||
* no fractional component. No range-checking is performed on the number.
|
||||
* @param {number} num The number to test.
|
||||
* @return {boolean} Whether {@code num} is an integer.
|
||||
*/
|
||||
goog.math.isInt = function(num) {
|
||||
return isFinite(num) && num % 1 == 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns whether the supplied number is finite and not NaN.
|
||||
* @param {number} num The number to test.
|
||||
* @return {boolean} Whether {@code num} is a finite number.
|
||||
* @deprecated Use {@link isFinite} instead.
|
||||
*/
|
||||
goog.math.isFiniteNumber = function(num) {
|
||||
return isFinite(num);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {number} num The number to test.
|
||||
* @return {boolean} Whether it is negative zero.
|
||||
*/
|
||||
goog.math.isNegativeZero = function(num) {
|
||||
return num == 0 && 1 / num < 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the precise value of floor(log10(num)).
|
||||
* Simpler implementations didn't work because of floating point rounding
|
||||
* errors. For example
|
||||
* <ul>
|
||||
* <li>Math.floor(Math.log(num) / Math.LN10) is off by one for num == 1e+3.
|
||||
* <li>Math.floor(Math.log(num) * Math.LOG10E) is off by one for num == 1e+15.
|
||||
* <li>Math.floor(Math.log10(num)) is off by one for num == 1e+15 - 1.
|
||||
* </ul>
|
||||
* @param {number} num A floating point number.
|
||||
* @return {number} Its logarithm to base 10 rounded down to the nearest
|
||||
* integer if num > 0. -Infinity if num == 0. NaN if num < 0.
|
||||
*/
|
||||
goog.math.log10Floor = function(num) {
|
||||
if (num > 0) {
|
||||
var x = Math.round(Math.log(num) * Math.LOG10E);
|
||||
return x - (parseFloat('1e' + x) > num ? 1 : 0);
|
||||
}
|
||||
return num == 0 ? -Infinity : NaN;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A tweaked variant of {@code Math.floor} which tolerates if the passed number
|
||||
* is infinitesimally smaller than the closest integer. It often happens with
|
||||
* the results of floating point calculations because of the finite precision
|
||||
* of the intermediate results. For example {@code Math.floor(Math.log(1000) /
|
||||
* Math.LN10) == 2}, not 3 as one would expect.
|
||||
* @param {number} num A number.
|
||||
* @param {number=} opt_epsilon An infinitesimally small positive number, the
|
||||
* rounding error to tolerate.
|
||||
* @return {number} The largest integer less than or equal to {@code num}.
|
||||
*/
|
||||
goog.math.safeFloor = function(num, opt_epsilon) {
|
||||
goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
|
||||
return Math.floor(num + (opt_epsilon || 2e-15));
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* A tweaked variant of {@code Math.ceil}. See {@code goog.math.safeFloor} for
|
||||
* details.
|
||||
* @param {number} num A number.
|
||||
* @param {number=} opt_epsilon An infinitesimally small positive number, the
|
||||
* rounding error to tolerate.
|
||||
* @return {number} The smallest integer greater than or equal to {@code num}.
|
||||
*/
|
||||
goog.math.safeCeil = function(num, opt_epsilon) {
|
||||
goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0);
|
||||
return Math.ceil(num - (opt_epsilon || 2e-15));
|
||||
};
|
||||
@@ -0,0 +1,751 @@
|
||||
// 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 objects/maps/hashes.
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
*/
|
||||
|
||||
goog.provide('goog.object');
|
||||
|
||||
|
||||
/**
|
||||
* Whether two values are not observably distinguishable. This
|
||||
* correctly detects that 0 is not the same as -0 and two NaNs are
|
||||
* practically equivalent.
|
||||
*
|
||||
* The implementation is as suggested by harmony:egal proposal.
|
||||
*
|
||||
* @param {*} v The first value to compare.
|
||||
* @param {*} v2 The second value to compare.
|
||||
* @return {boolean} Whether two values are not observably distinguishable.
|
||||
* @see http://wiki.ecmascript.org/doku.php?id=harmony:egal
|
||||
*/
|
||||
goog.object.is = function(v, v2) {
|
||||
if (v === v2) {
|
||||
// 0 === -0, but they are not identical.
|
||||
// We need the cast because the compiler requires that v2 is a
|
||||
// number (although 1/v2 works with non-number). We cast to ? to
|
||||
// stop the compiler from type-checking this statement.
|
||||
return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2);
|
||||
}
|
||||
|
||||
// NaN is non-reflexive: NaN !== NaN, although they are identical.
|
||||
return v !== v && v2 !== v2;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for each element in an object/map/hash.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object over which to iterate.
|
||||
* @param {function(this:T,V,?,Object<K,V>):?} f The function to call
|
||||
* for every element. This function takes 3 arguments (the value, the
|
||||
* key and the object) and the return value is ignored.
|
||||
* @param {T=} opt_obj This is used as the 'this' object within f.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.forEach = function(obj, f, opt_obj) {
|
||||
for (var key in obj) {
|
||||
f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for each element in an object/map/hash. If that call returns
|
||||
* true, adds the element to a new object.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object over which to iterate.
|
||||
* @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call
|
||||
* for every element. This
|
||||
* function takes 3 arguments (the value, the key and the object)
|
||||
* and should return a boolean. If the return value is true the
|
||||
* element is added to the result object. If it is false the
|
||||
* element is not included.
|
||||
* @param {T=} opt_obj This is used as the 'this' object within f.
|
||||
* @return {!Object<K,V>} a new object in which only elements that passed the
|
||||
* test are present.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.filter = function(obj, f, opt_obj) {
|
||||
var res = {};
|
||||
for (var key in obj) {
|
||||
if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
|
||||
res[key] = obj[key];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* For every element in an object/map/hash calls a function and inserts the
|
||||
* result into a new object.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object over which to iterate.
|
||||
* @param {function(this:T,V,?,Object<K,V>):R} f The function to call
|
||||
* for every element. This function
|
||||
* takes 3 arguments (the value, the key and the object)
|
||||
* and should return something. The result will be inserted
|
||||
* into a new object.
|
||||
* @param {T=} opt_obj This is used as the 'this' object within f.
|
||||
* @return {!Object<K,R>} a new object with the results from f.
|
||||
* @template T,K,V,R
|
||||
*/
|
||||
goog.object.map = function(obj, f, opt_obj) {
|
||||
var res = {};
|
||||
for (var key in obj) {
|
||||
res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for each element in an object/map/hash. If any
|
||||
* call returns true, returns true (without checking the rest). If
|
||||
* all calls return false, returns false.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to check.
|
||||
* @param {function(this:T,V,?,Object<K,V>):boolean} f The function to
|
||||
* call for every element. This function
|
||||
* takes 3 arguments (the value, the key and the object) and should
|
||||
* return a boolean.
|
||||
* @param {T=} opt_obj This is used as the 'this' object within f.
|
||||
* @return {boolean} true if any element passes the test.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.some = function(obj, f, opt_obj) {
|
||||
for (var key in obj) {
|
||||
if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for each element in an object/map/hash. If
|
||||
* all calls return true, returns true. If any call returns false, returns
|
||||
* false at this point and does not continue to check the remaining elements.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to check.
|
||||
* @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to
|
||||
* call for every element. This function
|
||||
* takes 3 arguments (the value, the key and the object) and should
|
||||
* return a boolean.
|
||||
* @param {T=} opt_obj This is used as the 'this' object within f.
|
||||
* @return {boolean} false if any element fails the test.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.every = function(obj, f, opt_obj) {
|
||||
for (var key in obj) {
|
||||
if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of key-value pairs in the object map.
|
||||
*
|
||||
* @param {Object} obj The object for which to get the number of key-value
|
||||
* pairs.
|
||||
* @return {number} The number of key-value pairs in the object map.
|
||||
*/
|
||||
goog.object.getCount = function(obj) {
|
||||
var rv = 0;
|
||||
for (var key in obj) {
|
||||
rv++;
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns one key from the object map, if any exists.
|
||||
* For map literals the returned key will be the first one in most of the
|
||||
* browsers (a know exception is Konqueror).
|
||||
*
|
||||
* @param {Object} obj The object to pick a key from.
|
||||
* @return {string|undefined} The key or undefined if the object is empty.
|
||||
*/
|
||||
goog.object.getAnyKey = function(obj) {
|
||||
for (var key in obj) {
|
||||
return key;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns one value from the object map, if any exists.
|
||||
* For map literals the returned value will be the first one in most of the
|
||||
* browsers (a know exception is Konqueror).
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to pick a value from.
|
||||
* @return {V|undefined} The value or undefined if the object is empty.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.getAnyValue = function(obj) {
|
||||
for (var key in obj) {
|
||||
return obj[key];
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the object/hash/map contains the given object as a value.
|
||||
* An alias for goog.object.containsValue(obj, val).
|
||||
*
|
||||
* @param {Object<K,V>} obj The object in which to look for val.
|
||||
* @param {V} val The object for which to check.
|
||||
* @return {boolean} true if val is present.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.contains = function(obj, val) {
|
||||
return goog.object.containsValue(obj, val);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the values of the object/map/hash.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object from which to get the values.
|
||||
* @return {!Array<V>} The values in the object/map/hash.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.getValues = function(obj) {
|
||||
var res = [];
|
||||
var i = 0;
|
||||
for (var key in obj) {
|
||||
res[i++] = obj[key];
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the keys of the object/map/hash.
|
||||
*
|
||||
* @param {Object} obj The object from which to get the keys.
|
||||
* @return {!Array<string>} Array of property keys.
|
||||
*/
|
||||
goog.object.getKeys = function(obj) {
|
||||
var res = [];
|
||||
var i = 0;
|
||||
for (var key in obj) {
|
||||
res[i++] = key;
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get a value from an object multiple levels deep. This is useful for
|
||||
* pulling values from deeply nested objects, such as JSON responses.
|
||||
* Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)
|
||||
*
|
||||
* @param {!Object} obj An object to get the value from. Can be array-like.
|
||||
* @param {...(string|number|!IArrayLike<number|string>)}
|
||||
* var_args A number of keys
|
||||
* (as strings, or numbers, for array-like objects). Can also be
|
||||
* specified as a single array of keys.
|
||||
* @return {*} The resulting value. If, at any point, the value for a key
|
||||
* is undefined, returns undefined.
|
||||
*/
|
||||
goog.object.getValueByKeys = function(obj, var_args) {
|
||||
var isArrayLike = goog.isArrayLike(var_args);
|
||||
var keys = isArrayLike ? var_args : arguments;
|
||||
|
||||
// Start with the 2nd parameter for the variable parameters syntax.
|
||||
for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {
|
||||
obj = obj[keys[i]];
|
||||
if (!goog.isDef(obj)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the object/map/hash contains the given key.
|
||||
*
|
||||
* @param {Object} obj The object in which to look for key.
|
||||
* @param {?} key The key for which to check.
|
||||
* @return {boolean} true If the map contains the key.
|
||||
*/
|
||||
goog.object.containsKey = function(obj, key) {
|
||||
return obj !== null && key in obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the object/map/hash contains the given value. This is O(n).
|
||||
*
|
||||
* @param {Object<K,V>} obj The object in which to look for val.
|
||||
* @param {V} val The value for which to check.
|
||||
* @return {boolean} true If the map contains the value.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.containsValue = function(obj, val) {
|
||||
for (var key in obj) {
|
||||
if (obj[key] == val) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Searches an object for an element that satisfies the given condition and
|
||||
* returns its key.
|
||||
* @param {Object<K,V>} obj The object to search in.
|
||||
* @param {function(this:T,V,string,Object<K,V>):boolean} f The
|
||||
* function to call for every element. Takes 3 arguments (the value,
|
||||
* the key and the object) and should return a boolean.
|
||||
* @param {T=} opt_this An optional "this" context for the function.
|
||||
* @return {string|undefined} The key of an element for which the function
|
||||
* returns true or undefined if no such element is found.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.findKey = function(obj, f, opt_this) {
|
||||
for (var key in obj) {
|
||||
if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Searches an object for an element that satisfies the given condition and
|
||||
* returns its value.
|
||||
* @param {Object<K,V>} obj The object to search in.
|
||||
* @param {function(this:T,V,string,Object<K,V>):boolean} f The function
|
||||
* to call for every element. Takes 3 arguments (the value, the key
|
||||
* and the object) and should return a boolean.
|
||||
* @param {T=} opt_this An optional "this" context for the function.
|
||||
* @return {V} The value of an element for which the function returns true or
|
||||
* undefined if no such element is found.
|
||||
* @template T,K,V
|
||||
*/
|
||||
goog.object.findValue = function(obj, f, opt_this) {
|
||||
var key = goog.object.findKey(obj, f, opt_this);
|
||||
return key && obj[key];
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the object/map/hash is empty.
|
||||
*
|
||||
* @param {Object} obj The object to test.
|
||||
* @return {boolean} true if obj is empty.
|
||||
*/
|
||||
goog.object.isEmpty = function(obj) {
|
||||
for (var key in obj) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes all key value pairs from the object/map/hash.
|
||||
*
|
||||
* @param {Object} obj The object to clear.
|
||||
*/
|
||||
goog.object.clear = function(obj) {
|
||||
for (var i in obj) {
|
||||
delete obj[i];
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes a key-value pair based on the key.
|
||||
*
|
||||
* @param {Object} obj The object from which to remove the key.
|
||||
* @param {?} key The key to remove.
|
||||
* @return {boolean} Whether an element was removed.
|
||||
*/
|
||||
goog.object.remove = function(obj, key) {
|
||||
var rv;
|
||||
if (rv = key in /** @type {!Object} */ (obj)) {
|
||||
delete obj[key];
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds a key-value pair to the object. Throws an exception if the key is
|
||||
* already in use. Use set if you want to change an existing pair.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to which to add the key-value pair.
|
||||
* @param {string} key The key to add.
|
||||
* @param {V} val The value to add.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.add = function(obj, key, val) {
|
||||
if (obj !== null && key in obj) {
|
||||
throw Error('The object already contains the key "' + key + '"');
|
||||
}
|
||||
goog.object.set(obj, key, val);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the value for the given key.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object from which to get the value.
|
||||
* @param {string} key The key for which to get the value.
|
||||
* @param {R=} opt_val The value to return if no item is found for the given
|
||||
* key (default is undefined).
|
||||
* @return {V|R|undefined} The value for the given key.
|
||||
* @template K,V,R
|
||||
*/
|
||||
goog.object.get = function(obj, key, opt_val) {
|
||||
if (obj !== null && key in obj) {
|
||||
return obj[key];
|
||||
}
|
||||
return opt_val;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds a key-value pair to the object/map/hash.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to which to add the key-value pair.
|
||||
* @param {string} key The key to add.
|
||||
* @param {V} value The value to add.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.set = function(obj, key, value) {
|
||||
obj[key] = value;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds a key-value pair to the object/map/hash if it doesn't exist yet.
|
||||
*
|
||||
* @param {Object<K,V>} obj The object to which to add the key-value pair.
|
||||
* @param {string} key The key to add.
|
||||
* @param {V} value The value to add if the key wasn't present.
|
||||
* @return {V} The value of the entry at the end of the function.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.setIfUndefined = function(obj, key, value) {
|
||||
return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets a key and value to an object if the key is not set. The value will be
|
||||
* the return value of the given function. If the key already exists, the
|
||||
* object will not be changed and the function will not be called (the function
|
||||
* will be lazily evaluated -- only called if necessary).
|
||||
*
|
||||
* This function is particularly useful for use with a map used a as a cache.
|
||||
*
|
||||
* @param {!Object<K,V>} obj The object to which to add the key-value pair.
|
||||
* @param {string} key The key to add.
|
||||
* @param {function():V} f The value to add if the key wasn't present.
|
||||
* @return {V} The value of the entry at the end of the function.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.setWithReturnValueIfNotSet = function(obj, key, f) {
|
||||
if (key in obj) {
|
||||
return obj[key];
|
||||
}
|
||||
|
||||
var val = f();
|
||||
obj[key] = val;
|
||||
return val;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Compares two objects for equality using === on the values.
|
||||
*
|
||||
* @param {!Object<K,V>} a
|
||||
* @param {!Object<K,V>} b
|
||||
* @return {boolean}
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.equals = function(a, b) {
|
||||
for (var k in a) {
|
||||
if (!(k in b) || a[k] !== b[k]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (var k in b) {
|
||||
if (!(k in a)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a shallow clone of the object.
|
||||
*
|
||||
* @param {Object<K,V>} obj Object to clone.
|
||||
* @return {!Object<K,V>} Clone of the input object.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.clone = function(obj) {
|
||||
// We cannot use the prototype trick because a lot of methods depend on where
|
||||
// the actual key is set.
|
||||
|
||||
var res = {};
|
||||
for (var key in obj) {
|
||||
res[key] = obj[key];
|
||||
}
|
||||
return res;
|
||||
// We could also use goog.mixin but I wanted this to be independent from that.
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Clones a value. The input may be an Object, Array, or basic type. Objects and
|
||||
* arrays will be cloned recursively.
|
||||
*
|
||||
* WARNINGS:
|
||||
* <code>goog.object.unsafeClone</code> does not detect reference loops. Objects
|
||||
* that refer to themselves will cause infinite recursion.
|
||||
*
|
||||
* <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and
|
||||
* copies UIDs created by <code>getUid</code> into cloned results.
|
||||
*
|
||||
* @param {T} obj The value to clone.
|
||||
* @return {T} A clone of the input value.
|
||||
* @template T
|
||||
*/
|
||||
goog.object.unsafeClone = function(obj) {
|
||||
var type = goog.typeOf(obj);
|
||||
if (type == 'object' || type == 'array') {
|
||||
if (goog.isFunction(obj.clone)) {
|
||||
return obj.clone();
|
||||
}
|
||||
var clone = type == 'array' ? [] : {};
|
||||
for (var key in obj) {
|
||||
clone[key] = goog.object.unsafeClone(obj[key]);
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
|
||||
return obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a new object in which all the keys and values are interchanged
|
||||
* (keys become values and values become keys). If multiple keys map to the
|
||||
* same value, the chosen transposed value is implementation-dependent.
|
||||
*
|
||||
* @param {Object} obj The object to transpose.
|
||||
* @return {!Object} The transposed object.
|
||||
*/
|
||||
goog.object.transpose = function(obj) {
|
||||
var transposed = {};
|
||||
for (var key in obj) {
|
||||
transposed[obj[key]] = key;
|
||||
}
|
||||
return transposed;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The names of the fields that are defined on Object.prototype.
|
||||
* @type {Array<string>}
|
||||
* @private
|
||||
*/
|
||||
goog.object.PROTOTYPE_FIELDS_ = [
|
||||
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
|
||||
'toLocaleString', 'toString', 'valueOf'
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Extends an object with another object.
|
||||
* This operates 'in-place'; it does not create a new Object.
|
||||
*
|
||||
* Example:
|
||||
* var o = {};
|
||||
* goog.object.extend(o, {a: 0, b: 1});
|
||||
* o; // {a: 0, b: 1}
|
||||
* goog.object.extend(o, {b: 2, c: 3});
|
||||
* o; // {a: 0, b: 2, c: 3}
|
||||
*
|
||||
* @param {Object} target The object to modify. Existing properties will be
|
||||
* overwritten if they are also present in one of the objects in
|
||||
* {@code var_args}.
|
||||
* @param {...Object} var_args The objects from which values will be copied.
|
||||
*/
|
||||
goog.object.extend = function(target, var_args) {
|
||||
var key, source;
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
source = arguments[i];
|
||||
for (key in source) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
|
||||
// For IE the for-in-loop does not contain any properties that are not
|
||||
// enumerable on the prototype object (for example isPrototypeOf from
|
||||
// Object.prototype) and it will also not include 'replace' on objects that
|
||||
// extend String and change 'replace' (not that it is common for anyone to
|
||||
// extend anything except Object).
|
||||
|
||||
for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {
|
||||
key = goog.object.PROTOTYPE_FIELDS_[j];
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new object built from the key-value pairs provided as arguments.
|
||||
* @param {...*} var_args If only one argument is provided and it is an array
|
||||
* then this is used as the arguments, otherwise even arguments are used as
|
||||
* the property names and odd arguments are used as the property values.
|
||||
* @return {!Object} The new object.
|
||||
* @throws {Error} If there are uneven number of arguments or there is only one
|
||||
* non array argument.
|
||||
*/
|
||||
goog.object.create = function(var_args) {
|
||||
var argLength = arguments.length;
|
||||
if (argLength == 1 && goog.isArray(arguments[0])) {
|
||||
return goog.object.create.apply(null, arguments[0]);
|
||||
}
|
||||
|
||||
if (argLength % 2) {
|
||||
throw Error('Uneven number of arguments');
|
||||
}
|
||||
|
||||
var rv = {};
|
||||
for (var i = 0; i < argLength; i += 2) {
|
||||
rv[arguments[i]] = arguments[i + 1];
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new object where the property names come from the arguments but
|
||||
* the value is always set to true
|
||||
* @param {...*} var_args If only one argument is provided and it is an array
|
||||
* then this is used as the arguments, otherwise the arguments are used
|
||||
* as the property names.
|
||||
* @return {!Object} The new object.
|
||||
*/
|
||||
goog.object.createSet = function(var_args) {
|
||||
var argLength = arguments.length;
|
||||
if (argLength == 1 && goog.isArray(arguments[0])) {
|
||||
return goog.object.createSet.apply(null, arguments[0]);
|
||||
}
|
||||
|
||||
var rv = {};
|
||||
for (var i = 0; i < argLength; i++) {
|
||||
rv[arguments[i]] = true;
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Creates an immutable view of the underlying object, if the browser
|
||||
* supports immutable objects.
|
||||
*
|
||||
* In default mode, writes to this view will fail silently. In strict mode,
|
||||
* they will throw an error.
|
||||
*
|
||||
* @param {!Object<K,V>} obj An object.
|
||||
* @return {!Object<K,V>} An immutable view of that object, or the
|
||||
* original object if this browser does not support immutables.
|
||||
* @template K,V
|
||||
*/
|
||||
goog.object.createImmutableView = function(obj) {
|
||||
var result = obj;
|
||||
if (Object.isFrozen && !Object.isFrozen(obj)) {
|
||||
result = Object.create(obj);
|
||||
Object.freeze(result);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @param {!Object} obj An object.
|
||||
* @return {boolean} Whether this is an immutable view of the object.
|
||||
*/
|
||||
goog.object.isImmutableView = function(obj) {
|
||||
return !!Object.isFrozen && Object.isFrozen(obj);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Get all properties names on a given Object regardless of enumerability.
|
||||
*
|
||||
* <p> If the browser does not support {@code Object.getOwnPropertyNames} nor
|
||||
* {@code Object.getPrototypeOf} then this is equivalent to using {@code
|
||||
* goog.object.getKeys}
|
||||
*
|
||||
* @param {?Object} obj The object to get the properties of.
|
||||
* @param {boolean=} opt_includeObjectPrototype Whether properties defined on
|
||||
* {@code Object.prototype} should be included in the result.
|
||||
* @param {boolean=} opt_includeFunctionPrototype Whether properties defined on
|
||||
* {@code Function.prototype} should be included in the result.
|
||||
* @return {!Array<string>}
|
||||
* @public
|
||||
*/
|
||||
goog.object.getAllPropertyNames = function(
|
||||
obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) {
|
||||
if (!obj) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Naively use a for..in loop to get the property names if the browser doesn't
|
||||
// support any other APIs for getting it.
|
||||
if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {
|
||||
return goog.object.getKeys(obj);
|
||||
}
|
||||
|
||||
var visitedSet = {};
|
||||
|
||||
// Traverse the prototype chain and add all properties to the visited set.
|
||||
var proto = obj;
|
||||
while (proto &&
|
||||
(proto !== Object.prototype || !!opt_includeObjectPrototype) &&
|
||||
(proto !== Function.prototype || !!opt_includeFunctionPrototype)) {
|
||||
var names = Object.getOwnPropertyNames(proto);
|
||||
for (var i = 0; i < names.length; i++) {
|
||||
visitedSet[names[i]] = true;
|
||||
}
|
||||
proto = Object.getPrototypeOf(proto);
|
||||
}
|
||||
|
||||
return goog.object.getKeys(visitedSet);
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
// 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 Useful compiler idioms.
|
||||
*
|
||||
* @author johnlenz@google.com (John Lenz)
|
||||
*/
|
||||
|
||||
goog.provide('goog.reflect');
|
||||
|
||||
|
||||
/**
|
||||
* Syntax for object literal casts.
|
||||
* @see http://go/jscompiler-renaming
|
||||
* @see https://goo.gl/CRs09P
|
||||
*
|
||||
* Use this if you have an object literal whose keys need to have the same names
|
||||
* as the properties of some class even after they are renamed by the compiler.
|
||||
*
|
||||
* @param {!Function} type Type to cast to.
|
||||
* @param {Object} object Object literal to cast.
|
||||
* @return {Object} The object literal.
|
||||
*/
|
||||
goog.reflect.object = function(type, object) {
|
||||
return object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Syntax for renaming property strings.
|
||||
* @see http://go/jscompiler-renaming
|
||||
* @see https://goo.gl/CRs09P
|
||||
*
|
||||
* Use this if you have an need to access a property as a string, but want
|
||||
* to also have the property renamed by the compiler. In contrast to
|
||||
* goog.reflect.object, this method takes an instance of an object.
|
||||
*
|
||||
* Properties must be simple names (not qualified names).
|
||||
*
|
||||
* @param {string} prop Name of the property
|
||||
* @param {!Object} object Instance of the object whose type will be used
|
||||
* for renaming
|
||||
* @return {string} The renamed property.
|
||||
*/
|
||||
goog.reflect.objectProperty = function(prop, object) {
|
||||
return prop;
|
||||
};
|
||||
|
||||
/**
|
||||
* To assert to the compiler that an operation is needed when it would
|
||||
* otherwise be stripped. For example:
|
||||
* <code>
|
||||
* // Force a layout
|
||||
* goog.reflect.sinkValue(dialog.offsetHeight);
|
||||
* </code>
|
||||
* @param {T} x
|
||||
* @return {T}
|
||||
* @template T
|
||||
*/
|
||||
goog.reflect.sinkValue = function(x) {
|
||||
goog.reflect.sinkValue[' '](x);
|
||||
return x;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The compiler should optimize this function away iff no one ever uses
|
||||
* goog.reflect.sinkValue.
|
||||
*/
|
||||
goog.reflect.sinkValue[' '] = goog.nullFunction;
|
||||
|
||||
|
||||
/**
|
||||
* Check if a property can be accessed without throwing an exception.
|
||||
* @param {Object} obj The owner of the property.
|
||||
* @param {string} prop The property name.
|
||||
* @return {boolean} Whether the property is accessible. Will also return true
|
||||
* if obj is null.
|
||||
*/
|
||||
goog.reflect.canAccessProperty = function(obj, prop) {
|
||||
|
||||
try {
|
||||
goog.reflect.sinkValue(obj[prop]);
|
||||
return true;
|
||||
} catch (e) {
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves a value from a cache given a key. The compiler provides special
|
||||
* consideration for this call such that it is generally considered side-effect
|
||||
* free. However, if the {@code opt_keyFn} or {@code valueFn} have side-effects
|
||||
* then the entire call is considered to have side-effects.
|
||||
*
|
||||
* Conventionally storing the value on the cache would be considered a
|
||||
* side-effect and preclude unused calls from being pruned, ie. even if
|
||||
* the value was never used, it would still always be stored in the cache.
|
||||
*
|
||||
* Providing a side-effect free {@code valueFn} and {@code opt_keyFn}
|
||||
* allows unused calls to {@code goog.reflect.cache} to be pruned.
|
||||
*
|
||||
* @param {!Object<K, V>} cacheObj The object that contains the cached values.
|
||||
* @param {?} key The key to lookup in the cache. If it is not string or number
|
||||
* then a {@code opt_keyFn} should be provided. The key is also used as the
|
||||
* parameter to the {@code valueFn}.
|
||||
* @param {function(?):V} valueFn The value provider to use to calculate the
|
||||
* value to store in the cache. This function should be side-effect free
|
||||
* to take advantage of the optimization.
|
||||
* @param {function(?):K=} opt_keyFn The key provider to determine the cache
|
||||
* map key. This should be used if the given key is not a string or number.
|
||||
* If not provided then the given key is used. This function should be
|
||||
* side-effect free to take advantage of the optimization.
|
||||
* @return {V} The cached or calculated value.
|
||||
* @template K
|
||||
* @template V
|
||||
*/
|
||||
goog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {
|
||||
var storedKey = opt_keyFn ? opt_keyFn(key) : key;
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {
|
||||
return cacheObj[storedKey];
|
||||
}
|
||||
|
||||
return (cacheObj[storedKey] = valueFn(key));
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,103 @@
|
||||
// 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 Utility for fast string concatenation.
|
||||
*/
|
||||
|
||||
goog.provide('goog.string.StringBuffer');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Utility class to facilitate string concatenation.
|
||||
*
|
||||
* @param {*=} opt_a1 Optional first initial item to append.
|
||||
* @param {...*} var_args Other initial items to
|
||||
* append, e.g., new goog.string.StringBuffer('foo', 'bar').
|
||||
* @constructor
|
||||
*/
|
||||
goog.string.StringBuffer = function(opt_a1, var_args) {
|
||||
if (opt_a1 != null) {
|
||||
this.append.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Internal buffer for the string to be concatenated.
|
||||
* @type {string}
|
||||
* @private
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.buffer_ = '';
|
||||
|
||||
|
||||
/**
|
||||
* Sets the contents of the string buffer object, replacing what's currently
|
||||
* there.
|
||||
*
|
||||
* @param {*} s String to set.
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.set = function(s) {
|
||||
this.buffer_ = '' + s;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Appends one or more items to the buffer.
|
||||
*
|
||||
* Calling this with null, undefined, or empty arguments is an error.
|
||||
*
|
||||
* @param {*} a1 Required first string.
|
||||
* @param {*=} opt_a2 Optional second string.
|
||||
* @param {...?} var_args Other items to append,
|
||||
* e.g., sb.append('foo', 'bar', 'baz').
|
||||
* @return {!goog.string.StringBuffer} This same StringBuffer object.
|
||||
* @suppress {duplicate}
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.append = function(a1, opt_a2, var_args) {
|
||||
// Use a1 directly to avoid arguments instantiation for single-arg case.
|
||||
this.buffer_ += String(a1);
|
||||
if (opt_a2 != null) { // second argument is undefined (null == undefined)
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
this.buffer_ += arguments[i];
|
||||
}
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Clears the internal buffer.
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.clear = function() {
|
||||
this.buffer_ = '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number} the length of the current contents of the buffer.
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.getLength = function() {
|
||||
return this.buffer_.length;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {string} The concatenated string.
|
||||
* @override
|
||||
*/
|
||||
goog.string.StringBuffer.prototype.toString = function() {
|
||||
return this.buffer_;
|
||||
};
|
||||
@@ -0,0 +1,458 @@
|
||||
// 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 Datastructure: Hash Map.
|
||||
*
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
*
|
||||
* This file contains an implementation of a Map structure. It implements a lot
|
||||
* of the methods used in goog.structs so those functions work on hashes. This
|
||||
* is best suited for complex key types. For simple keys such as numbers and
|
||||
* strings consider using the lighter-weight utilities in goog.object.
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.structs.Map');
|
||||
|
||||
goog.require('goog.iter.Iterator');
|
||||
goog.require('goog.iter.StopIteration');
|
||||
goog.require('goog.object');
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Class for Hash Map datastructure.
|
||||
* @param {*=} opt_map Map or Object to initialize the map with.
|
||||
* @param {...*} var_args If 2 or more arguments are present then they
|
||||
* will be used as key-value pairs.
|
||||
* @constructor
|
||||
* @template K, V
|
||||
* @deprecated This type is misleading: use ES6 Map instead.
|
||||
*/
|
||||
goog.structs.Map = function(opt_map, var_args) {
|
||||
|
||||
/**
|
||||
* Underlying JS object used to implement the map.
|
||||
* @private {!Object}
|
||||
*/
|
||||
this.map_ = {};
|
||||
|
||||
/**
|
||||
* An array of keys. This is necessary for two reasons:
|
||||
* 1. Iterating the keys using for (var key in this.map_) allocates an
|
||||
* object for every key in IE which is really bad for IE6 GC perf.
|
||||
* 2. Without a side data structure, we would need to escape all the keys
|
||||
* as that would be the only way we could tell during iteration if the
|
||||
* key was an internal key or a property of the object.
|
||||
*
|
||||
* This array can contain deleted keys so it's necessary to check the map
|
||||
* as well to see if the key is still in the map (this doesn't require a
|
||||
* memory allocation in IE).
|
||||
* @private {!Array<string>}
|
||||
*/
|
||||
this.keys_ = [];
|
||||
|
||||
/**
|
||||
* The number of key value pairs in the map.
|
||||
* @private {number}
|
||||
*/
|
||||
this.count_ = 0;
|
||||
|
||||
/**
|
||||
* Version used to detect changes while iterating.
|
||||
* @private {number}
|
||||
*/
|
||||
this.version_ = 0;
|
||||
|
||||
var argLength = arguments.length;
|
||||
|
||||
if (argLength > 1) {
|
||||
if (argLength % 2) {
|
||||
throw Error('Uneven number of arguments');
|
||||
}
|
||||
for (var i = 0; i < argLength; i += 2) {
|
||||
this.set(arguments[i], arguments[i + 1]);
|
||||
}
|
||||
} else if (opt_map) {
|
||||
this.addAll(/** @type {Object} */ (opt_map));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number} The number of key-value pairs in the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.getCount = function() {
|
||||
return this.count_;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the values of the map.
|
||||
* @return {!Array<V>} The values in the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.getValues = function() {
|
||||
this.cleanupKeysArray_();
|
||||
|
||||
var rv = [];
|
||||
for (var i = 0; i < this.keys_.length; i++) {
|
||||
var key = this.keys_[i];
|
||||
rv.push(this.map_[key]);
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the keys of the map.
|
||||
* @return {!Array<string>} Array of string values.
|
||||
*/
|
||||
goog.structs.Map.prototype.getKeys = function() {
|
||||
this.cleanupKeysArray_();
|
||||
return /** @type {!Array<string>} */ (this.keys_.concat());
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the map contains the given key.
|
||||
* @param {*} key The key to check for.
|
||||
* @return {boolean} Whether the map contains the key.
|
||||
*/
|
||||
goog.structs.Map.prototype.containsKey = function(key) {
|
||||
return goog.structs.Map.hasKey_(this.map_, key);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the map contains the given value. This is O(n).
|
||||
* @param {V} val The value to check for.
|
||||
* @return {boolean} Whether the map contains the value.
|
||||
*/
|
||||
goog.structs.Map.prototype.containsValue = function(val) {
|
||||
for (var i = 0; i < this.keys_.length; i++) {
|
||||
var key = this.keys_[i];
|
||||
if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether this map is equal to the argument map.
|
||||
* @param {goog.structs.Map} otherMap The map against which to test equality.
|
||||
* @param {function(V, V): boolean=} opt_equalityFn Optional equality function
|
||||
* to test equality of values. If not specified, this will test whether
|
||||
* the values contained in each map are identical objects.
|
||||
* @return {boolean} Whether the maps are equal.
|
||||
*/
|
||||
goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {
|
||||
if (this === otherMap) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.count_ != otherMap.getCount()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;
|
||||
|
||||
this.cleanupKeysArray_();
|
||||
for (var key, i = 0; key = this.keys_[i]; i++) {
|
||||
if (!equalityFn(this.get(key), otherMap.get(key))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Default equality test for values.
|
||||
* @param {*} a The first value.
|
||||
* @param {*} b The second value.
|
||||
* @return {boolean} Whether a and b reference the same object.
|
||||
*/
|
||||
goog.structs.Map.defaultEquals = function(a, b) {
|
||||
return a === b;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the map is empty.
|
||||
*/
|
||||
goog.structs.Map.prototype.isEmpty = function() {
|
||||
return this.count_ == 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes all key-value pairs from the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.clear = function() {
|
||||
this.map_ = {};
|
||||
this.keys_.length = 0;
|
||||
this.count_ = 0;
|
||||
this.version_ = 0;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes a key-value pair based on the key. This is O(logN) amortized due to
|
||||
* updating the keys array whenever the count becomes half the size of the keys
|
||||
* in the keys array.
|
||||
* @param {*} key The key to remove.
|
||||
* @return {boolean} Whether object was removed.
|
||||
*/
|
||||
goog.structs.Map.prototype.remove = function(key) {
|
||||
if (goog.structs.Map.hasKey_(this.map_, key)) {
|
||||
delete this.map_[key];
|
||||
this.count_--;
|
||||
this.version_++;
|
||||
|
||||
// clean up the keys array if the threshold is hit
|
||||
if (this.keys_.length > 2 * this.count_) {
|
||||
this.cleanupKeysArray_();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Cleans up the temp keys array by removing entries that are no longer in the
|
||||
* map.
|
||||
* @private
|
||||
*/
|
||||
goog.structs.Map.prototype.cleanupKeysArray_ = function() {
|
||||
if (this.count_ != this.keys_.length) {
|
||||
// First remove keys that are no longer in the map.
|
||||
var srcIndex = 0;
|
||||
var destIndex = 0;
|
||||
while (srcIndex < this.keys_.length) {
|
||||
var key = this.keys_[srcIndex];
|
||||
if (goog.structs.Map.hasKey_(this.map_, key)) {
|
||||
this.keys_[destIndex++] = key;
|
||||
}
|
||||
srcIndex++;
|
||||
}
|
||||
this.keys_.length = destIndex;
|
||||
}
|
||||
|
||||
if (this.count_ != this.keys_.length) {
|
||||
// If the count still isn't correct, that means we have duplicates. This can
|
||||
// happen when the same key is added and removed multiple times. Now we have
|
||||
// to allocate one extra Object to remove the duplicates. This could have
|
||||
// been done in the first pass, but in the common case, we can avoid
|
||||
// allocating an extra object by only doing this when necessary.
|
||||
var seen = {};
|
||||
var srcIndex = 0;
|
||||
var destIndex = 0;
|
||||
while (srcIndex < this.keys_.length) {
|
||||
var key = this.keys_[srcIndex];
|
||||
if (!(goog.structs.Map.hasKey_(seen, key))) {
|
||||
this.keys_[destIndex++] = key;
|
||||
seen[key] = 1;
|
||||
}
|
||||
srcIndex++;
|
||||
}
|
||||
this.keys_.length = destIndex;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the value for the given key. If the key is not found and the default
|
||||
* value is not given this will return {@code undefined}.
|
||||
* @param {*} key The key to get the value for.
|
||||
* @param {DEFAULT=} opt_val The value to return if no item is found for the
|
||||
* given key, defaults to undefined.
|
||||
* @return {V|DEFAULT} The value for the given key.
|
||||
* @template DEFAULT
|
||||
*/
|
||||
goog.structs.Map.prototype.get = function(key, opt_val) {
|
||||
if (goog.structs.Map.hasKey_(this.map_, key)) {
|
||||
return this.map_[key];
|
||||
}
|
||||
return opt_val;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds a key-value pair to the map.
|
||||
* @param {*} key The key.
|
||||
* @param {V} value The value to add.
|
||||
* @return {*} Some subclasses return a value.
|
||||
*/
|
||||
goog.structs.Map.prototype.set = function(key, value) {
|
||||
if (!(goog.structs.Map.hasKey_(this.map_, key))) {
|
||||
this.count_++;
|
||||
// TODO(johnlenz): This class lies, it claims to return an array of string
|
||||
// keys, but instead returns the original object used.
|
||||
this.keys_.push(/** @type {?} */ (key));
|
||||
// Only change the version if we add a new key.
|
||||
this.version_++;
|
||||
}
|
||||
this.map_[key] = value;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Adds multiple key-value pairs from another goog.structs.Map or Object.
|
||||
* @param {Object} map Object containing the data to add.
|
||||
*/
|
||||
goog.structs.Map.prototype.addAll = function(map) {
|
||||
var keys, values;
|
||||
if (map instanceof goog.structs.Map) {
|
||||
keys = map.getKeys();
|
||||
values = map.getValues();
|
||||
} else {
|
||||
keys = goog.object.getKeys(map);
|
||||
values = goog.object.getValues(map);
|
||||
}
|
||||
// we could use goog.array.forEach here but I don't want to introduce that
|
||||
// dependency just for this.
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
this.set(keys[i], values[i]);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls the given function on each entry in the map.
|
||||
* @param {function(this:T, V, K, goog.structs.Map<K,V>)} f
|
||||
* @param {T=} opt_obj The value of "this" inside f.
|
||||
* @template T
|
||||
*/
|
||||
goog.structs.Map.prototype.forEach = function(f, opt_obj) {
|
||||
var keys = this.getKeys();
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
var key = keys[i];
|
||||
var value = this.get(key);
|
||||
f.call(opt_obj, value, key, this);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Clones a map and returns a new map.
|
||||
* @return {!goog.structs.Map} A new map with the same key-value pairs.
|
||||
*/
|
||||
goog.structs.Map.prototype.clone = function() {
|
||||
return new goog.structs.Map(this);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns a new map in which all the keys and values are interchanged
|
||||
* (keys become values and values become keys). If multiple keys map to the
|
||||
* same value, the chosen transposed value is implementation-dependent.
|
||||
*
|
||||
* It acts very similarly to {goog.object.transpose(Object)}.
|
||||
*
|
||||
* @return {!goog.structs.Map} The transposed map.
|
||||
*/
|
||||
goog.structs.Map.prototype.transpose = function() {
|
||||
var transposed = new goog.structs.Map();
|
||||
for (var i = 0; i < this.keys_.length; i++) {
|
||||
var key = this.keys_[i];
|
||||
var value = this.map_[key];
|
||||
transposed.set(value, key);
|
||||
}
|
||||
|
||||
return transposed;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {!Object} Object representation of the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.toObject = function() {
|
||||
this.cleanupKeysArray_();
|
||||
var obj = {};
|
||||
for (var i = 0; i < this.keys_.length; i++) {
|
||||
var key = this.keys_[i];
|
||||
obj[key] = this.map_[key];
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an iterator that iterates over the keys in the map. Removal of keys
|
||||
* while iterating might have undesired side effects.
|
||||
* @return {!goog.iter.Iterator} An iterator over the keys in the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.getKeyIterator = function() {
|
||||
return this.__iterator__(true);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an iterator that iterates over the values in the map. Removal of
|
||||
* keys while iterating might have undesired side effects.
|
||||
* @return {!goog.iter.Iterator} An iterator over the values in the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.getValueIterator = function() {
|
||||
return this.__iterator__(false);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an iterator that iterates over the values or the keys in the map.
|
||||
* This throws an exception if the map was mutated since the iterator was
|
||||
* created.
|
||||
* @param {boolean=} opt_keys True to iterate over the keys. False to iterate
|
||||
* over the values. The default value is false.
|
||||
* @return {!goog.iter.Iterator} An iterator over the values or keys in the map.
|
||||
*/
|
||||
goog.structs.Map.prototype.__iterator__ = function(opt_keys) {
|
||||
// Clean up keys to minimize the risk of iterating over dead keys.
|
||||
this.cleanupKeysArray_();
|
||||
|
||||
var i = 0;
|
||||
var version = this.version_;
|
||||
var selfObj = this;
|
||||
|
||||
var newIter = new goog.iter.Iterator;
|
||||
newIter.next = function() {
|
||||
if (version != selfObj.version_) {
|
||||
throw Error('The map has changed since the iterator was created');
|
||||
}
|
||||
if (i >= selfObj.keys_.length) {
|
||||
throw goog.iter.StopIteration;
|
||||
}
|
||||
var key = selfObj.keys_[i++];
|
||||
return opt_keys ? key : selfObj.map_[key];
|
||||
};
|
||||
return newIter;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Safe way to test for hasOwnProperty. It even allows testing for
|
||||
* 'hasOwnProperty'.
|
||||
* @param {Object} obj The object to test for presence of the given key.
|
||||
* @param {*} key The key to check for.
|
||||
* @return {boolean} Whether the object has the key.
|
||||
* @private
|
||||
*/
|
||||
goog.structs.Map.hasKey_ = function(obj, key) {
|
||||
return Object.prototype.hasOwnProperty.call(obj, key);
|
||||
};
|
||||
@@ -0,0 +1,354 @@
|
||||
// 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 Generics method for collection-like classes and objects.
|
||||
*
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
*
|
||||
* This file contains functions to work with collections. It supports using
|
||||
* Map, Set, Array and Object and other classes that implement collection-like
|
||||
* methods.
|
||||
*/
|
||||
|
||||
|
||||
goog.provide('goog.structs');
|
||||
|
||||
goog.require('goog.array');
|
||||
goog.require('goog.object');
|
||||
|
||||
|
||||
// We treat an object as a dictionary if it has getKeys or it is an object that
|
||||
// isn't arrayLike.
|
||||
|
||||
|
||||
/**
|
||||
* Returns the number of values in the collection-like object.
|
||||
* @param {Object} col The collection-like object.
|
||||
* @return {number} The number of values in the collection-like object.
|
||||
*/
|
||||
goog.structs.getCount = function(col) {
|
||||
if (col.getCount && typeof col.getCount == 'function') {
|
||||
return col.getCount();
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return col.length;
|
||||
}
|
||||
return goog.object.getCount(col);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the values of the collection-like object.
|
||||
* @param {Object} col The collection-like object.
|
||||
* @return {!Array<?>} The values in the collection-like object.
|
||||
*/
|
||||
goog.structs.getValues = function(col) {
|
||||
if (col.getValues && typeof col.getValues == 'function') {
|
||||
return col.getValues();
|
||||
}
|
||||
if (goog.isString(col)) {
|
||||
return col.split('');
|
||||
}
|
||||
if (goog.isArrayLike(col)) {
|
||||
var rv = [];
|
||||
var l = col.length;
|
||||
for (var i = 0; i < l; i++) {
|
||||
rv.push(col[i]);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
return goog.object.getValues(col);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns the keys of the collection. Some collections have no notion of
|
||||
* keys/indexes and this function will return undefined in those cases.
|
||||
* @param {Object} col The collection-like object.
|
||||
* @return {!Array|undefined} The keys in the collection.
|
||||
*/
|
||||
goog.structs.getKeys = function(col) {
|
||||
if (col.getKeys && typeof col.getKeys == 'function') {
|
||||
return col.getKeys();
|
||||
}
|
||||
// if we have getValues but no getKeys we know this is a key-less collection
|
||||
if (col.getValues && typeof col.getValues == 'function') {
|
||||
return undefined;
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
var rv = [];
|
||||
var l = col.length;
|
||||
for (var i = 0; i < l; i++) {
|
||||
rv.push(i);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
return goog.object.getKeys(col);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the collection contains the given value. This is O(n) and uses
|
||||
* equals (==) to test the existence.
|
||||
* @param {Object} col The collection-like object.
|
||||
* @param {*} val The value to check for.
|
||||
* @return {boolean} True if the map contains the value.
|
||||
*/
|
||||
goog.structs.contains = function(col, val) {
|
||||
if (col.contains && typeof col.contains == 'function') {
|
||||
return col.contains(val);
|
||||
}
|
||||
if (col.containsValue && typeof col.containsValue == 'function') {
|
||||
return col.containsValue(val);
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.contains(/** @type {!Array<?>} */ (col), val);
|
||||
}
|
||||
return goog.object.containsValue(col, val);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the collection is empty.
|
||||
* @param {Object} col The collection-like object.
|
||||
* @return {boolean} True if empty.
|
||||
*/
|
||||
goog.structs.isEmpty = function(col) {
|
||||
if (col.isEmpty && typeof col.isEmpty == 'function') {
|
||||
return col.isEmpty();
|
||||
}
|
||||
|
||||
// We do not use goog.string.isEmptyOrWhitespace because here we treat the
|
||||
// string as
|
||||
// collection and as such even whitespace matters
|
||||
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.isEmpty(/** @type {!Array<?>} */ (col));
|
||||
}
|
||||
return goog.object.isEmpty(col);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Removes all the elements from the collection.
|
||||
* @param {Object} col The collection-like object.
|
||||
*/
|
||||
goog.structs.clear = function(col) {
|
||||
// NOTE(arv): This should not contain strings because strings are immutable
|
||||
if (col.clear && typeof col.clear == 'function') {
|
||||
col.clear();
|
||||
} else if (goog.isArrayLike(col)) {
|
||||
goog.array.clear(/** @type {IArrayLike<?>} */ (col));
|
||||
} else {
|
||||
goog.object.clear(col);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for each value in a collection. The function takes
|
||||
* three arguments; the value, the key and the collection.
|
||||
*
|
||||
* @param {S} col The collection-like object.
|
||||
* @param {function(this:T,?,?,S):?} f The function to call for every value.
|
||||
* This function takes
|
||||
* 3 arguments (the value, the key or undefined if the collection has no
|
||||
* notion of keys, and the collection) and the return value is irrelevant.
|
||||
* @param {T=} opt_obj The object to be used as the value of 'this'
|
||||
* within {@code f}.
|
||||
* @template T,S
|
||||
* @deprecated Use a more specific method, e.g. goog.array.forEach,
|
||||
* goog.object.forEach, or for-of.
|
||||
*/
|
||||
goog.structs.forEach = function(col, f, opt_obj) {
|
||||
if (col.forEach && typeof col.forEach == 'function') {
|
||||
col.forEach(f, opt_obj);
|
||||
} else if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj);
|
||||
} else {
|
||||
var keys = goog.structs.getKeys(col);
|
||||
var values = goog.structs.getValues(col);
|
||||
var l = values.length;
|
||||
for (var i = 0; i < l; i++) {
|
||||
f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for every value in the collection. When a call returns true,
|
||||
* adds the value to a new collection (Array is returned by default).
|
||||
*
|
||||
* @param {S} col The collection-like object.
|
||||
* @param {function(this:T,?,?,S):boolean} f The function to call for every
|
||||
* value. This function takes
|
||||
* 3 arguments (the value, the key or undefined if the collection has no
|
||||
* notion of keys, and the collection) and should return a Boolean. If the
|
||||
* return value is true the value is added to the result collection. If it
|
||||
* is false the value is not included.
|
||||
* @param {T=} opt_obj The object to be used as the value of 'this'
|
||||
* within {@code f}.
|
||||
* @return {!Object|!Array<?>} A new collection where the passed values are
|
||||
* present. If col is a key-less collection an array is returned. If col
|
||||
* has keys and values a plain old JS object is returned.
|
||||
* @template T,S
|
||||
*/
|
||||
goog.structs.filter = function(col, f, opt_obj) {
|
||||
if (typeof col.filter == 'function') {
|
||||
return col.filter(f, opt_obj);
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj);
|
||||
}
|
||||
|
||||
var rv;
|
||||
var keys = goog.structs.getKeys(col);
|
||||
var values = goog.structs.getValues(col);
|
||||
var l = values.length;
|
||||
if (keys) {
|
||||
rv = {};
|
||||
for (var i = 0; i < l; i++) {
|
||||
if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {
|
||||
rv[keys[i]] = values[i];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// We should not use goog.array.filter here since we want to make sure that
|
||||
// the index is undefined as well as make sure that col is passed to the
|
||||
// function.
|
||||
rv = [];
|
||||
for (var i = 0; i < l; i++) {
|
||||
if (f.call(opt_obj, values[i], undefined, col)) {
|
||||
rv.push(values[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls a function for every value in the collection and adds the result into a
|
||||
* new collection (defaults to creating a new Array).
|
||||
*
|
||||
* @param {S} col The collection-like object.
|
||||
* @param {function(this:T,?,?,S):V} f The function to call for every value.
|
||||
* This function takes 3 arguments (the value, the key or undefined if the
|
||||
* collection has no notion of keys, and the collection) and should return
|
||||
* something. The result will be used as the value in the new collection.
|
||||
* @param {T=} opt_obj The object to be used as the value of 'this'
|
||||
* within {@code f}.
|
||||
* @return {!Object<V>|!Array<V>} A new collection with the new values. If
|
||||
* col is a key-less collection an array is returned. If col has keys and
|
||||
* values a plain old JS object is returned.
|
||||
* @template T,S,V
|
||||
*/
|
||||
goog.structs.map = function(col, f, opt_obj) {
|
||||
if (typeof col.map == 'function') {
|
||||
return col.map(f, opt_obj);
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj);
|
||||
}
|
||||
|
||||
var rv;
|
||||
var keys = goog.structs.getKeys(col);
|
||||
var values = goog.structs.getValues(col);
|
||||
var l = values.length;
|
||||
if (keys) {
|
||||
rv = {};
|
||||
for (var i = 0; i < l; i++) {
|
||||
rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);
|
||||
}
|
||||
} else {
|
||||
// We should not use goog.array.map here since we want to make sure that
|
||||
// the index is undefined as well as make sure that col is passed to the
|
||||
// function.
|
||||
rv = [];
|
||||
for (var i = 0; i < l; i++) {
|
||||
rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls f for each value in a collection. If any call returns true this returns
|
||||
* true (without checking the rest). If all returns false this returns false.
|
||||
*
|
||||
* @param {S} col The collection-like object.
|
||||
* @param {function(this:T,?,?,S):boolean} f The function to call for every
|
||||
* value. This function takes 3 arguments (the value, the key or undefined
|
||||
* if the collection has no notion of keys, and the collection) and should
|
||||
* return a boolean.
|
||||
* @param {T=} opt_obj The object to be used as the value of 'this'
|
||||
* within {@code f}.
|
||||
* @return {boolean} True if any value passes the test.
|
||||
* @template T,S
|
||||
*/
|
||||
goog.structs.some = function(col, f, opt_obj) {
|
||||
if (typeof col.some == 'function') {
|
||||
return col.some(f, opt_obj);
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj);
|
||||
}
|
||||
var keys = goog.structs.getKeys(col);
|
||||
var values = goog.structs.getValues(col);
|
||||
var l = values.length;
|
||||
for (var i = 0; i < l; i++) {
|
||||
if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Calls f for each value in a collection. If all calls return true this return
|
||||
* true this returns true. If any returns false this returns false at this point
|
||||
* and does not continue to check the remaining values.
|
||||
*
|
||||
* @param {S} col The collection-like object.
|
||||
* @param {function(this:T,?,?,S):boolean} f The function to call for every
|
||||
* value. This function takes 3 arguments (the value, the key or
|
||||
* undefined if the collection has no notion of keys, and the collection)
|
||||
* and should return a boolean.
|
||||
* @param {T=} opt_obj The object to be used as the value of 'this'
|
||||
* within {@code f}.
|
||||
* @return {boolean} True if all key-value pairs pass the test.
|
||||
* @template T,S
|
||||
*/
|
||||
goog.structs.every = function(col, f, opt_obj) {
|
||||
if (typeof col.every == 'function') {
|
||||
return col.every(f, opt_obj);
|
||||
}
|
||||
if (goog.isArrayLike(col) || goog.isString(col)) {
|
||||
return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj);
|
||||
}
|
||||
var keys = goog.structs.getKeys(col);
|
||||
var values = goog.structs.getValues(col);
|
||||
var l = values.length;
|
||||
for (var i = 0; i < l; i++) {
|
||||
if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,580 @@
|
||||
// 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 Rendering engine detection.
|
||||
* @see <a href="http://www.useragentstring.com/">User agent strings</a>
|
||||
* For information on the browser brand (such as Safari versus Chrome), see
|
||||
* goog.userAgent.product.
|
||||
* @author arv@google.com (Erik Arvidsson)
|
||||
* @see ../demos/useragent.html
|
||||
*/
|
||||
|
||||
goog.provide('goog.userAgent');
|
||||
|
||||
goog.require('goog.labs.userAgent.browser');
|
||||
goog.require('goog.labs.userAgent.engine');
|
||||
goog.require('goog.labs.userAgent.platform');
|
||||
goog.require('goog.labs.userAgent.util');
|
||||
goog.require('goog.reflect');
|
||||
goog.require('goog.string');
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is IE.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_IE', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is EDGE.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_EDGE', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is GECKO.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_GECKO', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is WEBKIT.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_WEBKIT', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is a
|
||||
* mobile device running WebKit e.g. iPhone or Android.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether we know at compile-time that the browser is OPERA.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_OPERA', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the
|
||||
* {@code goog.userAgent.isVersionOrHigher}
|
||||
* function will return true for any version.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);
|
||||
|
||||
|
||||
/**
|
||||
* Whether we know the browser engine at compile-time.
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||
|
||||
goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||
|
||||
goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||
|
||||
goog.userAgent.ASSUME_OPERA;
|
||||
|
||||
|
||||
/**
|
||||
* Returns the userAgent string for the current browser.
|
||||
*
|
||||
* @return {string} The userAgent string.
|
||||
*/
|
||||
goog.userAgent.getUserAgentString = function() {
|
||||
return goog.labs.userAgent.util.getUserAgent();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* TODO(nnaze): Change type to "Navigator" and update compilation targets.
|
||||
* @return {?Object} The native navigator object.
|
||||
*/
|
||||
goog.userAgent.getNavigator = function() {
|
||||
// Need a local navigator reference instead of using the global one,
|
||||
// to avoid the rare case where they reference different objects.
|
||||
// (in a WorkerPool, for example).
|
||||
return goog.global['navigator'] || null;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is Opera.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_OPERA :
|
||||
goog.labs.userAgent.browser.isOpera();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is Internet Explorer.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_IE :
|
||||
goog.labs.userAgent.browser.isIE();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is Microsoft Edge.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_EDGE :
|
||||
goog.labs.userAgent.engine.isEdge();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is MS Internet Explorer or MS Edge.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is Gecko. Gecko is the rendering engine used by
|
||||
* Mozilla, Firefox, and others.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_GECKO :
|
||||
goog.labs.userAgent.engine.isGecko();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is WebKit. WebKit is the rendering engine that
|
||||
* Safari, Android and others use.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :
|
||||
goog.labs.userAgent.engine.isWebKit();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a mobile device.
|
||||
*
|
||||
* This is a separate function so that the logic can be tested.
|
||||
*
|
||||
* TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().
|
||||
*
|
||||
* @return {boolean} Whether the user agent is running on a mobile device.
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.isMobile_ = function() {
|
||||
return goog.userAgent.WEBKIT &&
|
||||
goog.labs.userAgent.util.matchUserAgent('Mobile');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a mobile device.
|
||||
*
|
||||
* TODO(nnaze): Consider deprecating MOBILE when labs.userAgent
|
||||
* is promoted as the gecko/webkit logic is likely inaccurate.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.MOBILE =
|
||||
goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();
|
||||
|
||||
|
||||
/**
|
||||
* Used while transitioning code to use WEBKIT instead.
|
||||
* @type {boolean}
|
||||
* @deprecated Use {@link goog.userAgent.product.SAFARI} instead.
|
||||
* TODO(nicksantos): Delete this from goog.userAgent.
|
||||
*/
|
||||
goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
|
||||
|
||||
|
||||
/**
|
||||
* @return {string} the platform (operating system) the user agent is running
|
||||
* on. Default to empty string because navigator.platform may not be defined
|
||||
* (on Rhino, for example).
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.determinePlatform_ = function() {
|
||||
var navigator = goog.userAgent.getNavigator();
|
||||
return navigator && navigator.platform || '';
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The platform (operating system) the user agent is running on. Default to
|
||||
* empty string because navigator.platform may not be defined (on Rhino, for
|
||||
* example).
|
||||
* @type {string}
|
||||
*/
|
||||
goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on a Macintosh operating
|
||||
* system.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_MAC', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on a Windows operating
|
||||
* system.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_WINDOWS', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on a Linux operating
|
||||
* system.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_LINUX', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on a X11 windowing
|
||||
* system.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_X11', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on Android.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_ANDROID', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on an iPhone.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_IPHONE', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on an iPad.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_IPAD', false);
|
||||
|
||||
|
||||
/**
|
||||
* @define {boolean} Whether the user agent is running on an iPod.
|
||||
*/
|
||||
goog.define('goog.userAgent.ASSUME_IPOD', false);
|
||||
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||
|
||||
goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||
|
||||
goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||
|
||||
goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||
|
||||
goog.userAgent.ASSUME_IPOD;
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a Macintosh operating system.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_MAC :
|
||||
goog.labs.userAgent.platform.isMacintosh();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a Windows operating system.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_WINDOWS :
|
||||
goog.labs.userAgent.platform.isWindows();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is Linux per the legacy behavior of
|
||||
* goog.userAgent.LINUX, which considered ChromeOS to also be
|
||||
* Linux.
|
||||
* @return {boolean}
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.isLegacyLinux_ = function() {
|
||||
return goog.labs.userAgent.platform.isLinux() ||
|
||||
goog.labs.userAgent.platform.isChromeOS();
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a Linux operating system.
|
||||
*
|
||||
* Note that goog.userAgent.LINUX considers ChromeOS to be Linux,
|
||||
* while goog.labs.userAgent.platform considers ChromeOS and
|
||||
* Linux to be different OSes.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_LINUX :
|
||||
goog.userAgent.isLegacyLinux_();
|
||||
|
||||
|
||||
/**
|
||||
* @return {boolean} Whether the user agent is an X11 windowing system.
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.isX11_ = function() {
|
||||
var navigator = goog.userAgent.getNavigator();
|
||||
return !!navigator &&
|
||||
goog.string.contains(navigator['appVersion'] || '', 'X11');
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on a X11 windowing system.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_X11 :
|
||||
goog.userAgent.isX11_();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on Android.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_ANDROID :
|
||||
goog.labs.userAgent.platform.isAndroid();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on an iPhone.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_IPHONE :
|
||||
goog.labs.userAgent.platform.isIphone();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on an iPad.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_IPAD :
|
||||
goog.labs.userAgent.platform.isIpad();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on an iPod.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
goog.userAgent.ASSUME_IPOD :
|
||||
goog.labs.userAgent.platform.isIpod();
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent is running on iOS.
|
||||
* @type {boolean}
|
||||
*/
|
||||
goog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?
|
||||
(goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||
|
||||
goog.userAgent.ASSUME_IPOD) :
|
||||
goog.labs.userAgent.platform.isIos();
|
||||
|
||||
/**
|
||||
* @return {string} The string that describes the version number of the user
|
||||
* agent.
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.determineVersion_ = function() {
|
||||
// All browsers have different ways to detect the version and they all have
|
||||
// different naming schemes.
|
||||
// version is a string rather than a number because it may contain 'b', 'a',
|
||||
// and so on.
|
||||
var version = '';
|
||||
var arr = goog.userAgent.getVersionRegexResult_();
|
||||
if (arr) {
|
||||
version = arr ? arr[1] : '';
|
||||
}
|
||||
|
||||
if (goog.userAgent.IE) {
|
||||
// IE9 can be in document mode 9 but be reporting an inconsistent user agent
|
||||
// version. If it is identifying as a version lower than 9 we take the
|
||||
// documentMode as the version instead. IE8 has similar behavior.
|
||||
// It is recommended to set the X-UA-Compatible header to ensure that IE9
|
||||
// uses documentMode 9.
|
||||
var docMode = goog.userAgent.getDocumentMode_();
|
||||
if (docMode != null && docMode > parseFloat(version)) {
|
||||
return String(docMode);
|
||||
}
|
||||
}
|
||||
|
||||
return version;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {?Array|undefined} The version regex matches from parsing the user
|
||||
* agent string. These regex statements must be executed inline so they can
|
||||
* be compiled out by the closure compiler with the rest of the useragent
|
||||
* detection logic when ASSUME_* is specified.
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.getVersionRegexResult_ = function() {
|
||||
var userAgent = goog.userAgent.getUserAgentString();
|
||||
if (goog.userAgent.GECKO) {
|
||||
return /rv\:([^\);]+)(\)|;)/.exec(userAgent);
|
||||
}
|
||||
if (goog.userAgent.EDGE) {
|
||||
return /Edge\/([\d\.]+)/.exec(userAgent);
|
||||
}
|
||||
if (goog.userAgent.IE) {
|
||||
return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(userAgent);
|
||||
}
|
||||
if (goog.userAgent.WEBKIT) {
|
||||
// WebKit/125.4
|
||||
return /WebKit\/(\S+)/.exec(userAgent);
|
||||
}
|
||||
if (goog.userAgent.OPERA) {
|
||||
// If none of the above browsers were detected but the browser is Opera, the
|
||||
// only string that is of interest is 'Version/<number>'.
|
||||
return /(?:Version)[ \/]?(\S+)/.exec(userAgent);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @return {number|undefined} Returns the document mode (for testing).
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.getDocumentMode_ = function() {
|
||||
// NOTE(user): goog.userAgent may be used in context where there is no DOM.
|
||||
var doc = goog.global['document'];
|
||||
return doc ? doc['documentMode'] : undefined;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* The version of the user agent. This is a string because it might contain
|
||||
* 'b' (as in beta) as well as multiple dots.
|
||||
* @type {string}
|
||||
*/
|
||||
goog.userAgent.VERSION = goog.userAgent.determineVersion_();
|
||||
|
||||
|
||||
/**
|
||||
* Compares two version numbers.
|
||||
*
|
||||
* @param {string} v1 Version of first item.
|
||||
* @param {string} v2 Version of second item.
|
||||
*
|
||||
* @return {number} 1 if first argument is higher
|
||||
* 0 if arguments are equal
|
||||
* -1 if second argument is higher.
|
||||
* @deprecated Use goog.string.compareVersions.
|
||||
*/
|
||||
goog.userAgent.compare = function(v1, v2) {
|
||||
return goog.string.compareVersions(v1, v2);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Cache for {@link goog.userAgent.isVersionOrHigher}.
|
||||
* Calls to compareVersions are surprisingly expensive and, as a browser's
|
||||
* version number is unlikely to change during a session, we cache the results.
|
||||
* @const
|
||||
* @private
|
||||
*/
|
||||
goog.userAgent.isVersionOrHigherCache_ = {};
|
||||
|
||||
|
||||
/**
|
||||
* Whether the user agent version is higher or the same as the given version.
|
||||
* NOTE: When checking the version numbers for Firefox and Safari, be sure to
|
||||
* use the engine's version, not the browser's version number. For example,
|
||||
* Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.
|
||||
* Opera and Internet Explorer versions match the product release number.<br>
|
||||
* @see <a href="http://en.wikipedia.org/wiki/Safari_version_history">
|
||||
* Webkit</a>
|
||||
* @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a>
|
||||
*
|
||||
* @param {string|number} version The version to check.
|
||||
* @return {boolean} Whether the user agent version is higher or the same as
|
||||
* the given version.
|
||||
*/
|
||||
goog.userAgent.isVersionOrHigher = function(version) {
|
||||
return goog.userAgent.ASSUME_ANY_VERSION ||
|
||||
goog.reflect.cache(
|
||||
goog.userAgent.isVersionOrHigherCache_, version, function() {
|
||||
return goog.string.compareVersions(
|
||||
goog.userAgent.VERSION, version) >= 0;
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Deprecated alias to {@code goog.userAgent.isVersionOrHigher}.
|
||||
* @param {string|number} version The version to check.
|
||||
* @return {boolean} Whether the user agent version is higher or the same as
|
||||
* the given version.
|
||||
* @deprecated Use goog.userAgent.isVersionOrHigher().
|
||||
*/
|
||||
goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;
|
||||
|
||||
|
||||
/**
|
||||
* Whether the IE effective document mode is higher or the same as the given
|
||||
* document mode version.
|
||||
* NOTE: Only for IE, return false for another browser.
|
||||
*
|
||||
* @param {number} documentMode The document mode version to check.
|
||||
* @return {boolean} Whether the IE effective document mode is higher or the
|
||||
* same as the given version.
|
||||
*/
|
||||
goog.userAgent.isDocumentModeOrHigher = function(documentMode) {
|
||||
return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Deprecated alias to {@code goog.userAgent.isDocumentModeOrHigher}.
|
||||
* @param {number} version The version to check.
|
||||
* @return {boolean} Whether the IE effective document mode is higher or the
|
||||
* same as the given version.
|
||||
* @deprecated Use goog.userAgent.isDocumentModeOrHigher().
|
||||
*/
|
||||
goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;
|
||||
|
||||
|
||||
/**
|
||||
* For IE version < 7, documentMode is undefined, so attempt to use the
|
||||
* CSS1Compat property to see if we are in standards mode. If we are in
|
||||
* standards mode, treat the browser version as the document mode. Otherwise,
|
||||
* IE is emulating version 5.
|
||||
* @type {number|undefined}
|
||||
* @const
|
||||
*/
|
||||
goog.userAgent.DOCUMENT_MODE = (function() {
|
||||
var doc = goog.global['document'];
|
||||
var mode = goog.userAgent.getDocumentMode_();
|
||||
if (!doc || !goog.userAgent.IE) {
|
||||
return undefined;
|
||||
}
|
||||
return mode || (doc['compatMode'] == 'CSS1Compat' ?
|
||||
parseInt(goog.userAgent.VERSION, 10) :
|
||||
5);
|
||||
})();
|
||||
Reference in new issue
Block a user